Day 6 python 从入门到实践——函数

  • 定义函数
#定义函数
def greet_user():
    """显示简单问候语"""
    print("Hello")
greet_user()

#向函数传递信息
def greet_user(user_name):
    """显示简单问候语"""
    print("Hello "+user_name.title()+" !")
greet_user("Li lei")
  • 形参与实参——在上述函数定义中使用的user_name为形参,在函数调用中使用的"Li lei"为实参
#位置实参——多个实参与函数中形参一一按顺序对应
def describe_pet(animal_type,pet_name):
    """显示宠物信息"""
    print("\nI have a "+animal_type.title())
    print("My "+animal_type.title()+"'s name is "+pet_name.title()+".")
describe_pet("hamster","harry")

#关键字实参——将实参与形参一一对应列出
def describe_pet(animal_type,pet_name):
    """显示宠物信息"""
    print("\nI have a "+animal_type.title())
    print("My "+animal_type.title()+"'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.title())
    print("My "+animal_type.title()+"'s name is "+pet_name.title()+".")
describe_pet(pet_name="willie")
describe_pet("willie")
describe_pet(pet_name = "lily", animal_type = "cat")
describe_pet("lily","cat")

#避免实参错误——当提供的实参过多或者过少将出现错误

#practice
def make_shirt(size,word):
    print("\nThe shirt's size is "+str(size)+".")
    print("And the word is "+word.title()+".")
make_shirt(75,"love")
make_shirt(size=75,word="love")

#
def make_shirt(size="medium",word="I love Python"):
    print("\nThe shirt's size is "+size.title()+".")
    print("And the word is "+word.title()+".")
make_shirt()

#返回值——函数处理后返回的值
#返回简单的值
def get_formatted_name(first_name,last_name):
    """返回整洁的姓名"""
    full_name = first_name+" "+last_name
    return full_name.title()
musician = get_formatted_name("jimi","hendrix")
print(musician)

#让实参变得可选
def get_formatted_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_formatted_name("john","hoker","lee")
print(musician)

#返回字典
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("jimi","hendrix",age = 27)
print(musician)

#结合使用函数与while
def get_formatted_name(first_name,last_name):
    """返回整洁的姓名"""
    full_name = first_name+" "+last_name
    return full_name.title()
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(formatted_name)
    
#practice
def city_country(city_name,country_name):
    print(city_name+", "+country_name)
city_country("A","B")

#传递列表
def greet_users(names):
    """向列表中每位用户发出问候"""
    for name in names:
        print("Hello "+name.title()+" !")
usernames = ["hannah","ty","margot"]
greet_users(usernames)

#使用函数修改列表
def print_models(unprinted_designs, completed_modles):
    """
    模拟打印每个设计,知道没有未打印的设计
    打印每个设计后,将其移动到完成列表completed_modles中
    """
    while unprinted_designs :
        current_design = unprinted_designs.pop()
        print("Print models: "+current_design.title())
        completed_models.append(current_design)
def show_completed_models(completed_models):
    """显示打印好的模型"""
    print("\nThe following models has been finished:")
    for completed_model in completed_models:
        print(completed_model.title())
unprinted_designs = ["iphone case","robot pendant", "dodecahedron"]
completed_models = []
print_models(unprinted_designs,completed_models)
show_completed_models(completed_models)#函数完成的功能应当简单单一具体

#传递列表副本
print_models(unprinted_designs[:],completed_models)

#practice
def show_magicians(magicians):
    for magician in magicians:
        print("\n"+magician.title())


# def make_great(magicians):
    # for magician in magicians:
        # change_magician = magician+" the Great"
        # magicians[magicians.index(magician)] = change_magician

# magicians = ["eric","bruce","tom"]
# make_great(magicians)
# print(magicians)

#传递任意数量的实参-*toppings使得创建一个名为toppings的空元组
def make_pizza(*toppings):
    """概述需要制作的比萨"""
    print("\nThe following toppings :")
    for topping in toppings:
        print("- "+topping)
make_pizza("mushrooms","green pepers","extra cheese")

#结合使用位置实参与任意数量实参,位置实参放在前面
def make_pizza(size,*toppings):
    """概述需要制作的比萨"""
    print("\nThe following toppings :")
    for topping in toppings:
        print("- "+topping+"- size: "+str(size))
make_pizza(16,"mushrooms","green pepers","extra cheese")

#使用任意数量得关键字实参
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",
    filed = "physics")
print(user_profile)

  • 导入模块与函数
# coding : utf-8
#导入整个模组
#import module_name
import pizza
pizza.make_pizza(16,"pepperoni")

#导入特定函数
#from module_name import fuction_0, function_1, function_2
from pizza import make_pizza
make_pizza(16,"pepperoni")

#使用as为函数指定别名
#from module_name import function_name as fn
from pizza import make_pizza as mp  

#使用as为模块指定别名
#import module_name as mn
import pizza as p

#导入模块中所有函数
#from pizza import *

你可能感兴趣的:(学习记录)