-1

I'm trying to create a guessing game. I want it so that it uses a while loop and changes the input message after the first one. I put together this piece of code but it doesn't evaluate correctly (it will say 9 is too high and say that 1 is too high and then the answer will be 18... things like that) and for the life of me can't figure out why.

import random

number = str(random.randint(1,20))

name = input("What is your name? ")
guess = input("Hello %s! I am thinking of a number between 1 and 20. What number am I thinking of? " % name)

while (guess != number):
    if guess > number:
        guess = input("Too High! Guess again: ")
    elif guess < number:
        guess = input("Too Low! Guess again: ")
        
print("Congratulations! You guessed it correctly!")
khelwood
  • 55,782
  • 14
  • 81
  • 108
Adrian
  • 1
  • 2
  • 2
    Instead of converting `number` to a `str`, you should convert `guess` to an `int`. That way you can compare them numerically instead of alphabetically. `10 > 9` but `'10' < '9'`! – Samwise May 26 '21 at 20:24

1 Answers1

1

Your number is a string here.

Convert it in integer as well as guess:

number = random.randint(1,20)   # Give you an integer

guess = int(guess) # Add it after each input(guess) to convert it in integer
Julien
  • 763
  • 8
  • 32
  • 1
    `random.randint` gives you an `int`, no need to convert it to an `int` again. – Samwise May 26 '21 at 20:32
  • Sure, I will edit my answer – Julien May 26 '21 at 20:33
  • Oh how silly of me! I converted it into a string so I wouldn't have to convert the other instances into an integer but I didn't realize that that meant I can't see if they're greater or less than each other. Thanks – Adrian May 26 '21 at 20:36