Search code examples
pythontypeerror

I am making a guessing game but I have problems with it. What should I do?


So this is my code:

import random
def guess(x):
      random_number = random.randint(1, x)
      guess = 0
      while guess != random_number:
            guess = input(f'Guess a number between 1 and {x}:')
            if guess < random_number:
                       print('Sorry, Guess again. Too low.')
            elif guess > random_number:
                       print('Sorry. Guess again. Too high')
print(f'Yay, Congrats. You have guessed the number {random_number} correctly!')
guess(10)

but I am getting these errors: line 15, in <module> guess(10)

and line 8, in guess if guess < random_number: TypeError: '<' not supported between instances of 'str' and 'int'


Solution

  • This should work:

    import random
    def guess(x):
        random_number = random.randint(1, x)
        guess = 0
        while guess != random_number:
            guess = int(input(f'Guess a number between 1 and {x}:'))
            if guess < random_number:
                print('Sorry, Guess again. Too low.')
            elif guess > random_number:
                print('Sorry. Guess again. Too high')
        print(f'Yay, Congrats. You have guessed the number {random_number} correctly!')
    guess(10)
    

    Output:

    Guess a number between 1 and 10: 4
    Sorry, Guess again. Too low.
    Guess a number between 1 and 10: 6
    Sorry. Guess again. Too high
    Guess a number between 1 and 10: 5
    Yay, Congrats. You have guessed the number 5 correctly!
    

    Your code had two problems: the indentation was not correct, and everything read from input() is a string. To fix that I just converted the number read from input() to an int.