python 练习题:接收一个或多个数并计算乘积
程序员文章站
2023-08-29 17:54:20
方法二: ......
以下函数允许计算两个数的乘积,请稍加改造,变成可接收一个或多个数并计算乘积
def product(x, y):
return x * y
# -*- coding: utf-8 -*-
def prodouct(*num):
n = 1
for x in num:
n = n * x
return n
# 测试
print('print(5)=',prodouct(5))
print('print(5,6)=',prodouct(5,6))
print('print(5,6,7)=',prodouct(5,6,7))
print('print(5,6,7,9)=',prodouct(5,6,7,9))
if prodouct(5) != 5:
print('测试失败')
elif prodouct(5,6) != 30:
print('测试失败')
elif prodouct(5,6,7) != 210:
print('测试失败')
elif prodouct(5,6,7,9) != 1890:
print('测试失败')
方法二:
# -*- coding: utf-8 -*-
def prodouct(x,*num):
if len(num) > 0 :
for y in num:
x = x * y
return x
# 测试
print('print(5)=',prodouct(5))
print('print(5,6)=',prodouct(5,6))
print('print(5,6,7)=',prodouct(5,6,7))
print('print(5,6,7,9)=',prodouct(5,6,7,9))
if prodouct(5) != 5:
print('测试失败')
elif prodouct(5,6) != 30:
print('测试失败')
elif prodouct(5,6,7) != 210:
print('测试失败')
elif prodouct(5,6,7,9) != 1890:
print('测试失败')
下一篇: 如何用Asp动态生成xml文件