user5514149
user5514149

Reputation:

Recursive Function inside While loop (Python)

So I'm learning about recursion in Python and I have some code that finds the factorial of a number input by user.

def recursion(x):
    if x == 1:
        return 1
    else:
        return(x * recursion(x - 1))

num = int(input("Enter a non-negative integer: "))
if num >= 1:
    print("The factorial of", num, "is", recursion(num))

This code works fine. That is, it will ask the question specified, allow user input, and find the factorial of the number. So what I'm trying to do is to put that recursive function inside of a While loop so that after the program prints the factorial of the number submitted, it asks if the user would like to input another number.

loop = 1
while loop == 1:

def recursion(x):
    if x == 1:
        return 1
    else:
        return(x * recursion(x - 1))

num = int(input("Enter a non-negative integer: "))
if num >= 1:
    print("The factorial of", num, "is", recursion(num))
    print()
    answer = input(print("Would you like to find the factorial of another non-negative integer? Y/N: "))
    if answer == "Y":
        loop = 1
    else:
        loop = 0

The issue I'm having with this code is that it will ask the user for an input number, find the factorial, and ask the question "Would you like to find the factorial of another non-negative integer? Y/N:" but when I run this in IDLE the line after the above question says "None."

Python 3.5.0 (v3.5.0:374f501f4567, Sep 13 2015, 02:27:37) 
[MSC v.1900 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
Enter a non-negative integer: 6
The factorial of 6 is 720
Would you like to find the factorial of another non-negative integer? Y/N: 
NoneY
Enter a non-negative integer: 4
The factorial of 4 is 24
Would you like to find the factorial of another non-negative integer? Y/N: 
NoneN
>>> 

I looked through the Python documentation (section 4.6) and it mentions that the interpreter usually suppresses "None."

  1. Why, when I run this in IDLE, does it display "None" after the loop control question?
  2. Is there a way to omit the "None" and still use print()?

Upvotes: 2

Views: 1165

Answers (2)

idjaw
idjaw

Reputation: 26580

The reason why you are seeing the None is because you have a print inside your input:

input(print("Would you like to find the factorial of another non-negative integer? Y/N: "))

Remove that print

input("Would you like to find the factorial of another non-negative integer? Y/N: ")

Upvotes: 3

Dair
Dair

Reputation: 16240

This line:

answer = input(print("Would you like to find the factorial of another non-negative integer? Y/N: "))

print returns None, so you are inputing None into your factorial function, which then gives None as an answer.

Should be:

answer = input("Would you like to find the factorial of another non-negative integer? Y/N: ")

Upvotes: 1

Related Questions