You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

运行猜数字Python代码时遇ValueError报错,请求排查

猜数字游戏代码ValueError报错排查

运行以下猜数字Python代码时,持续触发ValueError,提示无法将命令行相关字符串转换为十进制整数,需排查问题:

import random

num = random.randint( 1, 100)

print("ELCOME TO GUESS ME!")
print("I'm thinking of a number between 1 to 100")
print("If your guess is more than 10 away from my number, I'll tell you you're COLD")
print("If your guess is within 10 of my number, I'll tell you you're WARM")
print("If your guess is farther than your most recent guess, I'll say you're getting COLDEER")
print("If your guess is closer than your most recent guess, I'll say you're getting WARMER")
print("LET'S PLAY!")

guesses = [0]

while True:

    guess = int(input("I'm thinking of a number between 1 and 100.\n  What is your guess? "))

    if guess < 1 or guess > 100:
        print('OUT OF BOUNDS! Please try again:')
        continue

    break

while True:

    # we can copy the code from above to take an input
    guess = int(input("I'm thinking of a number between 1 and 100.\n  What is your guess? "))

    if guess < 1 or guess > 100:
        print('OUT OF BOUNDS! Please try again: ')
        continue

    #here e compare the player's guess to our number
    if guess == num:
        print(f'CONGRATULATIONS, YOU GUESSED IT IN ONLY {len(guesses)} GUESSES!!')
        break

    # if guess is incorrect, add guess to our number
    guesses.append(guess)

    # when testing the first guess, guesses[-2]==0, which evaluates to False
    #and brings us down to the second section 

    if guesses[-2]:
        if abs(num-guess) < abs(num-guesses[-2]):
            print('WARMER!')
        else:
            print('COLDER!')

    else:
        if abs(num-guess) <= 10:
            print('WARM!')
        else:
            print('COLD!')

报错信息:

If your guess is closer than your most recent guess, I'll say you're getting WARMER
LET'S PLAY!
I'm thinking of a number between 1 and 100.
  What is your guess? & C:/Users/Samarth/AppData/Local/Microsoft/WindowsApps/python3.11.exe c:/Users/Samarth/.vscode/extensions/ms-python.python-2023.12.0/pythonFiles/vscode_pytest/example.py
Traceback (most recent call last):
  File "c:\Users\Samarth\.vscode\extensions\ms-python.python-2023.12.0\pythonFiles\vscode_pytest\example.py", line 17, in <module>
    guess = int(input("I'm thinking of a number between 1 and 100.\n  What is your guess? "))
            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
ValueError: invalid literal for int() with base 10: '& C:/Users/Samarth/AppData/Local/Microsoft/WindowsApps/python3.11.exe c:/Users/Samarth/.vscode/extensions/ms-python.python-2023.12.0/pythonFiles/vscode_pytest/example.py'
PS C:\Users\Samarth>

问题根源

从报错信息看,程序读取到的输入不是数字,而是一段命令行启动代码的字符串,这说明你可能误将启动命令当成了输入内容,或是VS Code的运行配置异常,导致程序启动时把命令行参数传入了input()函数。

解决办法

  1. 正确运行程序:不要通过pytest相关入口运行脚本,直接在VS Code中点击右上角的▶️按钮(「运行Python文件」),或在终端手动输入以下命令运行:

    python c:/Users/Samarth/.vscode/extensions/ms-python.python-2023.12.0/pythonFiles/vscode_pytest/example.py
    

    运行后,在终端出现What is your guess?提示时,输入1-100之间的数字即可。

  2. 优化代码(可选):原代码存在重复输入逻辑,且未处理非数字输入的情况,可优化为:

    import random
    
    num = random.randint(1, 100)
    
    print("WELCOME TO GUESS ME!")
    print("I'm thinking of a number between 1 to 100")
    print("If your guess is more than 10 away from my number, I'll tell you you're COLD")
    print("If your guess is within 10 of my number, I'll tell you you're WARM")
    print("If your guess is farther than your most recent guess, I'll say you're getting COLDER")
    print("If your guess is closer than your most recent guess, I'll say you're getting WARMER")
    print("LET'S PLAY!")
    
    guesses = [0]
    
    while True:
        # 处理非数字输入
        try:
            guess = int(input("\nI'm thinking of a number between 1 and 100.\n  What is your guess? "))
        except ValueError:
            print("请输入有效的整数!")
            continue
    
        if guess < 1 or guess > 100:
            print('OUT OF BOUNDS! Please try again:')
            continue
    
        if guess == num:
            print(f'CONGRATULATIONS, YOU GUESSED IT IN ONLY {len(guesses)} GUESSES!!')
            break
    
        guesses.append(guess)
    
        if guesses[-2]:
            if abs(num - guess) < abs(num - guesses[-2]):
                print('WARMER!')
            else:
                print('COLDER!')
        else:
            if abs(num - guess) <= 10:
                print('WARM!')
            else:
                print('COLD!')
    

    优化点说明:

    • 合并重复的输入循环
    • 增加try-except捕获非数字输入,避免程序崩溃
    • 修正原代码中「COLDEER」「ELCOME」的拼写错误

内容的提问来源于stack exchange,提问作者S S

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 00:28:08