# 定义函数defgreet_user():# 定义的方法
name =input("Please enter your name")print("Hello "+ name)
greet_user()# 调用的方法# 向函数传递信息defgreet_user(user_name):print("Hello "+user_name.title()+"!")
greet_user("lewis")# 实参和形参# 在定义函数的时候user_name是形参——定义了函数需要完成这个功能所需要的信息。# 在调用函数的时候user_name是实参——定义了调用函数的时候传递给函数的信息。# 8-1 消息defdisplay_massage():print("I have learned nothing in this chapter")
display_massage()# 8-2 喜欢的图书deffavourite_book(title):print("My favourite book is "+title)
favourite_book("Jane")
传递实参
因为函数定义中可能包含多个形参,因此函数调用中可能也包含多个实参。
所以向函数传递参数有时会很麻烦,下面介绍几种传递参数的方式
# 传递实参# 位置实参defdescribe_pet(animal_type, pet_name):print("\nI have a "+animal_type)print("My "+animal_type+"'s name is "+pet_name.title())
describe_pet("cat","doudou")
describe_pet("rat","xiaoxiong")# 关键字实参 将实参和名字关联起来,所以即使位置出错也没关系defdescribe_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 ="cat", pet_name ="doudou")# 默认值 定义函数的时候给形参设定默认值,如果调用的时候不指定实参值则用默认值# def describe_pet(animal_type = "cat", pet_name): 这样写可不行defdescribe_pet(pet_name, animal_type="cat"):print("\nI have a "+animal_type)print("My "+animal_type+"'s name is "+pet_name.title())
describe_pet(pet_name="Doudou")
describe_pet("doudou")# 避免实参错误 记住traceback的方法# 8-3 T恤defmake_Tshirt(size,logo):# 这里接收的参数只能是str,如果说想输入整数怎么办呢?print("The Tshirt is "+size