I am getting errors from using try-except block to validate input

Issue

I want to use the try-except code block to notify the user not to insert float type input but, only integers
But any time i run the code the feature won’t work.
Also the code wont trow an error for easy debugging.
It only outputs the first print statements and it shuts-down

import random

MAX_GUESSES = 5  # max number of guesses allowed

MAX_RANGE = 20  # highest possible number

# show introductionpygame
print("welcome to my franchise guess number game")
print("guess any number between 1 and", MAX_RANGE)
print("you will have a range from", MAX_GUESSES, "guesses")

def playOneRound():
    # choose random target
    target = random.randrange(1, MAX_RANGE + 1)

    # guess counter
    guessCounter = 0

    # loop fovever
    while True:
        userGuess = input("take a guess:")

         #check for potential errors
         try:
             userGuess = int(userGuess)
         except: 
               print("sorry, you are only allowed to enter integers thanks!")



    # increment guess counter
    guessCounter = guessCounter + 1

    # if user's guess is correct, congratulate user, we're done
    if userGuess == target:
        print("you got it la")
        print("it only took you", guessCounter, "guess(es)")
        break
    elif userGuess < target:
        print("try again, your guess is too low.")
    else:
        print(" your guess was too high")

    # if reached max guesses, tell answer correct answer, were done
    if guessCounter == MAX_GUESSES:
        print(" you didnt get it in ", MAX_GUESSES, "guesses")
        print("the number was", target)
        break

    print("Thanks for playing ")

 # main code

 while True:
     playOneRound()  # call a function to play one round of the game
     goAgain = input("play again?(press ENTER to continue, or q to quit ):")
     if goAgain == "q":
         break

Solution

The task can be split into two steps:

  1. check that the input string can be converted into a number
  2. check that this number is an integer
while True:
    userGuess = input("take a guess: ")

    try:
        userGuess = float(userGuess)   # stuff like "asdf", "33ff" will raise a ValueError
        if userGuess.is_integer():     # this is False for 34.2
            userGuess = int(userGuess)
            break                      # an integer is found, leave the while loop
    except ValueError:
        pass                           # just try again

    print("sorry, you are only allowed to enter integers thanks!")

Answered By – maij

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published