ValueError:int()的基数为10的无效文字:'stop' [英] ValueError: invalid literal for int() with base 10: 'stop'

查看:750
本文介绍了ValueError:int()的基数为10的无效文字:'stop'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每次我试用我的代码都有效但当我输入'stop'时它会给我一个错误:

Every time I try me code it works but when I type in 'stop' it gives me an error:


ValueError:基数为10的int()的无效文字:'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()的字符串应该只包含数字:

The string passed to int() should only contain digits:

>>> 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'

快速修复将使用异常处理这里:

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的任何大写 - 小写组合:

And you can use guess.lower() == 'stop' to match any uppercase-lowercase combination of "stop":

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

这篇关于ValueError:int()的基数为10的无效文字:'stop'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆