1

Say I want to create a function that asks the user to input float data. The program checks if the input is float or not, if it is not, it returns to the beginning and if it is then it returns the data, bringing the function to an end. It works fine to check the data type and it does if the data is float, but if I first input invalid data and then input valid one, gives me error.

def function1():
    try:
        data1 = float(input("Please type in pi with its first 2 digits"))
        status = 1
    except ValueError:
        status = 0
    if status == 0:
        print("Please enter a valid answer.")
        function1()
    else:
        return data1
x = float(function1())
if x == 3.14:
    print("Correct!")
else:
    print("Incorrect, please try again.")
    function1()

The error it gives me is:

TypeError: float() argument must be a string or a number, not 'NoneType'

Note again. This ONLY happens when I first input invalid data (such as "no") and THEN inputting valid (3.14, 2.71 etc.). Otherwise, the 'program' works fine.

  • Note that although the duplicate has the solution to the specific issue, recursion really isn't the right way to do this in the first place. – Daniel Roseman Jul 14 '19 at 16:49

2 Answers2

1

You're supposed to return function1 like:

def function1():
    try:
        data1 = float(input("Please type in pi with its first 2 digits"))
        status = 1
    except ValueError:
        status = 0
    if status == 0:
        print("Please enter a valid answer.")
        return function1()
        # ^^^^ Here
    else:
        return data1

This also makes the function recursive. When you don't return anything from a funciton, None is returned automatically.


Also you're catching the exception, so you should do the recursion from there:

def function1():
    try:
        data1 = float(input("Please type in pi with its first 2 digits"))
    except ValueError:
        print("Please enter a valid answer.")
        return function1()
        # ^^^^ Here
    else:
        return data1

This also removes the redundant status to track validity.


As an aside, Python does not have tail call optimization so you could reach the max stack size when using recursion.

heemayl
  • 35,775
  • 6
  • 62
  • 69
0

You're not returning from recursive function so you get None

    if status == 0:
        print("Please enter a valid answer.")
        return function1()
Rubén Salas
  • 228
  • 3
  • 6