我正在尝试从用户那里得到小时和分钟,但是当我输入一个字母数字超过允许的用户范围的数字时,用户返回一个无类型值。我想从用户那里得到号码。我知道解决方案是显而易见的,但由于某种原因我无法弄明白。
def get_hours():
h = input("Hour:")
try:
if len(h) == 0:
return 0
else:
h = int(h)
if 0 <= h <= 24:
print(h)
print(type(h))
return h
else:
print("Enter Hours between 0 and 24")
get_hours()
except ValueError:
print("Enter Hour example = 16")
get_hours()
def get_mins():
m = input("Minutes:")
try:
if len(m) == 0:
return 0
else:
m = int(m)
if 0 <= m <= 60:
print(m)
print(type(m))
return m
else:
print("Enter minutes between 0 and 60")
get_mins()
except ValueError:
print("Enter Minutes example = 23")
get_mins()
def get_activity():
flag = True
while flag:
ui = input("Enter a brief summary of what you will be doing? \n:")
if len(ui) == 0:
flag = True
else:
return ui
def main():
data = []
time = []
activity = []
hour = get_hours()
print(type(hour))
print("Hours: " +str(hour))
while hour == None:
hour = get_hours()
mins = get_mins()
print(type(mins))
print("Mins: " + str(mins))
while mins == None:
mins = get_mins()
main()
这就是我想要的:
Hours: 10
Minutes: 53
这是我输入以下输入时得到的结果
Hour:1a
Enter Hour example = 16
Hour:231
Enter Hours between 0 and 24
Hour:2
2
<class 'int'>
<class 'NoneType'>
Hours: None
Hour:2a
Enter Hour example = 16
Hour:2
2
<class 'int'>
Hour:2a
Enter Hour example = 16
Hour:2
2
<class 'int'>
Hour:2
2
<class 'int'>
Minutes:2a
Enter Minutes example = 23
Minutes:222
Enter minutes between 0 and 60
Minutes:2a
Enter Minutes example = 23
Minutes:2
2
<class 'int'>
<class 'NoneType'>
Mins: None
Minutes:2
2
<class 'int'>
答案 0 :(得分:1)
所有路径都需要引导您自己的return
声明,以免获得None
。
例如,在这里你没有返回一个值。
else:
print("Enter Hours between 0 and 24")
get_hours()
# return None # this is implicit
建议:使用正确的循环,而不是递归,但如果这样做,则应返回递归的结果。
else:
print("Enter Hours between 0 and 24")
return get_hours() # this is explicit