【发布时间】:2018-11-06 15:03:13
【问题描述】:
当我在创建一个变量并放置一段时间后尝试返回一个值 True、try/except 命令时,该变量不会返回该值。我正在尝试将这个“开始”全球化,以便可以使用它。
def start_time():
while True:
try:
starting = int(input("Please enter a starting hour(HH): "))
if starting < 0:
print("There are no negative hours!")
elif starting > 24:
print("There are only 24 hours in a day!")
else:
break
except ValueError:
print("Please enter in a correct format (HH)")
return starting
def end_time():
while True:
try:
ending = int(input("Please enter an ending hour (HH): "))
if ending < starting:
print("You can only plan a day!")
elif ending < 0:
print("There are only 24 hours in a day!")
elif ending > 24:
print("There are only 24 hours in a day!")
else:
break
except ValueError:
print("Please enter in a correct format (HH)")
return ending
#obtain starting and ending time
start_time()
end_time()
#confirm starting and ending time
谢谢
【问题讨论】:
-
当输入正确时,你永远不会跳出 while 循环。将
pass替换为break(或者只是提前返回)。
标签: python while-loop return global try-except