while循环使用input()python

时间:2015-09-13 00:17:48

标签: python python-3.x

我正在尝试让这段代码工作但不知何故它无法正常工作

我想检查用户输入(它必须与我的火车站列表匹配)

我应该使用while循环,直到用户使用正确的火车站,然后继续问2

首先输入的是:出发站? 第二个输入(第二个问题):到站?

到目前为止,这是我的代码:

stations = ["Schagen", "Heerhugowaard", "Alkmaar", "Castricum", "Zaandam", "Amsterdam Sloterdijk", "Amsterdam Centraal",
        "Amsterdam Amstel", "Utrecht Centraal", "Hertogenbosch", "Eindhoven", "Weert", "Roermond", "Sittard",
        "Maastricht"]
start = input("Wat is je begin station?")
end = input("Wat is je eind station?")

if start in stations:
    print('Je vertrekt vanaf:', start)
else:
    print("wrong station")

3 个答案:

答案 0 :(得分:0)

试试这个:

stations = ["Schagen", "Heerhugowaard", "Alkmaar", "Castricum", "Zaandam", "Amsterdam Sloterdijk", "Amsterdam Centraal",
        "Amsterdam Amstel", "Utrecht Centraal", "Hertogenbosch", "Eindhoven", "Weert", "Roermond", "Sittard",
        "Maastricht"]
mapped = [x.lower().strip() for x in stations] # lowercased stations
start = input("Wat is je begin station?").lower().strip()

while not start.lower().strip() in mapped:
    print("wrong station")
    start = input("Wat is je begin station?").lower().strip()
start = stations[mapped.index(start)]

end = input("Wat is je eind station?").lower().strip()
print('Je vertrekt vanaf:', start)

while not end in stations:
    print("wrong station")
    end = input("Wat is je eind station?").lower().strip()

end = stations[mapped.index(start)]
# print the end station here.

答案 1 :(得分:0)

questions = {1: "Wat is je begin station?", 2: "Wat is je eind station?"}
ques_number = 1     

while ques_number<=2:
  answer = input(questions[ques_number])
  if answer in stations:
    print('Je vertrekt vanaf:%s'%answer)
    ques_number += 1
  else:
    print("wrong station")

这会不断向用户询问电台。你可以增加号码。根据需要提出问题。

答案 2 :(得分:0)

希望这不是功课,因为您应该尝试使用文档来解决这些问题(https://wiki.python.org/moin/WhileLoop

我会尝试这样的东西..虽然可以通过允许按数字选择站点或模糊匹配字符串来使其更好。

stations = ["Schagen", "Heerhugowaard", "Alkmaar", "Castricum", "Zaandam", "Amsterdam Sloterdijk", "Amsterdam Centraal","Amsterdam Amstel", "Utrecht Centraal", "Hertogenbosch", "Eindhoven", "Weert",  "Roermond", "Sittard","Maastricht"]

print "Stations"
for i in range(len(stations)):
     print(str(i) + " " + stations[i])

start = input("Wat is je begin station?")
while start not in stations:
        print("wrong station")
        start = input("Wat is je begin station?")

print('Je vertrekt vanaf: {0}'.format(start))

end = input("Wat is je eind station?")
while end not in stations:
       print("wrong station")
      end = input("Wat is je eind station?")

print('Je aankomt op: {0}'.format(end))