0

I need help with an assignment I have for Intro to Python.

The assignment is to have the computer pick a random number between 1 and 100 and the user has to guess the number. If your guess is too high then you will be told. If your guess was too low then you will be told. It will continue repeating until you guess the correct number that was generated.

My issue is that if an input is a string then you would get a prompt saying that it is not a possible answer. How do I fix this issue?

P.S. If it would not be too much trouble, I would like to get tips on how to fix my code and not an answer.

Code:

import random

#answer= a
a= random.randint(1,100)

#x= original variable of a
x= a

correct= False
print("I'm thinking of anumber between 1 and 100, try to guess it.")

#guess= g

while not correct:

    g= input("Please enter a number between 1 and 100: ", )

    if g == "x":

       print("Sorry, but \"" + g + "\" is not a number between 1 and 100.")

    elif int(g) < x:

        print("your guess was too low, try again.")

    elif int(g) > x:

        print("your guess was too high, try again.")

    else:

        print("Congratulations, you guessed the number!")
halfer
  • 19,824
  • 17
  • 99
  • 186
Luis
  • 21
  • 1

1 Answers1

0

So if you want to sanitize the input to make sure only numbers are being inputted you can use the isdigit() method to check for that. For example:

g=input("blah blah blah input here: ")
if g.isdigit():
    # now you can do your too high too low conditionals
else:
  print("Your input was not a number!")

You can learn more in this StackOverflow thread.

lovinghate
  • 63
  • 7