我观看了bilibili视频 并总结了一些字典的知识,希望能帮到大家。
1.1 定义函数
def hello_world ():
print ("Hello,world")
hello_world()
1.1.1 向函数传递信息
def hello_world (usename):
print ("Hello,"+" "+usename.title())
hello_world('mojingqin')
1.2 传递实参
1.2.1 位置实参
def pet (animal_type,pet_name):
print("l have a "+animal_type+".")
print("my"+animal_type+"'s name is"+pet_name.title()+".")
pet('haster','harry')
1.2.2 关键字实参
def pet (animal_type,pet_name):
print("l have a "+animal_type+".")
print("my"+animal_type+"'s name is"+pet_name.title()+".")
pet(animal_type='haster',pet_name='harry')
1.3 函数返回值- return语句
def get_name(f_name,l_name):
full_name =f_name+" "+l_name
return full_name.title()
musician = get_name('mo','fen')
print (musician)
1.3.1 让实参变为可选的
def get_name(f_name,l_name,m_name=""):
if m_name:
full_name=f_name+""+m_name+""+l_name
else:
full_name =f_name+" "+l_name
return full_name.title()
musician = get_name('mo','fen')
print (musician)
doctor= get_name('mo','miao','jing')
print(doctor)
1.3.2 返回字典
def build_person (f_name,l_name):
person={'first':f_name,'last':l_name}
return person
build_person ('mo','di')
1.4 传递列表
def greet_users (names):
for name in names:
msg = "Hello,"+name.title()+"!"
print(msg)
usernames=['modi','mofen','moju']
greet_users(usernames)
1.5 传递任意数量的实参
# 传递任意数量的实参
def make_pizza(*toppings):
""" 打印顾客点的所有配料"""
print(toppings)
make_pizza('Pepperoni')
make_pizza('mushrooms','green peppers','extra cheese')
1.5.1 结合使用位置实参和任意数量实参
def make_pazzle(size,*toppings ):
print("\nMaking a "+str(size)+
"-inch pizza with the following toppings")
for topping in toppings:
print("- "+topping)
make_pazzle(16,'pepperoni')
make_pazzle(12,'mushrooms','green peppers ','extra cheese')
将函数存储在模块中
pizza.py
def make_pizza(size,*toppings):
print("\nMaking a " + str(size)+
"-inch pizza with the following toppings:")
for topping in toppings:
print("-" + topping)
import pizza
#python读取这个文件时,代码行import pizza让Python打开文件pizza.py,并将其中的
#所有函数都复制到这个程序中
pizza.make_pizza(16,'pepperoni')
pizza.make_pizza(12,'mushrooms','green peppers','extra cheese')