I am learning Python, stuck in factorial program, I am getting multiple lines of output instead of single line output.
Program I wrote
num = int (input ("Enter a number: "))
factorial = 1
if num == 0:
print ("The factorial of 0 is 1")
elif num <0:
print ("Error, negative number does not have factorial")
else:
for i in range (2, num 1):
factorial = factorial*i
print ("the factorial is: ", factorial)
getting output as below.
Enter a number: 4
the factorial is: 2
the factorial is: 6
the factorial is: 24
I am looking for single line answer but getting multiple lines, I am unable to understand why.
CodePudding user response:
You don't need an explicit test for the input being equal to 0. The correct result can be obtained by carefully constructing the range.
Do not print the intermediate value(s) within the loop - just do it once after the loop terminates.
Using Python 3.8 you could do it like this:
if (n := int(input('Input value for n: '))) < 0:
print('Unable to calculate factorial of a negative number')
else:
f = 1
for i in range(2, n 1):
f *= i
print(f'{n}! = {f}')
If n < 2 (but not negative) the loop will not be entered and so the value of 1 initially assigned to f will be the correct answer
CodePudding user response:
your placement of print ("the factorial is: ", factorial) is wrong it should under for i in range (2, num 1):
CodePudding user response:
print ("the factorial is: ", factorial)
currently, your print statement is under the scope of for loop that's why after each iteration print statement is also evaluated. so to avoid this simply move the print statement from the scope of for loop
num = int (input ("Enter a number: "))
factorial = 1
if num == 0:
print ("The factorial of 0 is 1")
elif num <0:
print ("Error, negative number does not have factorial")
else:
for i in range (2, num 1):
factorial = factorial*i
print ("the factorial is: ", factorial)