当前位置:   article > 正文

Python编程:从入门到实践(读书笔记:第8章 函数)_preat(so, hi , gender(person_name))5.定义一个函数say_hi_

preat(so, hi , gender(person_name))5.定义一个函数say_hi_default(), 有2个

coding=gbk

coding:utf-8!

定义函数

def great_user():
“”“显示简单的问候语”""
print(“Hello!”)
great_user()

向函数传递信息

print()
def great_user(username):
“”“显示简单的问候语”""
print("Hello, " + username.title() + “!”)
great_user(‘jessie’)

实参合形参

传递实参

位置实参

def describe_pet(animal_type, pet_name):
“”“显示宠物信息1"”"
print("\nI have a " + animal_type + “.”)
print("My " + animal_type + "'s name is " + pet_name.title() + “.”)
describe_pet(‘hamster’, ‘harry’)

调用函数多次

def describe_pet(animal_type, pet_name):
“”“显示宠物信息2"”"
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):
“”“显示宠物信息3"”"
print("\nI have a " + animal_type + “.”)
print("My " + animal_type + "'s name is " + pet_name.title() + “.”)
describe_pet(animal_type = ‘hamster’, pet_name = ‘harry’)

默认值

def describe_pet(pet_name, animal_type=‘dog’): # 注意这里修改了形参顺序
“”“显示宠物信息4"”"
print("\nI have a " + animal_type + “.”)
print("My " + animal_type + "'s name is " + pet_name.title() + “.”)
describe_pet(pet_name = ‘willie’) # 也可直接用describe_pet(‘willie’)

如果要描述的不是小狗,可显式地给animal_type提供实参,让Python忽略形参默认值

def describe_pet(pet_name, animal_type=‘dog’):
“”“显示宠物信息5"”"
print("\nI have a " + animal_type + “.”)
print("My " + animal_type + "'s name is " + pet_name.title() + “.”)
describe_pet(pet_name = ‘harry’, animal_type = ‘hamster’)

返回值 使用return语句

返回简单值

print()
def get_formatted_name(first_name, last_name):
“”“返回整洁的姓

声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop】
推荐阅读
相关标签
  

闽ICP备14008679号