python计算两个数乘积_python 练习题:接收一个或多个数并计算乘积

以下函数允许计算两个数的乘积,请稍加改造,变成可接收一个或多个数并计算乘积

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('测试失败')

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!