码迷,mamicode.com
首页 > 编程语言 > 详细

Python_基础_Day_3

时间:2018-05-21 16:08:20      阅读:198      评论:0      收藏:0      [点我收藏+]

标签:ret   class   other   组成   tuple   nbsp   可变参数   code   调用   

函数

一、定义函数

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、命名关键词参数(如果要限制关键字参数的名字,就可以用命名关键字参数,例如,只接收cityjob作为关键字参数)

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

标签:ret   class   other   组成   tuple   nbsp   可变参数   code   调用   

原文地址:https://www.cnblogs.com/jp-mao/p/9067250.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!