函数

函数

定义函数
def greet_user():    #def告诉python你要定义一个函数
    """显示简单的问候语""" #函数注释
    print('Hello!')
greet_user()
实参和形参
username=input('>>:')
def greet_user(username):#此username为形参
    """显示简单的问候语"""
    print('Hello, ' + username.title() + '!')
greet_user(username) #此username为实参
位置实参
调用函数时,python必须将函数调用中的每个实参都关联到函数定义的一个形参。
最简单的关联方式是基于实参的顺序。
关键字实参
关键字实参是传递给函数的名称-值对
def describe_pet(animal_type,pet_name):
    """显示宠物的信息"""
    print('\nI have a ' + animal_type +'.')
    print('My ' + animal_type + "'s name is " + pet_name.title() + '.')
describe_pet(animal_type='dog',pet_name='wang cai') #调用函数时,向python明确地指出了各个实参对应形参
默认值
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='wang cai')
返回字典
def build_person(first_name,last_name,age=''):
    person={'first':first_name,'last':last_name}
    if age:
        person['age']=age
    return person
musician=build_person('jjc','wcx',age=27)
print(musician)
结合使用函数和while循环
def name(first_name,last_name):
    fullname=first_name + ' ' + last_name
    return fullname.title()
while True:
    print('输入名字:')
    f_name=input('firstname:')
    if f_name=='q':
        break
    l_name=input('lastname:')
    if l_name=='q':
        break
    get_name=name(f_name,l_name)
    print(get_name)
传递列表
def users(names):
    for name in names:
        msg='Hello ' + name.title()
        print(msg)
usernames=['jjc','wcx']
users(usernames)
禁止函数修改列表
unprinted_designs=['jjc','wcx','jjf','jjb',]
completed_models=[]
def print_models(unprinted_designs,completed_models):
    while unprinted_designs:
        current_design=unprinted_designs.pop()
        #模拟根据设计制作3D打印模型的过程
        print('current models:' + current_design)
        completed_models.append(current_design)
def show_completed_models(completed_models):
    #显示打印好的所有模型
    print('\nThe following models have been printed:')
    for completed_model in completed_models:
        print(completed_model)
#切片表示法[:]创建列表的副本,函数依然能完成任务,不影响列表本身
print_models(unprinted_designs[:],completed_models)
show_completed_models(completed_models)
print(unprinted_designs)
传递任意数量的实参
def make_pizza(*toppings):
    print(toppings)
#形参名的星号让python创建一个名为toppings的元组,并将收到的所有值封装到这个元组
使用任意数量的关键字实参
#两个星号让python创建一个空字典
def build_profile(first,last,**user_info):
    
    profile={}
    profile['first_name']=first
    profile['last_name']=last
    for key,value in user_info.items():
        profile[key]=value
    return profile
user_profile=build_profile('albert','einstein',
                            location='princeton',
                            field='physics')
print(user_profile)

将函数存储在模块中

将函数存储在被称为模块的独立文件中,再将模块导入到主程序中。
import语句允许在当前运行的程序文件中使用模块中的代码。
导入整个模块
要让函数是可导入的,得先创建模块。模块是扩展名为.py的文件,包含要导入到程序中的代码
创建一个包含函数make_pizza()的模块。为此我们将文件pizza.py中除函数make_pizza()之外的其他代码都删除:
def make_pizza(size,*toppings):
#pizza.py
def make_pizza(size,*toppings):
    '''概述要制作的披萨'''
    print('\nMaking a ' + str(size) + 
            '-inch pizza with the following toppings:')
    for topping in toppings:
        print('- ' + topping)
#making_pizzas.py
import pizza
pizza.make_pizza(16,'pepperoni')
pizza.make_pizza(12,'mushrooms','green peppers','entra cheese',)
导入特定的函数
from module_name import function_name
#通过逗号分隔函数名
from module_name import function_0,function_1
#对于之前的making_pizza.py示例
from pizza import make_pizza

make_pizza(16,'pepperoni')
make_pizza(12,'mushrooms','green peppers','entra cheese',)
使用as给函数指定别名
from pizzza import make_pizza as mp

mp(16,'pepperoni')
mp(12,'mushrooms','green peppers','entra cheese',)
#上面的import语句将函数make_pizza()重命名为mp()
#指定别名的通用语法如下
from module_name import function_name as fn
使用as给模块指定别名
import pizza as p
p.make_pizza(16,'pepperoni')
p.make_pizza(12,'mushrooms','green peppers','entra cheese',)
导入模块中所有函数
from pizza import *

转载于:https://www.cnblogs.com/rener0424/p/10111698.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值