范例一:
pets = ['dog','cat','dog','goldfish','cat','rabbit','cat']
print(pets)
while 'cat' in pets:
pets.remove('cat')
print(pets)
print("###")
print(pets)
范例二:
responses = {}
polling_active = True
while polling_active:
name = input("\nWhat is your name?")
response1 = input("Which mountain would you like to climb someday? ")
responses[name] = response1
repeat = input("Would you like to let another person respond?(yes/no) ")
if repeat == 'no':
polling_active = False
print("\n---Poll Results ---")
for name,respon in responses.items():
print(name + "would like to climb" + respon + ".")
范例三
sandwich_orders = ['tudou','doufu','kaoya']
finished_sandwiches = []
while sandwich_orders:
sandwich_target = sandwich_orders.pop()
print("I made your tuna sandwich:" + sandwich_target)
finished_sandwiches.append(sandwich_target)
print(finished_sandwiches)
范例四:函数传参
#coding:gbk
def greet_user(username):
#"""显示简单的问候语"""
print("Hello, " + username.title() + "!")
greet_user('lihua')
范例五:函数位置实参|多次调用
#coding:gbk
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')
范例六:函数关键字实参
#coding:gbk
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 = 'hamster',pet_name = 'harry')
范例七:函数的默认值 【默认形参不能在函数形参的第一位】
#coding:gbk
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')
#【由于显式地给animal_type 提供了实参,因此Python将忽略这个形参的默认值。】
describe_pet(pet_name='harry', animal_type='hamster')
范例七:函数返回值
#coding:gbk
def get_formatted_name(first_name,last_name):
#返回整洁的姓名
full_name = first_name + ' ' + last_name
return full_name.title()
musician = get_formatted_name('yin','zitao')
print(musician)
范例八:对函数实参的有无进行判断
#coding:gbk
def get_formatted_name(first_name,last_name,middle_name=''):
#返回整洁的姓名
if middle_name:
full_name = first_name + ' ' + middle_name + ' ' + last_name
return full_name.title()
else:
full_name = first_name + ' ' + last_name
return full_name.title()
musician = get_formatted_name('yin','tao','zi')
print(musician)
范例九:使用函数构建字典
#coding:gbk
def build_person(first_name,last_name):
#返回一个字典,其中包含有关一个人的信息
person = {'first':first_name,'last':last_name}
return person
musician = build_person('jimi','hendrix')
print(musician)
#例二
#coding:gbk
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','23')
print(musician)
范例十:while循环与函数结合使用
#coding:gbk
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 + "!")
范例十一:使用函数遍历列表
#coding:utf-8
def greet_users(names):
#向列表中的每位用户都发出简单的问候
for name in names:
msg = "Hello, " + name.title() + "!"
print(msg)
usernames = ['hannah','lisi','zhangsan']
greet_users(usernames)
范例十二:在函数中修改列表
#coding:utf-8
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)
#范例二
#coding:utf-8
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_models(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)
show_completed_models(completed_models)
#切片开辟新的空间
#coding:utf-8
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_models(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 = []
unprinted_designs1 = unprinted_designs[:]
print_models(unprinted_designs,completed_models)
show_completed_models(unprinted_designs1)
#向函数传递列表副本,列表本身没有改变
#coding:utf-8
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_models(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 = []
unprinted_designs1 = unprinted_designs[:]
print_models(unprinted_designs[:],completed_models)
show_completed_models(completed_models)
范例十三:【函数接收多个传参*】
#coding:utf-8
def make_pizza(*toppings):
#打印顾客点的所有配料
print(toppings)
make_pizza('latiao','xiaoyugan','douya')
##遍历元组
#coding:utf-8
def make_pizza(*toppings):
#打印顾客点的所有配料
print("\nMaking a pizza with the following toppings:")
for topping in toppings:
print("-" + topping)
make_pizza('latiao','xiaoyugan','douya')
##函数同时接收实参、位置参数和多个形参
#coding:utf-8
def make_pizza(size,*toppings):
#打印顾客点的所有配料
print("\nMaking a " + str(size) + " -inch pizza with the following toppings:")
for topping in toppings:
print("-" + topping)
make_pizza('5','latiao','xiaoyugan','douya')
###函数接收多个参数,包括实参、形参,且将未知形参内容存储到字典中
#coding:utf-8
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)