在我的练习中,我遇到了一个如何创建函数的问题
编写一个名为approxTime的函数,将两个整数作为输入:hour是1到12之间的整数;minute是0到59之间的整数。函数应将时间打印到最近的季度 一小时。以下是一些示例:
>>> approxTime(3, 18)
The time is about quarter past three
>>> approxTime(3, 28)
The time is about half past three
>>> approxTime(8,50)
The time is about quarter to nine
>>> approxTime(8,55)
The time is about nine o’clock
有什么办法吗?你知道吗
我用了另一种方式:
def approxTimehour(h):
try:
Hour = int(h)
except:
print("This is not a integer, please try again")
return(None)
if h<1:
print("You cannot input Hour under 1")
return(None)
if h>12:
print ("You cannot input Hour over 12")
return(None)
return Hour
def approxTimeMin(m):
try:
Minute = int(m)
except:
print("This is not a integer, please try again")
return(None)
if m<0:
print("You cannot input Minute under 0")
return(None)
if m>59:
print ("You cannot input Minute over 59")
return(None)
return Minute
PT1 = None
while PT1==None:
h = int(input("Please input the hour (1-12): "))
PT1 = approxTimehour(h)
print("")
PT2 = None
while PT2==None:
m = int(input("Please input the Minute (1-59): "))
PT2 = approxTimeMin(m)
print("The time is",h,":",m)
if m<15:
print ("The time is ",h,"o'clock")
elif m>=15 and m<26:
print ("The time is about quarter past",h)
elif m>25 and m<36:
print ("The time is about half past",h)
elif m>35 and m<51:
print ("The time is about quarter to",h+1)
elif m>50 and m<60:
print ("The time is about",h+1,"o'clock")
我想知道如何用另一种方式去做
另一个确定你也在哪个时间(0、15、30、45、60[点,一刻一刻,半点,一刻到一刻,点])的好方法是使用
min
来确定最接近的值:从这里开始,你应该做两件事:
确定是否需要添加一个小时(对于45和60),因为它们是四舍五入的)。
将数字解析为文本,这可以使用dicts轻松完成:
用这种方法我可以写10行的函数。Here如果你感兴趣的话(不想直接发布,这样你就可以自己尝试了)。他说
少一点暗示多一点解决方案:
相关问题 更多 >
编程相关推荐