我正在将 children 选择自己的冒险书翻译成 Python 程序,例如,“如果你选择 x 转到第 y 页,或者如果你选择 a 转到第 b 页”
虽然这个程序可以运行,但到本书结尾时将有超过 100 个 if 语句,有没有办法创建一个表,将用户输入与页面列表进行比较。我在研究时看到的一个示例显示了与此类似的表格:
#this would hold the potential user inputs
[0,0,0,0,0,0]
[0,0,0,0,0,0]
[0,0,0,0,0,0]
但是我不确定如何实现它
#imports the pages of the book from another python file
from Content import *
clrscrn = (chr(27) + "[2J")
def page0():
print "\n %s" % page1
page0()
#User input loop
while True:
inp = raw_input(">>> ").lower()
#clears the screen then prints the variable (page)
if inp == '3':
print clrscrn
print '%s' % page3
if inp == '10':
print clrscrn
print '%s' % page10
if inp == '5':
print clrscrn
print '%s' % page5
if inp == '14':
print clrscrn
print '%s' % page14
#quits python
elif inp == 'quit':
raise SystemExit
最佳答案
每个 if
语句的唯一区别是您访问的是哪个页面变量。由于您希望在用户输入“14”时到达 page14
,因此您可以使用 globals()
返回的字典以动态方式访问页面变量。
因此,您实际上根本不需要数百个 if
语句。您可以改用以下行。
print clrscrn
print globals()['page' + inp]
关于python - 将多个 if 语句缩减为一个表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42603764/