如何解决为什么我的全局变量不起作用? 蟒蛇
我正在为学校制作一款基于文本的游戏,并且希望它具有个性化的名称功能,但是每当我经过定义变量的函数时,其他函数仅使用原始值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():我已经排除了它可能是其他东西的可能性,因为在复制器窗口中它说“未定义”名称“名称””
解决方法
global
用于内部函数,该函数指示应被视为局部变量的名称应改为全局名称。
def naming():
global name
...
def prologue():
print(f'Very well,{name}. ...')
只要在调用prologue
之前不调用name
,就不需要在全局范围内初始化name
; naming
中的分配就足够了。
此外,您的意思是choice in ["Yes"]
,或者更好的是choice == "Yes"
从名称中删除全局,则它应该起作用
,这是一个有效的示例,但是将名称传递给序言函数而不是使用全局变量会更好吗?这是另一个主题,但是您必须避免使用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()
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。