Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

TypeError: in python in custom input function, exception handling

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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:
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading