LEXOR AI
LEXOR AI

Reputation: 103

Recursive function not running if statements in 1st recursion

def age():
    try:
        num = int(input('Please enter your birth year: '))
        if num > 2020:
            print 'Invalid input. Not a valid birth year.'
            age()
        else:
            return 2020 - num
    except ValueError:
        print 'Invalid input. Not a number.'
        age()

If the input is a string it successfully returns "Invalid input. Not a number.". But if I then enter a number less than 2020 after the first recursion I do not get anything returned.

What is happening here?

Upvotes: 0

Views: 86

Answers (2)

chepner
chepner

Reputation: 531708

Recursion is not a replacement for a loop in Python; the former is limited by the allowed stack size.

def age():
    while True:
        response = input("Please enter your birth year: ")
        try:
            num = int(response)
        except ValueError:
            print("Invalid input. Not a number.")
        else:
            if num > 2020:
                print("Invalid input. Not a valid birth year.")
            else:
                return 2020 - num

Here is a infinite loop that uses a constant amount of stack space. The function returns (exiting the loop as well) once num > 2020 successfully evaluates to False.

Upvotes: 1

Simran
Simran

Reputation: 108

Value is getting returned, but you are not printing it anywhere. You are just calling age() function but not printing the returned value.

Upvotes: 0

Related Questions