python-3.x - 如何处理ValueError?

标签 python-3.x error-handling

因此,这是一个小猜谜游戏,您有9次尝试猜测0到100之间的数字。但是,如果用户输入字符串值,则会得到ValueError。如何处理ValueError

for Guesses in range(9):
        print('Take a guess.')

        Guess = int(input())

        if Guess < 0:
            print('Please enter a positive number')
        elif Guess > 100:
            print('The number is only between 0 and 100')
        elif Guess < Number:
            print('Higher...')
        elif Guess > Number:
            print('Lower...')           
        else:
            print('Spot on!')
            break # Guess was correct

最佳答案

使用tryexcept。尝试这个:

for Guesses in range(9):
        print('Take a guess.')
        while True:
            try:
                Guess = int(input())
                break
            except ValueError:
                print("Try again. That is not a number")

        if Guess < 0:
            print('Please enter a positive number')
        elif Guess > 100:
            print('The number is only between 0 and 100')
        elif Guess < Number:
            print('Higher...')
        elif Guess > Number:
            print('Lower...')           
        else:
            print('Spot on!')
            break # Guess was correct

一些进步:
for Guesses in range(9):
        print('Take a guess.')
        while True:
            try:
                Guess = int(input())
                if (0 > Guess):
                    print('Please enter a positive number')
                elif (100 < Guess):
                    print('The number is only between 0 and 100')
                else:
                    break
            except ValueError:
                print("Try again. That is not a number")
        elif Guess < Number:
            print('Higher...')
        elif Guess > Number:
            print('Lower...')           
        else:
            print('Spot on!')
            break # Guess was correct

另外,建议变量名不要大写。

关于python-3.x - 如何处理ValueError?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61104379/

相关文章:

python - list() 与 Python 3.5+ 中的可迭代拆包

Python Pandas - 非连续时间序列?

python - 如何从列表中添加一定范围的整数元素? Python 3.3

excel - Excel工作簿已损坏和已修复现在工作表说代码错误时内存不足

python-3.x - Python 计划从每个工作日开始并每小时运行一次作业

python - Python 3.x 中的类型错误

visual-studio - Visual Studio错误

javascript - 我如何确保该函数正确处理错误?

powershell - 无法覆盖变量false,因为它是只读或常量

asp.net - 未处理的 ASP.NET 错误 - 是否有可用的日志记录?