gpt4 book ai didi

python - 值错误 : invalid literal for int() with base 10: 'stop'

转载 作者:太空狗 更新时间:2023-10-30 01:49:05 24 4
gpt4 key购买 nike

每次我尝试编写代码时,它都能正常工作,但当我输入 'stop' 时,它会给我一个错误:

ValueError: invalid literal for int() with base 10: 'stop'

def guessingGame():
global randomNum
guessTry = 3

while True:
guess = input('Guess a Number between 1 - 10, You have 3 Tries, or Enter Stop: ')
if int(guess) == randomNum:
print('Correct')
break

if int(guess) < randomNum:
print('Too Low')
guessTry = guessTry - 1
print('You have, ' + str(guessTry) + ' Guesses Left')

if int(guess) > randomNum:
print('Too High')
guessTry = guessTry - 1
print('You have, ' + str(guessTry) + ' Guesses Left')

if guessTry == 0:
print('You have no more tries')
return

if str(guess) == 'stop' or str(guess) == 'Stop':
break

最佳答案

传递给 int() 的字符串应该只包含数字:

>>> int("stop")
Traceback (most recent call last):
File "<ipython-input-114-e5503af2dc1c>", line 1, in <module>
int("stop")
ValueError: invalid literal for int() with base 10: 'stop'

快速解决方法是使用 exception handling这里:

def guessingGame():
global randomNum
global userScore
guessTry = 3

while True:
guess = input('Guess a Number between 1 - 10, You have 3 Tries, or Enter Stop: ')
try:
if int(guess) == randomNum:
print('Correct')
break

if int(guess) < randomNum:
print('Too Low')
guessTry = guessTry - 1
print('You have, ' + str(guessTry) + ' Guesses Left')

if int(guess) > randomNum:
print('Too High')
guessTry = guessTry - 1
print('You have, ' + str(guessTry) + ' Guesses Left')

if guessTry == 0:
print('You have no more tries')
return
except ValueError:
#no need of str() here
if guess.lower() == 'stop':
break
guessingGame()

并且您可以使用 guess.lower() == 'stop' 来匹配“stop”的任何大小写组合:

>>> "Stop".lower() == "stop"
True
>>> "SToP".lower() == "stop"
True
>>> "sTOp".lower() == "stop"
True

关于python - 值错误 : invalid literal for int() with base 10: 'stop' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16742432/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com