Python中给定数字阶乘的单行输出


n=int(input("Enter the Value for n:"))
result=1
for i in range(n, 1, -1):
result=result*i
print("factorial of",n,"is",result)

输出是这样的:

Enter the Value for n:4
factorial of 4 is 4
factorial of 4 is 12
factorial of 4 is 24

我的问题是 - 如何仅在单行(即最后一行(中获取输出?

在python中打印一行是这样的:

print('hello', end='')
print(' world')

输出为:你好世界

希望这是有帮助的

将 print 命令带出循环并仅打印一次结果

n=int(input("Enter the Value for n:"))
result=1
for i in range(n, 1, -1):
result=result*i
print("factorial of",n,"is",result)

这可能有助于您:

import math
num = int(input('Enter the number:')
f = math.factorial(num)
print('The factorial of {} is {}'.format(num, f))

如果你想特别花哨,你可以手动计算阶乘,将中间打印值构建为字符串,然后只用 1 行代码(不包括导入(打印所有内容。

下面打印一个元组,其中第一个元素是计算的阶乘,第二个元素是中间信息的字符串(打印在一行上(。

from functools import reduce
n=4
print(reduce(lambda x,y:(x[0]*y,"%s more text %d"%(x[1],x[0])),range(n,1,-1),(1,"")))

使用 reduce 和 lambda 函数

>>> z =5
>>> reduce(lambda x,y:x*y,range(1,z+1))
120

这可能会有所帮助

最新更新