无法找到Python错误“ImportError:无模块”

ozxc1zmp  于 2023-08-08  发布在  Python
关注(0)|答案(2)|浏览(106)

我不知道我做错了什么,但这是我使用的代码。

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>

5cg8jx4n

5cg8jx4n1#

我补充了Moses McCabe的回答。在代码中考虑以下行:

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

字符串
如果从字符串到整数的转换失败,Python将抛出ValueError。可以使用try/except构造捕获和处理错误,语法如下:

try:
  # Code that may fail
except:
  # Do something if the previous code failed


考虑到这一点,让我们通过检查输入是否有效并处理最终错误来改进代码:

try:
    # Try to get the user inpiut as an integer
    guess = int(input("I'm thinking of a number between 1 and 100.\n  What is your guess? "))
except ValueError:
    # If the string to integer conversion failed, print an error message and continue to the next iteration of the while loop
    print('Please enter a valid number.')
    continue


此外,您应该完全删除代码中的第一个while循环。我不知道为什么会在那里,也许你忘了删除它?最后的代码看起来像这样:

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

    # we can copy the code from above to take an input
    try:
        # Try to get the user inpiut as an integer
        guess = int(input("I'm thinking of a number between 1 and 100.\n  What is your guess? "))
    except ValueError:
        # If the string to integer conversion failed, print an error message and continue to the next iteration of the while loop
        print('Please enter a valid number.')
        continue

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


希望这能解决你的疑虑。祝你今天愉快。

41zrol4v

41zrol4v2#

你的代码运行得很好。我用PyCharm运行了几次。
您收到ValueError,因为字符串输入正在转换为int。如果用户输入一个字母或字符会发生什么?

ValueError是一种异常类型,当函数或操作接收到数据类型正确但值不合适的参数时,会引发该异常。当输入值不在预期范围内或不符合函数或操作定义的约束时,就会发生这种情况。

如果您尝试使用int()函数将string转换为integer,而该字符串不代表有效整数,则会引发ValueError
例如:

# Trying to convert a non-integer string (letter, characters) to an integer
guess = int(input("I'm thinking of a number between 1 and 100.\n  What is your guess? ")) 
# user input: & or A etc...

字符串
这将导致ValueError

相关问题