Code:[ZachxPKU/Python Crash Course]
Python Crash Course
Chapter 8 Functions
8.1 Defining a function
def greet_user():
"""Display a simple greeting."""
print("Hello!")
greet_user()
8.1.1 Passing information to a function
def greet_user(username):
"""Display a simple greeting."""
print(f"Hello, {
username.title()}!")
greet_user('Jesse')
8.1.2 Arguments and Parameters
TRY IT YOURSELF
- message.py
- favorite_book.py
8.2 Passing arguments
8.2.1 Positional arguments
def describe_pet(animal_type, pet_name):
"""Display information about a pet."""
print(f"\nI have a {
animal_type}.")
print(f"My {
animal_type}'s name is {
pet_name.title()}.")
describe_pet('hamster', 'harry')
Multiple function calls
def describe_pet(animal_type, pet_name):
"""Display information about a pet."""
print(f"\nI have a {
animal_type}.")
print(f"My {
animal_type}'s name is {
pet_name.title()}.")
describe_pet('hamster', 'harry')
describe_pet('dog', 'willie')
Order matters in positional arguments
def describe_pet(animal_type, pet_name):
"""Display information about a pet."""
print(f"\nI have a {
animal_type}.")
print(f"My {
animal_type}'s name is {
pet_name.title()}.")
describe_pet('harry', 'hamster')
8.2.2 Keyword arguments
def describe_pet(animal_type, pet_name):
"""Display information about a pet."""
print(f"\nI have a {
animal_type}.")
print(f"My {
animal_type}'s name is {
pet_name.title()}.")
describe_pet(animal_type = 'hamster', pet_name = 'harry')
def describe_pet(animal_type, pet_name):
"""Display information about a pet."""
print(f"\nI have a {
animal_type

本文详细介绍了Python中函数的定义与使用,包括参数传递、返回值、列表操作及任意数量参数的处理等。通过丰富的实例,帮助读者掌握Python函数的高级用法。
最低0.47元/天 解锁文章
713

被折叠的 条评论
为什么被折叠?



