函数
思维导图
代码
main.py
# 定义函数
# def greet_user():
# # 文档字符串
# """"显示简单的问候语"""
# print("Hello!")
# greet_user()
# 向函数传递信息
# def greet_user(username):
# """显示简单的问候语"""
# print("Hello, " + username.title() + "!")
# greet_user('jesse')
# 位置实参 顺序很重要
# 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('hamster', 'harry')
# describe_pet('dog', 'willie')
# 关键字实参
# 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(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='willie')
# 忽略形参的默认值
# describe_pet(pet_name='harry', animal_type='hamster')
# 等效的函数混用
# 一条名为Willie的小狗
# describe_pet('willie')
# describe_pet(pet_name='willie')
# # 一只名为Harry的仓鼠
# describe_pet('harry', 'hamster')
# describe_pet(pet_name='harry', animal_type='hamster')
# describe_pet(animal_type='hamster', pet_name='harry')
# 避免实参错误
# 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()
# 返回值
# 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('jimi', 'hendeix')
# print(musician)
# musician = get_formatted_name('john', 'lee', 'hooker')
# print(musician)
# 返回字典
# def build_person(first_name, last_name, age = ''):
# """返回一个字典,其中包含有关一个人的信息"""
# # person是字典类型
# 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("\nHello, " + formatted_name + "!")
# 传递列表
# def greet_users(names):
# """向列表中的每位用户都发出简单问候"""
# for name in names:
# msg = "Hello, " + name.title() + "!"
# print(msg)
# usernames = ['hannah', 'ty', 'margot']
# greet_users(usernames)
# 在函数中修改列表
# 首先创建一个列表,其中包含一些要打印的设计
# unprinted_designs = ['iphone case', 'robot pendant', 'dodecahedron']
# completed_models = []
# # 模拟打印每个设计,直到没有未打印的设计为止
# # 打印每个设计后,都将其移到列表completed_models中
# while unprinted_designs:
# current_design = unprinted_designs.pop()
# # 模拟根据设计制作3D打印模型的过程
# print("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):
# """
# 模拟打印每个设计,直到没有未打印的设计为止
# 打印每个设计后,都将其移到列表completed_models中
# """
# while unprinted_designs:
# current_design = unprinted_designs.pop()
# # 模拟根据设计制作3D打印模型的过程
# print("Printing model: " + current_design)
# completed_models.append(current_design)
# def show_completed(completed_models):
# """显示打印好的模型"""
# print("\nThe following models have been printed:")
# for completed_model in completed_models:
# print(completed_model)
# unprinted_designs = ['iphone case', 'robot pendant', 'dodecahedron']
# completed_models = []
# print_models(unprinted_designs[:], completed_models)
# print(unprinted_designs)
# show_completed(completed_models)
# 禁止函数修改列表 将列表的副本传递给函数,如上
# 传递任意数量的实参
# *toopings 让Python创建一个名为toopings的空元组
# def make_pizza(*toopings):
# """概述要制作的比萨"""
# print("\nMaking a pizza with the following toppings:")
# for tooping in toopings:
# print("- " + tooping)
# make_pizza('pepperoni')
# make_pizza('mushrooms', 'green peppers', 'extra cheese')
# 结合使用位置实参和任意数量实参
# 任意数量实参必须放在后面
# def make_pizza(size, *toopings):
# """概述要制作的比萨"""
# print("\nMaking a " + str(size) + "-inch pizza with the following toppings:")
# for tooping in toopings:
# print("- " + tooping)
# make_pizza(16, 'pepperoni')
# make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
# 使用任意数量的关键字实参
# **user_info 让Python创建一个名为user_info的空字典
# def build_profile(first, last, **user_info):
# """创建一个字典,其中包含我们知道的有关用户的一切"""
# profile = {}
# profile['first_name'] = first
# profile['last_name'] = last
# for Key, Value in user_info.items():
# # user_info字典里面的内容移到profile里 扩展字典语句
# profile[Key] = Value
# return profile
#
#
# user_profile = build_profile('albert', 'einstein', location='princeton', field='physics')
# print(user_profile)
# 导入整个模块
def make_pizza(size, *toppings):
"""概述要制作的比萨"""
print("\nMaking a " + str(size) + "-inch pizza with the following toppings:")
for topping in toppings:
print("- " + topping)
making_pizza.py
# 导入整个模块
# import main
# main.make_pizza(16, 'pepperoni')
# main.make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
# 导入模块中特定的函数
# from main import make_pizza
# make_pizza(16, 'pepperoni')
# make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
# 使用as给函数指定别名
# from main import make_pizza as mp
# mp(16, 'pepperoni')
# mp(12, 'mushrooms', 'green peppers', 'extra cheese')
# 使用as给模块指定别名
# import main as p
# p.make_pizza(16, 'pepperoni')
# p.make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
# 导入模块中所有函数
from main import *
make_pizza(16, 'pepperoni')
make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')