You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中如何退出函数且保持全局变量level值不变?

解决方案:在level始终为0时停止执行eg_func()

由于你无法修改level变量,我们可以通过引入执行标记的方式,控制eg_func()仅运行一次后就停止执行,同时保持level的值不变。以下是两种可行的实现方式:

方法1:新增全局标记变量

通过添加一个额外的全局变量记录eg_func()是否已执行,以此作为判断条件:

import pygame, sys
from pygame.locals import *

pygame.init()

level = 0
x = 0
# 初始化标记:eg_func尚未执行
eg_func_executed = False

def eg_func():
    global x, eg_func_executed
    x = 10
    # 执行后将标记设为True
    eg_func_executed = True

def eg_func2():
    global x
    x = 2

# 原代码未定义playing,这里补充初始化避免报错
playing = False

while True:
    # 仅当level为0且函数未执行过时才调用
    if level == 0 and not eg_func_executed:       
        eg_func()

    if playing == True:
        eg_func2()   

    print(x)

    # 添加pygame退出逻辑,避免无限循环卡死
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()

pygame.quit()
sys.exit()

方法2:利用函数自身属性

不需要额外全局变量,直接给eg_func添加一个属性来记录执行状态,更简洁:

import pygame, sys
from pygame.locals import *

pygame.init()

level = 0
x = 0

def eg_func():
    global x
    x = 10
    # 执行后标记函数已运行
    eg_func.has_run = True

# 初始化函数的自定义属性
eg_func.has_run = False

def eg_func2():
    global x
    x = 2

playing = False

while True:
    # 判断level为0且函数未运行过
    if level == 0 and not eg_func.has_run:       
        eg_func()

    if playing == True:
        eg_func2()   

    print(x)

    # 添加退出逻辑
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()

pygame.quit()
sys.exit()

补充说明

  • 两种方法都能在level始终为0的前提下,让eg_func()仅执行一次后停止,完全不修改level变量。
  • 原代码中playing变量未定义,已补充初始化避免运行报错;同时添加了pygame的事件监听逻辑,确保程序可以正常退出。

内容的提问来源于stack exchange,提问作者Pyton

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 02:00:04