zoukankan      html  css  js  c++  java
  • 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('测试失败')
    

      

      

  • 相关阅读:
    zookeeper部署
    Hadoop集群的构建和安装
    numpy ndarray求其最值的索引
    两数之和
    盛最多水的容器
    mysql 单表卡死
    Leetcode 258. Add Digits
    Matlab中添加路径与去除路径
    Leetcode 136 Single Number
    Leetcode 485. Max Consecutive Ones
  • 原文地址:https://www.cnblogs.com/chling/p/11737070.html
Copyright © 2011-2022 走看看