Python可变参数用法实例分析

yipeiwu_com6年前Python基础

本文实例讲述了Python可变参数用法。分享给大家供大家参考,具体如下:

#!/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的元素变成可变参数传进去:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import math
def calc(*numbers):
  sum=0
  for n in numbers:
    sum+=n**2
  return sum
nums = [1,2,3]
print(calc(*nums))

运行效果图如下:

更多关于Python相关内容感兴趣的读者可查看本站专题:《Python函数使用技巧总结》、《Python数据结构与算法教程》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总

希望本文所述对大家Python程序设计有所帮助。

相关文章

解决python中用matplotlib画多幅图时出现图形部分重叠的问题

1.解决方法:使用函数 tight_layout() 2.具体使用方法 import matplotlib.pyplot as plt fig = plt.figure()...

Python中一些自然语言工具的使用的入门教程

NLTK 是使用 Python 教学以及实践计算语言学的极好工具。此外,计算语言学与人工 智能、语言/专门语言识别、翻译以及语法检查等领域关系密切。 NLTK 包括什么 NLTK 会被自...

Python实现绘制双柱状图并显示数值功能示例

Python实现绘制双柱状图并显示数值功能示例

本文实例讲述了Python实现绘制双柱状图并显示数值功能。分享给大家供大家参考,具体如下: # -*- coding:utf-8 -*- #! python3 import matp...

python去掉字符串中重复字符的方法

复制代码 代码如下:If order does not matter, you can use "".join(set(foo))set() will create a set of u...

对python中的try、except、finally 执行顺序详解

如下所示: def test1(): try: print('to do stuff') raise Exception('hehe') print('to r...