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

Why is my global variable not working? (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 prologue(): 我已经排除了它是其他东西的可能性,因为在复制器 window 它说“未定义名称 'name'”

global 内部 函数中使用,以指示将被视为局部变量的名称应该改为全局名称。

def naming():
    global name

    ...

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

只要在调用name之前不调用prologue,就不需要在全局范围内初始化namenaming里面的赋值就够了。


此外,您的意思是 choice in ["Yes"] 或者,更好的是,choice == "Yes"

从名称中删除全局,然后它应该可以工作

这是一个工作示例,但将名称传递给 prologue 函数而不是使用全局变量不是更好吗?这是另一个主题,但你必须避免使用 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()