Python函数知识总结

Python函数知识总结

**

首先,演示一个最简单的函数结构

def greet_user():
    """显示简单的问候语"""
    print("Hello ! ")

greet_user()

运行结果:

Hello ! 

**

向函数传递信息

def greet_user(username):
    """显示简单的问候语"""
    print("Hello, "+username.title()+"!")

greet_user("Python")

在函数greet_user()的定义中,变量username是一个形参——函数完成其工作所需的一项信息。在代码greet_user(“Python”)中,"Python"是一个实参——调用函数时传递给函数的信息。
**
传递实参三种方式:
位置实参

def describe_pet(pet_name,animal_type):
    print("\nI have a "+ animal_type +".")
    print("My "+animal_type+ "'s name is "+pet_name.title()+".")

describe_pet("hamster",'harry')

位置实参的顺序很重要,如果实参的顺序不正确,结果可能出乎意料。
**
关键字实参

def describe_pet(pet_name,animal_type):
    print("\nI have a "+ animal_type +".")
    print("My "+animal_type+ "'s name is "+pet_name.title()+".")
#以下两种方式均可调用此函数
describe_pet(animal_type="hamster",pet_name='harry')
describe_pet(pet_name='harry',animal_type="hamster")~

使用关键字实参时,务必的指定函数定义中的形参名。
**

默认值

def describe_pet(pet_name,animal_type='dog'):
    print("\nI have a "+ animal_type +".")
    print("My "+animal_type+ "'s name is "+pet_name.title()+".")

describe_pet(pet_name='lele')#结合关键字实参
describe_pet("lele")#结合位置实参
describe_pet("lele",'cat')#'cat'替代'dog'

注意:当存在默认值时,将有默认值的形参写在后面。

**
返回值
函数并非直接显示输出,它可以处理一些数据,并返回一个或一组值。函数返回的值称为返回值。

def get_gormatted_name(first_name,last_name):
    full_name=first_name+" " + last_name
    return full_name.title()

musician=get_gormatted_name('jimi','hendrix')
print(musician)

运行结果:

Jimi Hendrix

**

让实参变为可选的

def get_gormatted_name(first_name,last_name,middle_name=''):
    if middle_name:
        full_name=first_name+" " +middle_name+" "+ last_name
    else:
        full_name = first_name + " "  + last_name
    return full_name.title()
musician=get_gormatted_name('chai','ming')
print(musician)
musician=get_gormatted_name('chai','min',"jin")
print(musician)

为让中间名变为可选的,可给形参middle_name指定一个默认值——空字符串,并在用户没有提供中间名时不使用这个形参。
**
返回字典

def build_person(first_name,last_name):
    person={'first':first_name,'last':last_name}
    return person

musician=build_person('jimi','hendrix')
print(musician)

运行结果:

{'first': 'jimi', 'last': 'hendrix'}

**
传递列表

def greet_user(usernames):
    """显示简单的问候语"""
    for username in usernames:
        print("Hello, "+username.title()+"!")

usernames=['aaa','bbb','ccc']
greet_user(usernames)

运行结果:

Hello, Aaa!
Hello, Bbb!
Hello, Ccc!

**
在函数中修改列表
在函数中对列表所做的任何修改都是永久性的(这个大家可以上机实验一下)

def print_models(unprinted_users,completed_users):
    while unprinted_users:
        current_user = unprinted_users.pop()
        print("Verifying user: " + current_user.title())
        confirmed_users.append(current_user)


def show_completed_models(unprinted_users,completed_models):
    print("\nThe following users hace been confirmed: ")
    print("unprinted_users: ")
    print(unprinted_users)
    print("confirmed_user: ")
    print(confirmed_users)
    for confirmed_user in confirmed_users:
        print(confirmed_user)

unprinted_users=['alice','brian','candace']
confirmed_users=[]

print_models(unprinted_users,confirmed_users)
show_completed_models(unprinted_users,confirmed_users)
**

禁止函数修改列表
如果像上面函数一样,列表作为实参传入函数,就会被修改。如果说不希望修改传入列表,则可通过向函数传入列表的副本来实现。

def print_models(unprinted_users,completed_users):
    while unprinted_users:
        current_user = unprinted_users.pop()
        print("Verifying user: " + current_user.title())
        confirmed_users.append(current_user)


def show_completed_models(unprinted_users,completed_models):
    print("\nThe following users hace been confirmed: ")
    print("unprinted_users: ")
    print(unprinted_users)
    print("confirmed_user: ")
    print(confirmed_users)
    for confirmed_user in confirmed_users:
        print(confirmed_user)

unprinted_users=['alice','brian','candace']
confirmed_users=[]

print_models(unprinted_users[:],confirmed_users)
show_completed_models(unprinted_users,confirmed_users)

这个与上一个函数基本一样,只是在print_models函数调用时更改为print_models(unprinted_users[:],confirmed_users) ,利用切片表示法创建副本。

**

传递任意数量的实参(个人觉得这个很牛逼)

def make_pizza(*toppings):
    print(toppings)

make_pizza('aaa')
make_pizza('aaa','bbb','ccc')

形参名*toppings中的星号是让python创建一个名为toppings的空元组,并将收到的所有的值都封装到这个元组当中。
同样,也可将任意数量实参与位置实参结合起来。

def make_pizza(size,*toppings):
	'''后面函数省略,自行脑补哈'''

**
使用任意数量的关键字实参

def build_profile(first,last,**user_info):
    profile={}
    profile['first_name']=first.title()
    profile['last_name']=last.title()
    for key,value in user_info.items():
        profile[key]=value
    return  profile

print(build_profile('zhang','san',location='China',sex='man'))

形参**user_info中的两个星号让python创建一个名为user_info的空
字典。

								参考书籍《Python编程从入门到实践》
							
										2020.7.26_第一周
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值