python - 将多个 if 语句缩减为一个表

标签 python database

我正在将 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/

相关文章:

python - 安装 Tensorflow 时权限被拒绝

database - 如果水平分布的数据库丢失了一个分片,该分片的数据会怎样?

sql - INSTEAD OF INSERT 触发器和标识列使用 View

python - 为什么Iphone不显示python 2.7.x发送的附件

python - 在不隐藏构造函数、可选参数或功能的情况下继承时避免使用长构造函数

python - 将列表写入 csv 文件,而不是按需要写入

ios - SQLite 数据库崩溃

php - 如何在使用 mysql 插入期间连接和保存名字和姓氏?

database - 数据库中的键值

python - 如何在 python 中连接列表,但如果元素相等,则只保留相邻列表的最后一个或第一个元素