Python编程从入门到实践(第六部分 函数)

  • 函数是带名字的代码块
  • 要是在程序中需要多次完成相同任务的时候,那么不需要编写相同的代码,只需要调用执行这个任务的函数
  • 这样的话阅读,测试,修复都会更容易

定义和调用函数

# 定义函数
def greet_user(): # 定义的方法
    name = input("Please enter your name")
    print("Hello "+ name)
greet_user() # 调用的方法
# 向函数传递信息
def greet_user(user_name):
    print("Hello "+user_name.title()+"!")
greet_user("lewis")
# 实参和形参
# 在定义函数的时候user_name是形参——定义了函数需要完成这个功能所需要的信息。
# 在调用函数的时候user_name是实参——定义了调用函数的时候传递给函数的信息。
# 8-1 消息
def display_massage():
    print("I have learned nothing in this chapter")
display_massage()
# 8-2 喜欢的图书
def favourite_book(title):
    print("My favourite book is "+title)
favourite_book("Jane")

传递实参

  • 因为函数定义中可能包含多个形参,因此函数调用中可能也包含多个实参。
  • 所以向函数传递参数有时会很麻烦,下面介绍几种传递参数的方式
# 传递实参
# 位置实参
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("cat","doudou")
describe_pet("rat","xiaoxiong")

# 关键字实参 将实参和名字关联起来,所以即使位置出错也没关系
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 = "cat", pet_name = "doudou")

# 默认值 定义函数的时候给形参设定默认值,如果调用的时候不指定实参值则用默认值
# def describe_pet(animal_type = "cat", pet_name): 这样写可不行
def describe_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恤
def make_Tshirt(size,logo): # 这里接收的参数只能是str,如果说想输入整数怎么办呢?
    print("The Tshirt is "+size
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值