Python语言基础与应用-北京大学-陈斌-P29-28-计算和控制流:控制流:上机:基本计算程序-给定n,计算1+2!+3!+...+n!的值-上机代码
方法一,使用自定义函数:
# 给定n,计算1+2!+3!+...+n!的值
def factoral(number): # 自定义一个阶乘的函数
start_number = 1
end_number = number
result_number = 1
while start_number <= end_number: # 阶乘部分
result_number = result_number * start_number
start_number += 1
print("阶乘函数中的运算结果:",result_number)
return(result_number)
user_number = int(input("请输入一个数:"))
start_number = 1
result = 0
while start_number <= user_number:
result = result + factoral(start_number)
start_number += 1
print(result)
结果:
Python 3.7.6 (bundled)
>>> %Run test.py
请输入一个数:5
阶乘函数中的运算结果: 1
阶乘函数中的运算结果: 2
阶乘函数中的运算结果: 6
阶乘函数中的运算结果: 24
阶乘函数中的运算结果: 120
153
>>>
方法二,不用自定义函数:
# 给定n,计算1+2!+3!+...+n!的值,不使用自定义函数
user_number = int(input("请输入一个数:"))
start_number = 1
result = 0
while start_number <= user_number: # 第1层循环体
# 计算阶乘的循环体
factoral_start_number = 1 # 把阶乘开始的数值定义为1
factoral_result = 1 # 定义一个变量 factoral_result 存储阶乘循环体的结果
while factoral_start_number <= start_number: # 第2层循环体,计算阶乘的循环体
factoral_result = factoral_result * factoral_start_number
factoral_start_number += 1
result = result + factoral_result
start_number += 1
print(result)
结果:
Python 3.7.6 (bundled)
>>> %Run test.py
请输入一个数:5
153
>>>