skip to Main Content

I do not know what I did wrong, but here is the code I have been using.

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

I keep getting an error when trying to run my code:

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:UsersSamarth.vscodeextensionsms-python.python-2023.12.0pythonFilesvscode_pytestexample.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:UsersSamarth>
        

2

Answers


  1. Your code work perfectly. I ran it few time using PyCharm.

    You’re receiving ValueError because the string input is being converted to int. what’ll happen if the user enter a letter or a character?

    A ValueError is a type of exception that is raised when a function or operation receives an argument with the correct data type but an inappropriate value. It occurs when the input value is not within the expected range or doesn’t fit the constraints defined by the function or operation.

    If you try to convert a string to an integer using the int() function, and the string does not represent a valid integer, a ValueError will be raised.

    for example:

    # 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...
    

    This will result in a ValueError

    Login or Signup to reply.
  2. I’m adding to Moses McCabe’s answer. Consider the following line in your code:

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

    If the conversion from a string to an integer fails, Python will throw a ValueError. Errors can be caught and handled using a try/except construct with the following syntax:

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

    With this in mind, let’s improve your code by checking if the input is valid and handling eventual errors:

    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
    

    Also, you should completely remove the first while loop in your code. I don’t know why it’s there, maybe you forgot to delete it? The final code would look like this:

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

    Hope this solves your doubts. Have a nice day.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search