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

时间:2020-10-07 11:59:16

标签: python global-variables text-based

我正在为学校制作一款基于文本的游戏,并且希望它具有个性化的名称功能,但是每当我经过定义变量的函数时,其他函数仅使用原始值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():我已经排除了它可能是其他东西的可能性,因为在复制器窗口中它说“未定义”名称“名称””

3 个答案:

答案 0 :(得分:0)

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

def naming():
    global name

    ...

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

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


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

答案 1 :(得分:0)

从名称中删除全局,则它应该起作用

答案 2 :(得分:0)

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