簡體   English   中英

為什么我的全局變量不起作用? (Python)

[英]Why is my global variable not working? (Python)

我正在為學校制作一個基於文本的游戲,我希望它具有個性化的名稱功能,但是每當我越過定義變量的 function 時,其他函數只使用原始值,即 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 中它說“未定義的名稱'名稱'"

globalfunction 中使用,表示原本會被視為局部變量的名稱應該是 global。

def naming():
    global name

    ...

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

只要在調用name之前不調用prologue ,就不需要在全局 scope 中初始化name naming中的賦值就足夠了。


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

從名稱中刪除全局然后它應該工作

這是一個工作示例,但將名稱傳遞給序言function 而不是使用全局變量不是更好嗎? 這是另一個主題,但您必須避免使用全局。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM