I'm new here, and I'm also new in coding.
I'm actually learning Python, and I have a question, because I already tried everything, but I was unable to resolve it.
I have this code from a little game I saw in a tutorial. The objective is to the user guess the number. What I was trying to do is to handle the exception if the user enters a letter, then show an error message and go back to the loop. If someone helps me, I will be grateful.
highest = 200
answer = random.randrange(highest)
guess = raw_input("Guess a number from 0 to %d:" %highest)
if (int(guess) < answer):
print "Answer if higher"
print "Answer is lower"
guess=raw_input("Guess a number from 0 to %d: " %highest)
raw_input ("You're a winner Face!!!")
This is how i would do it:
import random highest = 200 answer = random.randrange(highest) while True: try: guess = int(input("Guess a number from 0 to %d: " %highest)) if guess < answer: print("Answer if higher") elif guess > answer: print("Answer is lower") else: print("You're a winner Face!!!") break except: print('Input not valid!') continue
I have a dummy condition on the
while and i am directing the flow from inside the loop using
break. I wrapped the whole guess checking procedure in a
try-except block but the only thing that is really tried is the conversion of the input to
integer. Everything else could also be moved after the