当我遇到困境时,我一直在练习python。我无法弄清楚如何通过列表循环原始输入(使用while)以生成正确的错误消息。
places_to_visit = {1 : 'London', 2 : 'Rome', 3: 'Amsterdam', 4: 'Paris'}
place = raw_input("where are you travelling to?:")
#gives the cost of travelling to a specific destination
while str(place) != ____:
place = raw_input("Sorry i did not catch that. please enter your destination again:")
if str(place) == ____:
def travel_cost(place):
if place == "London":
return 2000
elif place == "Rome":
return 3000
elif place == "Amsterdam":
return 3000
elif place == "Paris":
return 5000
任何帮助将不胜感激。 感谢
答案 0 :(得分:2)
如果您将费用存储在适当的dict
中,则可以执行以下操作:
#!/usr/bin/env python
# coding: utf-8
places_with_costs = {"London": 2000, "Rome": 3000, "Amsterdam": 3000, "Paris":5000}
while True:
place = raw_input("Where are you travelling to?: ")
if place in places_with_costs:
print "Your trip is {}.".format(places_with_costs[place])
else:
print "Unable to find your destination. Try again."
答案 1 :(得分:1)
您可以使用in
运算符查看元素是否在序列中
while place not in places_to_visit.values()
在这种情况下,您可以测试他们输入的字符串是否在您dict