我创建了一个编号为1-10的名字列表。我希望用户能够输入数字(1-10)来选择名称。我有以下代码,但仍然无法让它工作。我是python的新手。谢谢你的帮助
def taskFour():
1 == Karratha_Aero
2 == Dampier_Salt
3 == Karratha_Station
4 == Roebourne_Aero
5 == Roebourne
6 == Cossack
7 == Warambie
8 == Pyramid_Station
9 == Eramurra_Pool
10 == Sherlock
print''
print 'Choose a Base Weather Station'
print 'Enter the corresponding station number'
selection = int(raw_input('Enter a number from: 1 to 10'))
if selection == 1:
selectionOne()
elif selection == 2:
selectionTwo()
elif selection == 3:
selectionThree()
答案 0 :(得分:5)
您正在遵循反模式。当有一百万个不同的电台或每个电台有多个数据时你打算做什么?
您无法手动selectionOne()
完成selectionOneMillion()
。
这样的事情怎么样:
stations = {'1': "Karratha_Aero",
'2': "Karratha_Station",
'10': "Sherlock"}
user_selection = raw_input("Choose number: ")
print stations.get(user_selection) or "No such station"
输入/输出:
1 => Karratha_Aero
10 => Sherlock
5 => No such station
答案 1 :(得分:2)
首先,你需要一个真实的清单。您当前拥有的内容(1 == Name
)既不是列表,也不是有效语法(除非您在每个名称后面都有变量)。将您的列表更改为:
names = ['Karratha_Aero', 'Dampier_Salt', 'Karratha_Station', 'Roebourne_Aero', 'Roebourne', 'Cossack', 'Warambie', 'Pyramid_Station', 'Eramurra_Pool', 'Sherlock']
然后,将底部代码更改为:
try:
selection = int(raw_input('Enter a number from: 1 to 10'))
except ValueError:
print "Please enter a valid number. Abort."
exit
selection = names[selection - 1]
然后 selection
将成为用户选择的名称。
答案 2 :(得分:0)
以下是适合您的工作代码:
def taskFour():
myDictionary={'1':'Name1','2':'Name2','3':'Name3'}
print''
print 'Choose a Base Weather Station'
print 'Enter the corresponding station number'
selection = str(raw_input('Enter a number from: 1 to 10'))
if selection in myDictionary:
print myDictionary[selection]
#Call your function with this name "selection" instead of print myDictionary[selection]
taskFour()