【发布时间】:2020-08-24 08:54:35
【问题描述】:
这是我在这个社区的第一篇文章,当然我是初学者。我期待着有一天我可以帮助别人。无论如何,这是一个简单的代码,我想要它,以便在用户输入字符串时出现错误。不幸的是,它没有按照我想要的方式执行,这是代码:
number = 1
guess = int(input('Guess this number: '))
while True:
try:
if guess > number:
print("Number is too high, go lower, try again")
guess = int(input('Guess this number: '))
elif guess < number:
print("Too low, go higher, try again")
guess = int(input('Guess this number: '))
else:
print("That is correct")
break
except (SyntaxError, ValueError):
print("You can only enetr numbers, try again")
当程序执行时,它要求我“猜猜这个数字:”,当我写任何字符串时,例如“d”,它给出了错误:
Guess this number: d
Traceback (most recent call last):
File "Numberguess.py", line 5, in <module>
guess = int(input('Guess this number: '))
ValueError: invalid literal for int() with base 10: 'd'
感谢您的时间和支持。
【问题讨论】:
-
int 函数需要一个表达式,因此它是一个有效的整数,因为它不是一个有效的数字,所以它会引发错误。如果你想要一个 ascii,那么使用 ord() 函数。
标签: python if-statement exception user-input