是什么导致在赋值错误之前引用了这个变量? [英] What's causing this variable referenced before assignment error?

查看:44
本文介绍了是什么导致在赋值错误之前引用了这个变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我正在使用的代码:

This is the code that I am working with:

import pygame

global lead_x
global lead_y
global lead_x_change
global lead_y_change

lead_x = 300
lead_y = 300
lead_x_change = 0
lead_y_change = 0


def playerUpdateMovement():
    keys = pygame.key.get_pressed()
    if keys[pygame.K_LEFT]:
        lead_x_change = -1
    elif keys[pygame.K_RIGHT]:
        lead_x_change = 1
    else:
        lead_x_change = 0

    if keys[pygame.K_UP]:
        lead_y_change = -1
    elif keys[pygame.K_DOWN]:
        lead_y_change = 1
    else:
        lead_y_change = 0

    lead_x += lead_x_change
    lead_y += lead_y_change

无论出于何种原因运行此脚本时,都会出现错误:

When I run this script for whatever reason, I get the error:

第30行...赋值前引用的局部变量lead_x

不能在函数中调用全局变量吗?这很奇怪,我是 Python 新手.

Can global variables not be called in functions? This is weird and I am new to python.

推荐答案

如果您需要从函数内部修改全局变量,则需要使用 global 关键字:global lead_x 在这种情况下,在任何任务之前

If you need to modify a global variable from inside a function you need to use the global keyword: global lead_x in this case, before any assignment

这篇关于是什么导致在赋值错误之前引用了这个变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆