为什么我的全局变量不起作用?(Python)



我正在为学校制作一个基于文本的游戏,我希望它具有个性化的名称功能,但每当我通过定义变量的函数时,其他函数都只使用原始值,即0。这里有一个例子:

global name = 0 #this part is at the top of the page, not actually just above the segment
def naming();
print("A long, long time ago, there was a person who was born very ordinary, but would live to become very extraordinary.n")
time.sleep(2)
while True:
name=input("Who are you? Give me your name.n")
choice = input(f'You said your name was {name}, correct?n')
if choice in Yes:
prologue();
else:
return
def prologue():
print(f'Very well, {name}. You were born with a strange gift that nobody could comprehend, at the time. You were born with the Favor of the Gods.')

这正是我所拥有的代码段;运行";,它一直工作得很好,直到def-prolog((:我已经排除了它是其他东西的可能性,因为在replicator窗口中,它说"未定义的名称"name";

这是一个工作示例,但将name传递给prologe函数而不是使用全局变量不是更好吗?这是另一个主题,但你必须避免使用global。

import time
name = 0 #this part is at the top of the page, not actually just above the segment
def naming():
global name
print("A long, long time ago, there was a person who was born very ordinary, but would live to become very extraordinary.n")
time.sleep(2)
while True:
name=input("Who are you? Give me your name.n")
choice = input(f'You said your name was {name}, correct?n')
if choice == "Yes":
prologue()
else:
return
def prologue():
global name
print(f'Very well, {name}. You were born with a strange gift that nobody could comprehend, at the time. You were born with the Favor of the Gods.')

if __name__ == '__main__':
naming()

global在函数内部使用,以指示原本被视为局部变量的名称应该是全局的。

def naming():
global name
...
def prologue():
print(f'Very well, {name}. ...')

只要在调用name之前不调用prologue,就不需要在全局范围内初始化name;则CCD_ 5内部的分配就足够了。


另外,你指的是choice in ["Yes"],或者更好的是,choice == "Yes"

从名称中删除global,那么它应该可以工作

最新更新