-1

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

Anas Ansari
  • 405
  • 4
  • 6
  • [Please do not upload images of errors and/or program output when asking a question.](//meta.stackoverflow.com/q/285551) Instead, copy and paste the terminal output, formatted like text. Also, make sure to **ask a question** when posting on Stack Overflow, as described in [ask]. "I got an error" is not sufficent. Please try to start with a question word like "why" or "how", and end with a question mark (`?`). – Karl Knechtel May 19 '22 at 06:33
  • There are two possible questions here: one is about debugging the recursive code for `takeInput`, and the other is about how to *solve that problem* in the normal way. (It is not a good idea to use recursion for this problem.) Both questions are common duplicates, which I have now linked. – Karl Knechtel May 19 '22 at 06:36

1 Answers1

1

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:
Diptangsu Goswami
  • 5,554
  • 3
  • 25
  • 36