python之函数

#函数带名字的代码块
#定义函数名
def greet_user():
    """执行语句"""
    print("Hello!")
#调用函数
greet_user()


#增加形参(parameter):执行语句需要的信息
def greet_user(username):
    print(f"Hello,{username.title()}!")
#调用函数,传递实参(argument)
greet_user('Li')


#传递实参: 位置实参;关键字实参;列表与字典。
#位置实参:顺序与形参一致。
def  describe_pet(animal_type, pet_name):
    """显示宠物的信息"""
    print(f"\nI have a {animal_type}.")
    print(f"My {animal_type}'s name is {pet_name.title()}")

describe_pet('hamster','harry')
#多次调用函数
describe_pet('dog','willie')

#关键字实参:每个实参由变量名和值组成。
def describe_pet(animal_type, pet_name):
    """显示宠物信息"""
    print(f"\nI have a {animal_type}.")
    print(f"My {animal_type}'s name is {pet_name.title()}")
describe_pet(animal_type='dog', pet_name='yi')
describe_pet(pet_name='bi', animal_type='dog')


#默认值
def describe_pet(pet_name,animal_type='dog'):
    print(f"\nI have a {animal_type}.")
    print(f"\nMy {animal_type}'s name is {pet_name.title()}.")

describe_pet('mi') #位置传参
describe_pet('mi','cat') #位置传参加修改默认值
describe_pet(pet_name='ki') #关键字传参
describe_pet(pet_name='po',animal_type='cat') #关键字传参,修改默认值


#返回值:调用返回值时,需要提供一个变量
def get_formatted_name(first_name,last_name):
    """返回整洁的姓名"""
    full_name = f"{first_name} {last_name}"
    return full_name.title()
#提供变量
musician = get_formatted_name('jimi','hendrix')
print(musician)

#让实参可选
def get_formatted_name(first_name, middle_name, last_name):
    full_name = f"{first_name} {middle_name} {last_name}"
    return full_name.title()

musician = get_formatted_name('john','lee','hooker')
print(musician)
#为空表示False
def get_formatted_name(first_name, last_name, middle_name = ''):
    if middle_name:
        full_name = f"{first_name} {middle_name} {last_name}"
    else:
        full_name = f"{first_name} {last_name}"
    return full_name.title()

musician = get_formatted_name('li','mi','ni')
musician = get_formatted_name('wu','pi')
musician = get_formatted_name(last_name='pi', first_name= 'wu',)
musician = get_formatted_name(middle_name= 'mi', last_name='mi', first_name='li')


#返回字典
def build_person(first_name, last_name):
    """返回一个字典,其中包含有关一个人的信息"""
    person = {'first': first_name, 'last': last_name}
    return person

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

#None表示变量没有值,可视为占位值,条件测试相当于False
def build_person(first_name, last_name, age=None):   
    """返回一个字典,其中包含有关一个人的信息"""
    person = {'first': first_name, 'last': last_name }
    if age:
        person['age'] = age
    return person

#注意混合传参
#后面的'hendrix'无法识别:musician = build_person(first_name='jimi', 'hendrix' )
musician = build_person('jimi', last_name='hendrix')
musician = build_person('jimi', 'hendrix',27)
print(musician)

def get_formatted_name(first_name, last_name):
    full_name = f"{first_name} {last_name}"
    return full_name.title()

#无限循环,ctrl+z停止循环
while True:
    print("\nPlease tell me your name:")
    print("(enter 'q' at any time to quit)")
    f_name = input("First name:")
    if f_name == 'q':
        break
    l_name = input("Last name:")
    if l_name == 'q':
        break

    formatted_name = get_formatted_name(f_name, l_name)
    print(f"\nHello,{formatted_name}!")

#传递列表
def greet_users(names):
    for name in names:
        msg = f"Hello,{name.title()}!"
        print(msg)

usernames = ['hannah','ty','margot']
greet_user(usernames)

#在函数中修改列表
#先创建一个要打印的列表,再创建一个空列表
unprinted_design = ['phone case', 'rotbot pendant','dodecahedron']
completed_models = []
#移到空列表
while unprinted_design:
    current_design = unprinted_design.pop()
    print(f"Printing model: {current_design}")
    completed_models.append(current_design)

print("\nThe following models have been printed:")
for completed_model in completed_models:
    print(completed_model)

#将以上编写为两个函数
def print_models(unprinted_designs, completed_models):
    while unprinted_designs:
       print(f"Printing model: {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)

unprinted_designs = ['phone case', 'rotbot pendant','dodecahedron']
completed_models = []

print_models(unprinted_designs, completed_models)
show_completed_models(completed_models)

#禁止函数修改列表,可向函数传递列表的副本
print_models(unprinted_designs[:], completed_models)


#传递任意数量的实参
# *P :名为P的元组
# **P :名为P的字典 
def make_pizza(*toppings):
    print(toppings)

make_pizza('pepperoni')
make_pizza('mushrooms', 'green peppers', 'extra cheese')

#遍历
def make_pizza(*toppings):    
    for topping in toppings:
        print(f"-{topping}")

make_pizza('pepperoni')
make_pizza('mushrooms', 'green peppers', 'extra cheese')

#结合使用位置实参和任意数量实参
def make_pizza(size, *toppings):
    print(f"\nMaking a {size}-inch pizza with the following toppings:")
    for topping in toppings:
        print(f"-{topping}")

make_pizza(16,'pepperoni')
make_pizza(12,'mushrooms', 'green peppers', 'extra cheese')

#使用任何数量的关键字实参
def buil_profile(first, last, **user_info):
    """创建一个字典,其中包含我们知道的有关用户的一切"""
    user_info['first_name'] = first
    user_info['last_name'] = last
    return user_info
#先打印实参传递的实参,后打印函数的执行结果
user_profile = build_person('albert', 'einstein', location='princeton', filed='physics')
print(user_profile)

#模块:扩展名为.py的文件,以下文件名为pizza.py
def make_pizza(size,*toppings):
    print(f"\nMaking a {size}-inch pizza with the following toppings:")
    for topping in toppings:
        print(f"-{topping}")

#以下为另一个文件,引用以上模块
#导入整个模块: import 模块名
import pizza
make_pizza(16,'pepperoni')
make_pizza(12,'mushrooms', 'green peppers', 'extra cheese')
#如果导入了整个函数,可以使用句点法来使用模块的任意函数。 模块名.函数名()
pizza.make_pizza()

#导入特定函数,可以直接引用,不用句点法。  from 模块名 import 函数名1,函数名2,函数名n
from pizza import make_pizza
 
#使用as给模块指定别名 import 模块名 as 别名
import pizza as pi

#导入模块中的所有函数,可以通过名称调用,无须句点法,不建议,可能会与当前名称相同而发生覆盖。from 模块名 import *
from pizza import *

#函数名:描述性名称,且只是要小写字母和下划线。
#形参过长时,输入左括号后按回车键,进入下一行,再按两次top键。
#多个函数时 可以在函数之间空两行

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值