需要帮助修复我在 Python 制作的游戏

Need help fixing a game I made in Python

我在python接到了一个任务,要做一个水果机游戏,但是我遇到了一个小问题,它涉及到一个变量。它是说我在赋值之前引用了变量,即使我已经赋值了它。它似乎将其作为局部变量而不是全局变量来读取。我该如何解决这个问题。

这是最麻烦的部分

Credit = 1

def main(): #the main program
    Credit = Credit - 0.20
    print("Credit remaining = " + Credit) #tells the player the amount of credit remaining
    print("\n *** The Wheel Spins... *** \n") #Spinning the wheel
    print(input("\n (press enter to continue) \n"))

错误信息

line 19, in main
   Credit = Credit - 0.20
UnboundLocalError: local variable 'Credit' referenced before assignment

任何时候你想在 python 的另一个函数中写入全局变量,你应该让 python 知道你想使用全局变量。在主插入的第一行之前:

global Credit

this question 的答案可能对您有所帮助(复制粘贴在下方)。

If you want to simply access a global variable you just use its name. However to change its value you need to use the global keyword.

E.g.

global someVar
someVar = 55

This would change the value of the global variable to 55. Otherwise it would just assign 55 to a local variable.

The order of function definition listings doesn't matter (assuming they don't refer to each other in some way), the order they are called does.

您都阅读了 更改了 Credit 的值 您需要将您的代码重写为以下内容:

def main(): #the main program(edited)
    global Credit
    Credit = Credit - 0.20

您没有声明您的变量。在函数外部声明的变量不会作用于函数。要使用该变量,您必须在这种情况下将信用作为全局变量。然后一切都会好起来的。祝一切顺利.

x = something #declearing a local variable
def something():
    global x # setting local x variable as global variable, so x can be use into as well as outside of the function
    print x
    #or do something u like .