如何使定义生效?

2024-10-03 17:15:16 发布

您现在位置:Python中文网/ 问答频道 /正文

请参见以下示例:

import pygame
pygame.init()
x = 800
y = 600
programDisplay = pygame.display.set_mode((x,y))
pygame.display.set_caption('Title')
pygame.display.update()
programExit = False  
while not programExit:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            programExit = True
pygame.quit()
quit()

第二个例子:

import pygame
pygame.init()
x = 800
y = 600
programDisplay = pygame.display.set_mode((x,y))
pygame.display.set_caption('Title')
pygame.display.update()
programExit = False
def programQuit():
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            programExit = True
while not programExit:
    programQuit()
pygame.quit()
quit()

如何使第二个例子的定义起作用,使结果与第一个例子相同? 我认为这可能与全局变量和局部变量有关,但无法使其工作


Tags: importeventfalsetitleinitmodedisplayupdate
2条回答

给,我修好了

import pygame
pygame.init()
x = 800
y = 600
programDisplay = pygame.display.set_mode((x,y))
pygame.display.set_caption('Title')
pygame.display.update()
programExit = False

def checkForProgramQuit():
    global programExit
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            programExit = True



while not programExit:
    checkForProgramQuit()
    programDisplay.fill((255,255,255))
    pygame.display.update()

pygame.quit()
quit()

所修改的programExit变量是函数的局部变量

carcigentitate是非常正确的,但是这里有一些关于这里发生的事情的注释,以及一些将来可以避免这种情况的实践

programExit = False
def programQuit(programExit=False):
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            programExit = True   # Issue 1

while not programExit:
    programQuit()

问题1是这个赋值是在函数的作用域中创建一个新变量并设置它的值。它不会更改模块级变量programExit的值

一个更好的方法是让函数像这样将结果作为返回值传回

def programContinue():
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            return False
    return True

while programContinue():
    pass

同样通过反转函数返回的布尔逻辑,我认为事情变得更清楚了,我们可以去掉“not”。用这种方式表达while子句对我来说似乎更清楚一些。“pass”语句可以用一些日志记录或C.\答案的显示更新来代替

相关问题 更多 >