【发布时间】:2014-11-09 17:36:32
【问题描述】:
我正在为我们将军事时间转换为标准时间的课程做作业,并认为我会很聪明地拥有单独的函数来获取输入和检查输入 - 我的理由是如果 check_input 函数失败,我可以继续循环通过 get_inputs 函数,直到用户以正确的格式输入。
但是,当我输入像“jklfd”这样的乱码时,我的 get_input 函数会崩溃,因为它无法将其转换为函数的一部分。
在这种情况下是否有更好的方法来处理异常?此外,任何一般性提示或建议都将受到赞赏。提前感谢您的帮助!
__author__ = 'Ethan'
#This program takes input in military time in the format hour:minutes and outputs
#the time in standard time hour:minute AM/PM
def main():
print_intro()
while True:
mil_h, m = get_inputs()
if check_input(mil_h,m):
break
reformat_time(mil_h,m)
def print_intro():
print("This program takes input as military time from user")
print("in format hour:minute ex. 23:34")
print("and outputs the time in standard AM/PM format")
print("ex. from above 11:34 PM")
def get_inputs():
raw = input("Enter time: ")
time_list = raw.split(":")
mil_h = int(time_list[0])
m = int(time_list[1])
return mil_h, m
def check_input(mil_h,m):
try:
if mil_h >= 24 or mil_h <0:
print("Time must be in format hh:mm")
print("Hour must be in range 0 to 23")
return False
elif m >= 60 or m <0:
print("Time must be in format hh:mm")
print("Minute must be in range 0 to 59")
return False
else:
return True
except:
print("Input must be in military time in format hh:mm")
def reformat_time(mil_h,m):
am_pm = "AM"
if mil_h == 12:
am_pm = "PM"
stand_h = 12
elif mil_h > 12:
am_pm = "PM"
stand_h = mil_h % 12
else:
stand_h = mil_h
print(stand_h,':', m,' ', am_pm, sep='')
main()
【问题讨论】:
标签: python-3.x exception-handling