我正在学习Python,陷入阶乘程序中,我得到多行输出而不是单行输出。
我写的程序
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)
得到如下输出。
Enter a number: 4
the factorial is: 2
the factorial is: 6
the factorial is: 24
我正在寻找单行答案,但得到多行答案,我无法理解为什么。
您不需要显式测试输入是否等于 0。通过仔细构建范围可以获得正确的结果。
不要打印循环内的中间值 - 只需在循环终止后打印一次。
使用 Python 3.8+ 你可以这样做:
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}')
如果 n < 2 (but not negative) the loop will not be entered and so the value of 1 initially assigned to f 就是正确答案
因为你的输出有多个答案。而不是使用 while 范围。
num = int (input ("Enter a number: "))
factorial = 1
i=1
if num == 0:
print ("The factorial of 0 is 1")
elif num <0:
print ("Error, negative number does not have factorial")
else:
while i<=num:
factorial = factorial*i
i=i+1
print ("the factorial is: ", factorial)
或者,
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)
有最简单的方法:
import math
num = int (input ("Enter a number: "))
if num == 0:
print ("The factorial of 0 is 1")
elif num <0:
print ("Error, negative number does not have factorial")
else:
factorial=math.factorial(num)
print ("the factorial is: ", factorial)
num = int(input("请输入一个数字:")) 阶乘 = 1
如果 num == 0: print("0的阶乘是1") elif 数字 <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)
print ("the factorial is: ", factorial)
目前,您的 print 语句位于 for 循环的范围内,这就是为什么在每次迭代之后也会评估 print 语句。因此,为了避免这种情况,只需将 print 语句从 for 循环范围中移出
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)