因此,这是一个小猜谜游戏,您有9次尝试猜测0到100之间的数字。但是,如果用户输入字符串值,则会得到ValueError
。如何处理ValueError
?
for Guesses in range(9):
print('Take a guess.')
Guess = int(input())
if Guess < 0:
print('Please enter a positive number')
elif Guess > 100:
print('The number is only between 0 and 100')
elif Guess < Number:
print('Higher...')
elif Guess > Number:
print('Lower...')
else:
print('Spot on!')
break # Guess was correct
最佳答案
使用try
和except
。尝试这个:
for Guesses in range(9):
print('Take a guess.')
while True:
try:
Guess = int(input())
break
except ValueError:
print("Try again. That is not a number")
if Guess < 0:
print('Please enter a positive number')
elif Guess > 100:
print('The number is only between 0 and 100')
elif Guess < Number:
print('Higher...')
elif Guess > Number:
print('Lower...')
else:
print('Spot on!')
break # Guess was correct
一些进步:
for Guesses in range(9):
print('Take a guess.')
while True:
try:
Guess = int(input())
if (0 > Guess):
print('Please enter a positive number')
elif (100 < Guess):
print('The number is only between 0 and 100')
else:
break
except ValueError:
print("Try again. That is not a number")
elif Guess < Number:
print('Higher...')
elif Guess > Number:
print('Lower...')
else:
print('Spot on!')
break # Guess was correct
另外,建议变量名不要大写。
关于python-3.x - 如何处理ValueError?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/61104379/