0

我创建了一个编号为 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()
4

3 回答 3

5

您正在遵循反模式。当有 100 万个不同的站点,或者每个站点有多个数据时,你会怎么做?

您不能一直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
于 2013-04-30T13:19:42.613 回答
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然后将是用户选择的名称。

于 2013-04-30T13:13:13.667 回答
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()
于 2013-04-30T13:15:05.720 回答