names1 = ['bob', 'jack', 'adam', 'dom' ]
num = int(input('Please select a number? ')) # select number 1
for name in names + num: # This is where my problem is
print (s)
names1 = ['bob', 'jack', 'adam', 'dom' ]
num = int(input('Please select a number? ')) # select number 1
name_array = "names" + str(num)
for name in name_array: # This is where my problem is
print(name)
parent_list = [['bob', 'jack', 'adam', 'dom'], ["alpha", "beta", "gamma"], ["India", "USA"]]
num = int(input('Please select a number? '))
#Checking if the value entered can be accessed or not.
if num<3:
for name in parent_list[num]:
print name
else:
print "Please enter a number between 0-2"
词典:
parent_dict = {0:['bob', 'jack', 'adam', 'dom'], 1:["alpha", "beta", "gamma"], 2:["India", "USA"]}
num = int(input('Please select a number? '))
if num<3:
for name in parent_dict[num]:
print name
else:
print "Please enter a number between 0-2"
from __future__ import print_function
try:
input = raw_input
except NameError:
input = raw_input # Python 2/3 compatibility
names = ["bob", "jack", "adam", "dom"]
def prompt(prompt, *valid):
try:
s = input(prompt).strip()
while s not in valid:
s = input(prompt).strip()
return s
except (KeyboardInterrupt, EOFError):
return ""
choices = list(enumerate(names))
print("Choices are: {0}".format(", ".join("{0}:{1}".format(i, name) for i, name in choices)))
try:
s = prompt("Your selection? ", *(str(i) for i, _ in choices))
i = int(s)
except ValueError:
print("Invalid input: {0}".format(s))
else:
print("Thanks! You selected {0}".format(choices[i][1]))
演示:
$ python foo.py
Choices are: 0:bob, 1:jack, 2:adam, 3:dom
Your selection? 0
Thanks! You selected bob
$ python foo.py
Choices are: 0:bob, 1:jack, 2:adam, 3:dom
Your selection? foo
Your selection? 1
Thanks! You selected jack
This also correctly handles the scenario of invalid inputs and int() throwing a ValueError as well as silencing ^D (EOFError) and ^C (KeyboardInterrupt) exceptions.
这里我们刚刚连接了
name_array
值。希望对你也有用。你知道吗有两个选项,您可以使用
nested list
结构或dictionary
。你知道吗嵌套列表:
词典:
如果已经在脚本中创建了变量,则可以选择创建字典或变量嵌套列表:
正确的方法是使用list或dict数据结构来存储一组选项,然后编写一个简单的函数来提示用户输入,并根据“有效选项”进行验证。你知道吗
示例:
演示:
注意:你可以做
for name in eval("names{0:d}".format(num)):
但是不要这样做,因为使用eval()
任意评估输入被认为是邪恶的,非常危险的。见:Is using eval() in Python bad pracice?相关问题 更多 >
编程相关推荐