''' This program allows users to add citites and distances
as well as calculating the cost of their flight.'''
City = []
Distance = []
Canada_city = ''
flight = False
while Canada_city != 'exit':
print('Type exit to quit\n')
Canada_city = input('Enter a Canadian city\n')
City.append(Canada_city)
if Canada_city == 'exit':
quit
else:
km = int(input('How far is the city from Ottawa in km?\n'))
Distance.append(km)
done = input('Would you like to save these cities & distances? y/n \n')
if done == 'y':
print ('Your final cities list is ',City)
print ('Your final distance list is ',Distance)
choice = input('What city would you like to travel to from your list\n')
所以现在城市被添加到列表中,距离也是如此。但我不知道如何制作它,所以当选择一个城市时,与它相关的距离也会在等式中使用,而无需人工挑选。起价为100美元,之后每公里0.5美元。
while flight == False:
if choice in City:
print ('You have chose to fly to: ',choice)
print('Please wait while we determine your flight path')
下面的语句只会记录输入的最近距离并计算,但不会计算与输入城市相关的距离。
print ("Your cost to travel is",0.5*km+100)
flight == True
break
Cost(choice)
else:
print ('City not found in your list')
choice = input('What city would you like to travel to from your list\n')
else:
continue
例如,我可能会进入多伦多和400公里,它将正确计算300美元的成本。但是如果我将另一个距离为600公里的城市添加到列表中,并选择再次计算多伦多,那么它将使用距离600而不是与其一起输入的距离400。所以基本上如何在城市被召唤时如此,它计算与它一起输入的距离,而不是最近输入的距离?
答案 0 :(得分:1)
我最好的建议是使用字典。这些值存储在键中。
keys = {"Montreal":250}
当您致电keys["Montreal"]
时,您会收到250的值。
要创建新的,您可以使用keys["Toronto"] = 500
您的最终结果:keys = {"Toronto":500,"Montreal":250}
然后,只要您打电话,就可以在程序中随时使用这些值。
答案 1 :(得分:0)
使用字典
data = {}
并输入信息
data['Toronto'] = 400
data['Another'] = 600
获取信息
print(100 + data['Toronto'] * 0.5)
print(100 + data['Another'] * 0.5)
BTW:您还可以创建二维字典 - 距离为[from][to]
,
data = {}
data['Toronto'] = {}
data['Toronto']['Another'] = 400
data['Toronto']['Other'] = 600
data['Another'] = {}
data['Another']['Other'] = 1000
print(100 + data['Toronto']['Another'] * 0.5)
print(100 + data['Another']['Other'] * 0.5)
答案 2 :(得分:0)
您的计划存在的问题是,在您的距离计算中,您使用的是km变量,该变量最近在input()
中更新,询问距离城市的距离。相反,您需要找到城市在城市列表中的位置,并使用距离列表中的正确值。
您可以使用.index()
方法找到项目在列表中的哪种方式。
因此,您的计算代码变为:
i = City.index(choice)
d = Distance[i]
print ("Your cost to travel is", 0.5*d+100)
希望这有帮助!
答案 3 :(得分:0)
要将关联的距离存储到城市,使用关联数组会更方便。在Python中,这些被称为“dictionaries”。
而不是
Distance = [] ... City.append(Canada_city) ... Distance.append(km)
DO
Distance = {}
...
Distance[Canada_city] = km
然后通过
获得与城市choice
相关的距离
Distance[choice]