Useranonimo Useranonimo - 4 months ago 7
Python Question

Exception handling on Python

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.

import random

highest = 200
answer = random.randrange(highest)
guess = raw_input("Guess a number from 0 to %d:" %highest)
while(int(guess)!=answer):
if (int(guess) < answer):
print "Answer if higher"
else:
print "Answer is lower"
guess=raw_input("Guess a number from 0 to %d: " %highest)
raw_input ("You're a winner Face!!!")

Answer

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 continue and 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 except bit.

Comments