Python可变参数
2016-07-29 15:55
375 查看
#!/usr/bin/env python # -*- coding: utf-8 -*- import math def calc(*numbers): sum=0 for n in numbers: sum+=n**2 return sum print(calc(1,2,3)) print(calc(1,3,5,7)) print(calc())
定义可变参数和定义一个list或tuple参数相比,仅仅在参数前面加了一个*号。在函数内部,参数numbers接收到的是一个tuple,因此,函数代码完全不变。但是,调用该函数时,可以传入任意个参数,包括0个参数。
Python允许你在list或tuple前面加一个
*号,把list或tuple的元素变成可变参数传进去:
nums = [1,2,3] print(calc(*nums))
相关文章推荐
- Python repr() 函数和str() 函数
- Python黑帽编程 2.0 第二章概述
- python遇到‘\u’开头的unicode编码
- Python 简易购物系统--老男孩作业
- Ubuntu16.4系统下为Python配置caffe环境
- Python编码格式的指定方式
- 详解 Python 中的下划线命名规则
- Python 面向对象(4)
- 协程简单程序(python3.5)
- python练习 根据日志中的ip和url排序
- Python的列表推导式,字典推导式,集合推导式使用方法
- Python中的属性管理
- 五分钟战胜Python字符编码
- ②BeautifulSoup基础知识
- secureCRT 里使用 python 按 backspace 键删除出现 ^H
- Python中的MD5
- 136. Single Number [medium] (Python)
- ML1-mac 安装ipython
- python+Eclipse+pydev环境搭建
- 感知哈希算法 python 3.4