TypeError: in python in custom input function, exception handling

Question:

While creating a guess_the_number game in python, I wanted to catch the exception if user enters an invalid number, i.e. ValueError when typecasting the entered string to integer, I created a takeInput() function.
It works fine except for the part that when I raise an exception and enter a valid number after that, I get a TypeError.

import random
randInt = random.randint(1, 100)
count = 1
print("RandInt: " + str(randInt))


def takeInput(message):
    userInput = input(message)
    try:
        userInput = int(userInput)
        print("takeInput try " + str(userInput)) #This line is printing correct value every time
        return userInput
    except ValueError as e:
        takeInput("Not a valid number, try again: ")


userInput = takeInput("Please enter a number: ")

while(not(userInput == randInt)):
    print("while loop " + str(userInput)) #I am receiving a none value after I raise an exception and then enter a valid number
    if(userInput < randInt):
        userInput = takeInput("Too small, try again : ")
    else:
        userInput = takeInput("Too large, try again : ")
    count += 1

print("Congratulations, you guessed it right in " + str(count) + " tries.")

This is output

Asked By: Anas Ansari

||

Answers:

You need to return the value of the function when an exception occurs. Since you’re not returning anything, it returns None by default even when the function gets called.

def takeInput(message):
    userInput = input(message)
    try:
        userInput = int(userInput)
        print("takeInput try " + str(userInput)) #This line is printing correct value every time
        return userInput
    except ValueError as e:
        return takeInput("Not a valid number, try again: ")

A few things unrelated to the error,

  • Try using snake_case and not camelCase in python.
  • f strings are pretty nice, print(f"takeInput try {userInput}")
  • Consider while userInput != randInt:
Answered By: Diptangsu Goswami