0

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!!!")
khelwood
  • 55,782
  • 14
  • 81
  • 108
  • This can be done without Exception-handling. raw_input() always returns a string, strings have the method isdigit() which can be used in a boolean context. Do you really want to use Exception-handling? – sphere Jul 13 '16 at 09:46

1 Answers1

1

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.

Ma0
  • 15,057
  • 4
  • 35
  • 65