python - 将 var 的布尔值跟随到另一个文件中
问题描述
我的文本游戏中有两个文件。正在分配的变量将是 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 转移过来。它似乎不记得你什么时候给它在第一个文件中的价值,给第二个文件
导入时如何将分配给变量的值转移到另一个文件?
解决方案
我不确定你的要求是否符合你的最大利益。默认情况下,存储在变量中的值在您导入它们所在的文件时已经被保留。然而,这种类型的零星架构并不是真正被认为是好的实践。让我给你一些关于你的程序的反馈。首先让我们给它一些输入验证:
# 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 ,阅读此项目中的代码将使您更好地了解您可能想要的方式处理自己的项目。(函数、类和继承的基础知识)
推荐阅读
- html - 你如何在正方形纵横比内居中图像并保持响应能力?
- twitter-bootstrap - Bootstrap 固定到底部滚动问题
- html - 自定义 HTML 嵌入式 SVG 动画在 IE 11 中不起作用?
- python - 在 Flask SQLAlchemy 中反映数据库
- xcode - Xcode Archive:是否可以在没有登录用户和密码的情况下存档
- superpowered - SuperpoweredMixer 仪表值
- java - 使用 @Select 查询数据,但得到“无效的绑定语句(未找到)”
- arrays - React-Native 如何从 props 传递和访问数组数组中的数据
- c# - Xml 序列化 - 不存在数据时不包含元素
- arduino - werkstatt 词干课程上的 Arduino 编译错误(处理代码)