Useranonimo Useranonimo - 1 year ago 51
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)
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!!!")

Answer Source

This is how i would do it:

import random

highest = 200
answer = random.randrange(highest)
while True:
        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")
            print("You're a winner Face!!!")
        print('Input not valid!')

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.