Reputation: 19
I coded this program to find the factorial of a number. When I tried it with the number 0 it would print twice but when I use any other number it just works fine.
def factorial_num(factorial):
num = int(input("Write a number to figure out his factorial"))
if num == 0:
print ("The factorial of 0 is 1")
elif num < 0:
print ("Negative numbers don't have a factorial")
else:
for i in range (1, num + 1):
factorial = factorial*i
print ("The factorial of", num, "is", factorial)
factorial_num(1)
Why is this happening?
Upvotes: 0
Views: 88
Reputation: 92
So basically the issue here has to do with indentation.
If you look at your if block there are 3 options. With any given number only 1 of the: if, elif, else will be executed, then the code will continue running after the if block.
When you input 0 the code executes the
if num == 0:
print ("The factorial of 0 is 1")
block (Hence printing the result once) then continues after it.
After the if block there is another print that gets executed always (Hence the second print)
What you can do to fix that:
Indent the last print so its in the else part of the block or Completely remove the first if part and modify the block so the 0 is included on the else part.
Upvotes: 1