3 回答

TA贡献1786条经验 获得超11个赞
这是一个更加Pythonic(Python 3)的版本。
def guessing_game(random_num):
tries = 3
print("Guess a number between 1 - 10, you have 3 tries, or type 'stop' to quit")
while True:
guess = input("Your number: ")
try:
guess = int(guess)
except (TypeError, ValueError):
if guess.lower() == 'stop' :
return
else:
print("Invalid value '%s'" % guess)
continue
if guess == random_num:
print('Correct')
return
elif guess < random_num:
print('Too low')
else:
print('Too high')
tries -= 1
if tries == 0:
print('You have no more tries')
return
print('You have %s guesses left' % tries)

TA贡献1909条经验 获得超7个赞
您正在尝试将字符串“ stop”转换为整数。该字符串没有有效的整数表示形式,因此会出现该错误。你应该放
if str(guess) == 'stop' or str(guess) == 'Stop':
break
作为第一张支票
另一个建议是在输入上使用小写字母,然后检查小写字母“ stop”。这样,您只需要检查一次,它将捕获“停止”,“停止”,“断点”等。
if str(guess).lower() == 'stop':
break
添加回答
举报