ValueError:基数为10的int()的无效文字:'stop'

Chr*_*ett 4 python string int

每次我尝试编码它都有效,但当我输入'stop'它时会给我一个错误:

ValueError:基数为10的int()的无效文字:'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
Run Code Online (Sandbox Code Playgroud)

Ash*_*ary 12

传递给的字符串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'
Run Code Online (Sandbox Code Playgroud)

快速解决方法是在此处使用异常处理:

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()
Run Code Online (Sandbox Code Playgroud)

您可以使用guess.lower() == 'stop'匹配"stop"的任何大写 - 小写组合:

>>> "Stop".lower() == "stop"
True
>>> "SToP".lower() == "stop"
True
>>> "sTOp".lower() == "stop"
True
Run Code Online (Sandbox Code Playgroud)