ValueError:以10为基数的int()的文本无效:“stop”

2024-04-24 08:16:39 发布

您现在位置:Python中文网/ 问答频道 /正文

每次我尝试编写代码时,它都会工作,但当我输入'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

Tags: oryouifhaveinttoostopprint
3条回答

您正在尝试将字符串“stop”转换为整数。该字符串没有有效的整数表示形式,因此会出现该错误。你应该把

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

作为第一次检查

另一个建议是对输入使用小写,然后检查小写的“stop”。这样你只需检查一次,它就会捕获“停止”、“停止”、“停止”等。。

if str(guess).lower() == 'stop':
break

这里有一个更像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)

传递给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

相关问题 更多 >