我的基于文本的游戏中有两个文件。正在分配的变量将为keep_note。
如果输入“ Take”,则将布尔值True分配给have_note-001 但是在下一个文件中,如果have_note_001 == True,我得到一个错误提示 have_note-001未定义
If keep_note is == "Take":
have_note_001 = True
然后在下一个文件中,我希望将True值传递到下一个文件。
If have_note_001 == True: print("This Value Is True")
keep_paper = input("Do you want to Leave the piece of paper or Take it? > ")
if keep_paper == "Take":
have_note_01 = True
if have_note_01 == True:
print("You have chosen to keep the piece of paper")
print("You leave the house with the note(" + note_001 + ")")
这是我的下一个文件
from intros.intro_001 import have_note_001
if have_note_01 == True:
print("True")
elif have_note_01 == False:
print("False")
在文件中,导入正在进行。 我正在导入have_note_001。它只是不转移值True。似乎不记得在第一个文件中给第二个文件赋值时的情况
导入后如何将分配给变量的值转移到另一个文件?
答案 0 :(得分:1)
我不确定您要的是您的最大利益。默认情况下,当您导入变量来源时,存储在变量中的值已被保留。但是,这种零星的体系结构并不是真正的好习惯。让我给您一些有关您程序的反馈。首先让我们进行一些输入验证:
# start off setting keep_paper to nothing
keep_paper = ''
# As long as the player does not enter 'take' or 'leave' we are going to
# keep asking them to enter a proper response.
while keep_paper not in ['take', 'leave']:
# here we are going to "try" and ask the player for his choice
try:
# here we are getting input from the user with input(...)
# then converting it into a string with str(...)
# then converting it to lowercase with .lower()
# all together str(input(...)).lower()
keep_paper = str(input("Do you want to Leave the piece of paper or Take it? > ")).lower()
# if the player entered an invalid response such as "53" we will go back
# to the beginning and ask for another response.
except ValueError:
print("Sorry, I didn't understand that.")
# ask the user to provide valid input
continue
if have_note_01 == True:
print("True")
elif have_note_01 == False:
print("False")
现在让我们解决您的问题的主要主题。将值分配给变量会继续导入。正如我已经提到的,这通常不是您想要的,这就是为什么大多数Python程序都包含以下代码的原因:
if __name__ == "__main__":
# do xyz....
这可确保xyz
仅在文件正在运行时运行,而在文件导入时不会运行。
出于良好的考虑,我建议您结帐:https://github.com/phillipjohnson/text-adventure-tut/tree/master/adventuretutorial,仔细阅读该项目中的代码可以使您更好地了解自己想如何解决自己的项目。 (函数,类和继承的基础)