【问题标题】:Why is my global variable not working? (Python)为什么我的全局变量不起作用? (Python)
【发布时间】:2021-01-22 09:09:24
【问题描述】:

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

【问题讨论】:

  • 鉴于这个 sn-p 代码,name 不需要是全局的。只需定义prologue 以获取名为name参数,并在您调用prologue 时将用户的输入作为参数传递。
  • 这能回答你的问题吗? In Python what is a global statement?
  • 感谢 chepner,但是 wdym 参数?

标签: python global-variables text-based


【解决方案1】:

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

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()

【讨论】:

  • 这不起作用,不。它说“名称”不是定义的变量
  • 这就是你想要的吗?如果可以,您可以选择它作为答案并投票吗?
  • 这点我不管了,好像没人明白
  • 那么你必须扩展或重构你的问题更容易理解(:
【解决方案2】:

global 用于一个函数中,以指示一个原本会被视为局部变量的名称应该是全局的。

def naming():
    global name

    ...

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

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


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

【讨论】:

  • 对于命名变量,我将如何进行变量更新,使其成为用户对其余代码的输入?不,“是”是输入变量的名称
  • “更新”是什么意思?一旦你设置了全局name,它就可供你的其余代码使用(至少,其余代码共享同一个全局命名空间)。
  • 我的意思是当我用用户输入定义它时,当我启动一个新函数时它恢复为0(默认值)
  • 它不需要默认值;摆脱那个任务。 (目前尚不清楚如何再次执行该分配。)
  • 但是当我将它分配为全局并且没有定义它时,它只是有一个错误,并说“名称”没有定义
【解决方案3】:

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

【讨论】:

  • 它没有。我从那个开始,但是当我启动一个新功能时,它会恢复为 0
猜你喜欢
  • 1970-01-01
  • 2019-09-27
  • 1970-01-01
  • 2016-12-30
  • 1970-01-01
  • 2022-12-20
  • 1970-01-01
  • 2019-01-20
  • 2015-06-25
相关资源
最近更新 更多