如果用户输入不正确,我如何使我的代码循环

goa*_*oat 0 python loops if-statement

今天我想我可能有一个简单的问题.我有一些代码要求用户选择1到10之间的数字,这是指列表.如果用户输入的输入不正确,即55我要循环的代码是什么,并要求他们做出另一个选择.到目前为止,我有以下代码,但我不确定如何使其循环.提前致谢

    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:
    print 'You have selected Karratha Aero as your Base Station'
elif selection == 2:
    print 'You have selected Dampier Salt as your Base Station'
elif selection == 3:
    print 'You have selected Karratha Station as your Base Station'
elif selection == 4:
    print 'You have selected Roebourne Aero as your Base Station'
elif selection == 5:
    print 'You have selected Roebourne as your Base Station'
elif selection == 6:
    print 'You have selected Cossack as your Base Station'
elif selection == 7:
    print 'You have selected Warambie as your Base Station'
elif selection == 8:
    print 'You have selected Pyramid Station as your Base Station'
elif selection == 9:
    print 'You have selected Eramurra Pool as your Base Station'
elif selection == 10:
    print 'You have selected Sherlock as your Base Station'
else:
    print 'You have made an error. Please chose a number from 1 to 10'
Run Code Online (Sandbox Code Playgroud)

Pat*_*shu 7

首先,您应该有一个所有可能基站的列表,而不是手动构建要打印的十个字符串,如

basestations = ["", "Karratha Aero", "Dampier Salt", ...]

然后你可以这样做:basestations[1]获取索引1处的字符串(第一个索引是0),例如一般情况下basestations[selection].现在,您只需要一个打印语句来表示所有十种可能性.(提示:您可以通过执行连接两个字符串stringa + stringb)

其次,使用while循环.如果未进行有效选择,则while循环的条件应为true,如果进行了有效选择,则为false.不同的if是,一个while遗嘱的主体会在它到达终点后返回并检查条件,如果它再次成立,它将再次执行.