Python_基础_Day_3
Posted 起航追梦人
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python_基础_Day_3相关的知识,希望对你有一定的参考价值。
函数
一、定义函数
def my_abs(x): if x < 0: return -x else: return x
二、调用函数
my_abs(-10) # 10
三、参数
1、默认参数(默认参数必须指向不变对象)
def my_abs(x=2): if x < 0: return -x else: return x
2、可变参数(0个或任意个)
def calc(*numbers): sum = 0 for n in numbers: sum += n*n return sum print(calc(1,2,3,4)) # 30 l = [1,2,3,4] #Python允许在list或tuple前面加一个*号,把list或tuple的元素变成可变参数传进 print(calc(*l)) # 30
3、关键词参数(0个或任意个包含参数名的参数,这些参数在函数内自动组成dict),功能:扩展函数功能
def person(name, age, **kw): print(‘name:‘, name, ‘age:‘, age, ‘other:‘, kw) person(‘char‘, 28) # name: char age: 28 other: {} person(‘char‘, 28, city=‘beijing‘) # name: char age: 28 other: {‘city‘: ‘beijing‘} person(‘char‘, 28, gender = ‘M‘, job = ‘Engineer‘) # name: char age: 28 other: {‘gender‘: ‘M‘, ‘job‘: ‘Engineer‘} extra = {‘city‘: ‘beijing‘, ‘job‘: ‘Engineer‘} person(‘char‘, 28, **extra) # name: char age: 28 other: {‘city‘: ‘beijing‘, ‘job‘: ‘Engineer‘}
4、命名关键词参数(如果要限制关键字参数的名字,就可以用命名关键字参数,例如,只接收city
和job
作为关键字参数)
def person(name, age, *, city, job): print(‘name:‘, name, ‘age:‘, age, city, job) person(‘char‘, 28, city=‘beijing‘, job=‘Engineer‘) # name: char age: 28 beijing Engineer
以上是关于Python_基础_Day_3的主要内容,如果未能解决你的问题,请参考以下文章