详记函数(下)--Python入门笔记7

函数的使用可以让我们明了、方便的处理数据。本篇文章接着专栏的上篇文章(详记函数(上)–Python入门笔记)在函数的使用中,讲解知识点。

老样子,代码中的注释也可以多看两眼哦 !


变量作用域

局部变量:函数内部定义的变量。
全局变量:定义在函数外面的变量,全局可用。

nonlocal 关键字:用于在嵌套函数中修改外部函数的变量
示例:

x = 10  # 全局变量

def func():
    global x  # 声明使用全局变量
    x = 20
    y = 30  # 局部变量 y
    
    def inner():
        nonlocal y  # 修改外部函数的变量 y
    print(y)    # 输出 30

func()
print(x)        # 输出 20

global 关键字
它可以用于访问和修改全局变量,而nonlocal 只能修改嵌套作用域里的变量。

x = 1  # 全局变量x 初始值为1
y = 0  # 全局变量y 初始值为0
def outer():
   x = 10  # 非全局的外部变量x
   
   def inner():
       global y    # 引用全局y
       nonlocal x  # 引用外部函数的x
       y = 20      # 修改y的值
       x = 30      # 修改x的值
   
   inner()
   print("外部函数变量 x:", x)  # 输出: 20 (在内部通过nonlocal使用并修改外部变量)

outer()
print("全局变量 x:", x) # 输出 1 (函数内的同名变量x 并没有影响全局变量x)
print("全局变量 y:", y) # 输出 20 (函数内部使用了global改变了全局变量)

使用global可以实现在函数内部影响全局变量。


实用的函数

前面介绍了很多函数的基础知识,接下来会讲一些较实用的函数知识。

让实参变成可选的

为了让我们在使用函数时只提供必须填的信息,我们可以设置默认值来处理没有填信息的情况。

使用默认值

class Person:    # 定义了一个面对人的类(后面会讲‘类’)
    def say_hello(self, name=None):#name 是可选的,默认 None
        if name is None:
            return "Hello, there!"#如果没有提供 name,返回通用问候
        return f"Hello, {name}!"  #否则返回带名字的问候

p = Person()
print(p.say_hello())       #没有名字时输出: "Hello, there!"
print(p.say_hello("Bob"))  #有名字时输出: "Hello, Bob!"

使用None作为默认值
对于更复杂的情况,可以使用None作为默认值:

def create_person(name, age=None, job=None):
    person = {"name": name}
    if age is not None:
        person["age"] = age
    if job is not None:
        person["job"] = job
    return person

print(create_person("Alice"))  # 输出: {'name': 'Alice'}
print(create_person("Bob", age=30))  # 输出: {'name': 'Bob', 'age': 30}

在信息密集的情况下就可以使用这种返回方式


使用可变参数
对于数量不定的可选参数,可以使用*args和**kwargs收集所有的可选参数:

def print_info(title, *args, **kwargs):
    print(f"Title: {title}")
    if args:
        print("Positional arguments:", args)
    if kwargs:
        print("Keyword arguments:", kwargs)

print_info("Hello")
print_info("Hello", 1, 2, 3, name="Alice", age=25)

再提醒一下,单星号(元组),一定要写在双星号(字典)之前。


实用建议:建议将必选参数放在前面,可选参数放在后面。这样可以保证前面的排版整齐。


返回字典

函数可返回任何类型的值,包括列表和字典这样较为复杂的数据。

def create_person():		# 创建一个函数
    person = {'name': 'Alice', 'age': 25, 'city': 'New York'}
    return person

result = create_person()	# 调用函数
print(result)  #输出: {'name':'Alice','age':25,'city':'New York'}

结合使用函数和whilie循环

将函数与while循环结合使用是一种强大的编程技术,可以创建灵活的重复逻辑和交互式程序。

下面的代码展示了使用while循环,让交互可以持续运行的例子:

def get_formatted_name(first_name, last_name):
    """整洁的姓名"""
    full_name = f"{first_name}{last_name}"
    return full_name.title()

while True:
    print("\nPlease tell me your name:")
    print("(enter 'q' at any time to quit)")
    f_name = input("First name:")
    if f_name == 'q':		# 在输入了q时退出循环
        break
    
    l_name = input("Last name:")
    if l_name == 'q':		# 在输入了q时退出循环
        break
    
    formatted_name = get_formatted_name(f_name, l_name)
    print(f"\nHello, {formatted_name}!")

在函数中修改列表

相比于返回一个新列表,直接用函数修改列表有一些优势:

  • 不创建副本:不用创建一个新列表来操作原列表,节省内存。
  • 适合大列表:处理大型数据时性能更优。
  • 意图明确:使用函数让操作的意图明确。
  • 共享函数:多个函数可以协作处理同一个列表。

下面将举一些修改列表的例子


直接修改原列表(原地修改)

def add_item_to_list(lst, item):
    """直接修改传入的列表"""
    lst.append(item)  # 原地操作,修改原列表
    print("函数内列表:", lst)

my_list = [1, 2, 3]
print("原始列表:", my_list)  # 输出: [1, 2, 3]

add_item_to_list(my_list, 4)
print("函数外列表:", my_list)  # 输出: [1, 2, 3, 4]
""" 输出:
原始列表: [1, 2, 3]
函数内列表: [1, 2, 3, 4]
函数外列表: [1, 2, 3, 4]
"""

使用切片赋值修改列表
这个知识在之前的列表那章里讲过,再复习一遍:
列表[:],中括号里面不加索引就是整体切片。

def replace_list_content(lst, new_items):
    """使用切片赋值替换列表内容"""
    lst[:] = new_items  # 替换原列表所有元素

my_list = [1, 2, 3]
replace_list_content(my_list, ['a', 'b', 'c'])
print("函数外列表:", my_list)  # 输出: ['a', 'b', 'c']

想要对列表或者字典进行更多的操作,只需要把对列表或字典的操作写进函数中,然后直接使用函数名来代替繁杂的代码即可。


往期回顾:
——>控制流基础:if语句-Python入门笔记
——>while循环-Python入门笔记


持续更新ing

The End

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值