Home > Software engineering >  How to use the try-except command in a for loop asking for user input?
How to use the try-except command in a for loop asking for user input?

Time:02-26

Abstract: I was making a guess the number game. Which will give you 7 tries to guess the no. after that it will tell you the number. I was trying to remove the human error of inputting a word(eg.six) instead of 6 by using Try and except method. This is how I wrote my code.

Tools: I am using Windows 10 with python 3.10.2 version in it.

Problem: I am facing an issue with try and except method which is not working. For eg. When I am typing six/five in words in user input its not printing That is not a number. Instead its giving me Traceback error. Which is what I am avoiding and trying to make a clean code.

    # This a guess the number game.


    import random  
    secretNumber=random.randint(1,20)

    for guessesTaken in range(1,7):
        print('Take a guess.')
        guess=int(input())

    #### Why this conditioning is importtant? ####
    #     Because it will only improve our guesses
        try:
            if guess < secretNumber:
                 print('Too Low')
            elif guess > secretNumber:
                 print('Too high')
            else:
                 break        #This is for the correct guess
        except:
            print('That is not a number')

    if guess == secretNumber:
        print('Good Game. ' 'You guessed it correctly in '  str(guessesTaken) ' 
    guesses')
    else:
         print('Nope. The number I was thinking of was ' str(secretNumber)) 
  

CodePudding user response:

input throws error before try block , move input() into try block

    # This a guess the number game.


    import random  
    secretNumber=random.randint(1,20)

    for guessesTaken in range(1,7):
        print('Take a guess.')
 

    #### Why this conditioning is importtant? ####
    #     Because it will only improve our guesses
        try:
            guess=int(input())
            if guess < secretNumber:
                 print('Too Low')
            elif guess > secretNumber:
                 print('Too high')
            else:
                 break        #This is for the correct guess
        except:
            print('That is not a number')

    if guess == secretNumber:
        print('Good Game. ' 'You guessed it correctly in '  str(guessesTaken) ' 
    guesses')
    else:
         print('Nope. The number I was thinking of was ' str(secretNumber)) 
  • Related