0

I have this function that should return 1 once the input is 'x'. Why does this return None if the first input is 'y' and then the next input is 'x'?

def func():
    a = input('x or y\n')
    if a == 'x':
        return 1
    else:
        func()

print(func())

This is written in the command line:

x or y 
y         # My input
x or y
x         # My input 
None

Why does it return None and not 1?

2 Answers2

0

functions always give output next to the return statement. You need to return your function as output for recursion.

def func():
    a = input('x or y\n')
    if a == 'x':
        return 1
    else:
        return func()

print(func())

will make your function recursive. Best regards...

ihsancemil
  • 432
  • 5
  • 16
0

In the else statement you are calling the function but not returning from it. So the function returns none if it goes in the else statement.

def func():
a = input('x or y\n')
if a == 'x':
    return 1
else:
    return func()

print(func())

Writing it like this will fix the problem as you'll return the calculated value from func. And the function will always return something regardless of the input.

Petar Velev
  • 2,305
  • 12
  • 24