-3

I have just started to learn coding. This is a simple number guessing game that I created with Python. It works fine but I feel like the code can be simplified/optimized so it looks more neat. Another thing is that every time I try to input a non-integer, an error occurred. Is there a way to check if the user input is an integer or not and then proceed to the next step only if it is an integer. Thank you in advance!

from random import randint

random_number = randint(1, 10)

guesses_taken = 0

print ("Hello! What is your name?")

guess_name = input()

print ("Well, " + guess_name + ", I am thinking of a number between 1-10.")


while guesses_taken < 4:
    print ("Take a guess!")
    guess = int(input())
    if guess not in range(1, 11):
        print ("Oops! That's not an option!")
    elif guess == random_number:
        print ("You're right! Congratulations!")
        break
    else:
        guesses_taken += 1
        if guesses_taken < 4:
            print ("Nope! Try again,")
        else:
            print ("Out of chances. You lose.")

1 Answers1

0

You could use a try except block, to check if the value is an integer and throw an error/user message if not, (this would go where you have guess = int (input())

something like:

try:
 val = int(guess)
except ValueError:
 print("Please enter an Integer")
Rob
  • 109
  • 2
  • 10
  • Your integer literals 10 and 11 are related, so you should define one of them in terms of the other. Then you don't run the risk of modifying only one and thus introduce a bug. – Arndt Jonasson May 24 '18 at 07:48