用户在python中输入 [英] User input in python
问题描述
我正在编写一个脚本,它为用户提供了很多可供选择的选项,例如
I am working on a script which provides the user a lot of options to choose from, e.g
选择功能选项
- A - 做 A(描述)
- B - 做 B(描述)
- C - 做 C(描述)
- D - 做 D(描述)
(如果选择 A)选择 A 子功能
- A1 - 做 A1(描述)
- A2 - 做 A2(描述)
- A3 - 做 A3(描述)
(如果选择 B)选择 B 子功能
- B1 - 做 B1(描述)
- B2 - 做 B2(描述)
- B3 - 做 B3(描述)
等等...
每个选项可供选择,并根据选择,python程序将继续.请注意在每个选项之前我提供了一个print
Each option is available for the option to choose and based on the choice, the python program will proceed. Please note before each option I provide a print
print ''' Enter Directory
1. Current Working Directory
2. CHoose other folder'''
然后我使用 raw_input
来接受用户输入,在这种情况下,这基本上意味着对用户的大量提示(和凌乱的代码).我怀疑这可能不是最好的设计.
Then I use raw_input
to accept user inputs, which basically in this case means a lot of prompts for the user (and messy code) . I suspect this might not be the best design .
我的问题是我做对了还是有我错过的替代方法?
My question is am I doing it correctly or is there an alternative approach which I have missed out?
推荐答案
一种选择(哈!)是将选项的结构存储在一个变量中.
One option (ha!) is to store the structure of the options in a variable.
例如,(在您的脑海中)将菜单"定义为包含这些值的某些子集的字典:
For example, (in your mind) define "a menu" as a dict which contains some subset of these values:
- 问题" - 这是显示菜单时要问的问题 - 选择 B 子功能"
- 描述" - 这是您选择进入此菜单的选项 - 例如,对于选择 B 子选项",这将是B" - 您选择在这里获得的答案.第一个菜单没有这个.
- 子选项" - 这是此处的菜单列表.
- "code" - 如果它存在,而不是显示此菜单,而是运行此代码.
对于你上面给出的例子
def function_for_A1():
print "You chose A1!"
menus={"question":"Choose function Options","answers":[
{"description":"A","question":"Choose A Subfunctions","answers":[
{"description":"A1","code":function_for_A1},
{"description":"A2","code":function_for_A2},
]},
{"description":"B","question":"Choose B Subfunctions","answers":[
{"description":"B1","code":function_for_A1},
{"description":"B2","question":"B2 sub-suboption","answers":[...]},
]},
}
一旦你有了这个结构,给定当前菜单,显示它就相当容易 - 运行代码(如果存在),否则显示问题,并为每个答案显示一个数字和描述".一旦他们选择了一个数字,找到菜单,清洗,冲洗,重复.你可以让菜单函数递归,所以如果他们选择0 - back",那么你从当前函数返回.
Once you have this structure, given the current menu, displaying it is fairly easy - run the code (if it exists), otherwise display the question, and for each of the answers display a number and the "description". Once they select a number, find the menu, wash, rince, repeat. You could make the menu function recursive, so if they select "0 - back", then you return from the current function.
完成!
这篇关于用户在python中输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!