我似乎无法让我的代码正常工作。我相信有许多不同的方法可以让这段代码用更少的行工作,但这是我目前在理解它的同时编写代码的唯一方法。
当我使用诸如 500 之类的值表示最大成本和"b"表示desired_features我只返回斯卡伯勒时,当我应该返回时:巴塞罗那、加利福尼亚、科孚岛、斯卡伯勒和惠特比,因为它们都有海滩并且成本低于 500。
print("INPUT:")
max_cost = input( "How many coins do you want to? " )
print("""nDesired holdiday features:
b = beach
c = culture
h = hot
m = mountains
""")
desired_features = input( "Enter string of first letters of desired features: " )
#barcelona
if (max_cost >="320" and desired_features == ("bch","b","c", "h", "bc", "bh", "cb", "ch", "hb", "hc" )):
destination_list = "Barcelona"
else:
destination_list = []
print (destination_list)
#California
if (max_cost >="750" and desired_features == ("bhm" , "b", "h", "m", "bh", "bm", "hb", "hm", "mb", "mh" )):
destination_list = "California"
else:
destination_list = []
print (destination_list)
#Corfu
if (max_cost >="300" and desired_features == ("bh", "b", "h", "hb")):
destination_list = "Corfu"
else:
destination_list = []
print (destination_list)
#Paris
if (max_cost >="250" and desired_features == "c"):
destination_list = "Paris"
else:
destination_list = []
print (destination_list)
#Rome
if (max_cost >="300" and desired_features == ("ch", "c", "h", "hc")):
destination_list = "Rome"
else:
destination_list = []
print (destination_list)
#Scarborough
if (max_cost >="45" and desired_features == "b"):
destination_list = "Scarborough"
else:
destination_list = []
print (destination_list)
#Switzerland
if (max_cost >="450" and desired_features == ("cm", "c", "m", "mc")):
destination_list = "Switzerland"
else:
destination_list = []
print (destination_list)
#Whitby
if (max_cost >="60" and desired_features == ("bc", "c", "b", "bc")):
destination_list = "Whitby"
else:
destination_list = []
print (destination_list)
# holiday_data = [ ["Barcelona", 320, ["beach", "culture", "hot"]],
# ["California", 750, ["beach", "hot", "mountains"]],
# ["Corfu", 300, ["beach", "hot"]],
# ["Paris", 250, ["culture"]],
# ["Rome", 300, ["culture", "hot"]],
# ["Scarborough", 45, ["beach"]],
# ["Switzerland", 450, ["culture", "mountains"]],
# ["Whitby", 60, ["beach", "culture"]]
# ]
我不认为你在海滩等测试中的意思是 ==。 也许"在"?
if (max_cost >="300" and desired_features in ("ch", "c", "h", "hc"))
请注意,列表是使用括号而不是括号定义的,并使用"in"运算符而不是 == 来确定字符串是否在列表中。
好吧,我不是一个讨厌元组的人,只是更习惯于列表......如果您喜欢,请使用元组(上图)。
原因是因为你正在使用这个
if (max_cost >="45" and desired_features == "b")
它返回"Scarborough",因为只有"Scarborough"具有"b"的单个所需特征
例如
if (max_cost >="450" and desired_features in ("cm", "c", "m", "mc"))
已编辑以更改为元组:)