我有这样的代码:
active = True
print("Hello, this is the pricing system for the theater.")
print("Depending on your age, your pricing will vary.")
print("Please type 'exit' to termiante the program")
toddler = "Below 3 = Free."
kid = "3-2 = $10"
big_kid = "12+ = $15"
prompt = "Please enter your age: "
while active:
message = input(prompt)
if message == "exit":
break
if message != type(int):
print("Int only")
continue
message = int(message)
if message < 3:
print(toddler)
elif message > 3 and message < 12:
print(kid)
else:
print(big_kid)我基本上是想告诉python,如果输入的值不是整数,请返回开始,输入一个int。然而,即使用户确实放置了int,它仍然告诉我“仅为int”。我在这里做错什么了?
发布于 2022-05-11 17:56:54
尝试使用message.isnumeric()而不是使用!=操作符检查它
发布于 2022-05-11 17:57:43
条件type(int)不能为真,因为您有来自input的str,您宁愿尝试str.isdigit()
while True:
message = input(prompt)
if message == "exit":
break
if message.isdigit():
print("Int only")
continue
message = int(message)
if message < 3:
print(toddler)
elif 3 <= message < 12:
print(kid)
else:
print(big_kid)发布于 2022-05-11 17:58:27
您也可以使用try-except块。
active = True
print("Hello, this is the pricing system for the theater.")
print("Depending on your age, your pricing will vary.")
print("Please type 'exit' to termiante the program")
toddler = "Below 3 = Free."
kid = "3-2 = $10"
big_kid = "12+ = $15"
prompt = "Please enter your age: "
while active:
message = input(prompt)
print(message)
if message == "exit":
break
try:
int(message)
except ValueError:
print("Int only")
continue
message = int(message)
if message < 3:
print(toddler)
elif message > 3 and message < 12:
print(kid)
else:
print(big_kid)https://stackoverflow.com/questions/72205525
复制相似问题