您好,这是我正在处理的代码的一部分。我想知道是否有办法检测输入的输入是否为字母并给出响应。我需要减去时间,所以我将它转换为int,但如果除了int之外的任何东西都是类型,如果给我一个错误。
def Continue():
time = int(input("What time is it?: "))
if time > 12:
print ("I'm sorry, just the hour, I don't need anymore than that.")
Continue()
else:
print ("It's %d" % time + "?!")
time = time - 1
print ("I'm late!\nI'm sorry I have to go!\nI'm sure your leg is fine just walk it off!")
print ("I was suppose to be there at %d" % time, "I'm an hour late!")
答案 0 :(得分:0)
这样做你想要的:
def Continue():
try:
time = int(input("What time is it?: "))
except ValueError:
print('Invalid input.')
print('Please enter a number between 1 and 12.')
Continue()
if time > 12:
print("I'm sorry, just the hour, I don't need anymore than that.")
Continue()
else:
print("It's %d" % time + "?!")
time = time - 1
print ("I'm late!\nI'm sorry I have to go!\nI'm sure your leg is fine just walk it off!")
print ("I was suppose to be there at %d" % time, "I'm an hour late!")
您可以使用try
- except
声明。如果转换为整数失败,Python将引发ValueError
。在这种情况下,您使用except
捕获异常,告诉用户输入错误,然后再次调用您的函数。
答案 1 :(得分:0)
解决此问题的一种方法是不立即将输入转换为int,而是创建一个if else语句,用于检查输入是否为数字。如果是数字,则可以将变量转换为int。