我知道我的头衔听起来有点奇怪,但请一定要往下看:
available_things=["bike","smart tv","car","i-phone X"]
prices=[100,150,180,300]
additionals=["smart phone","xbox","ps4","laptop","computer accessories"]
things=raw_input("\nWhat you wish to get:")
selected_additionals=[]
for val in range(0,3):
selected_additionals.append(raw_input("Enter an additional item:"))
for selected_additional in selected_additionals:
if selected_additional not in additionals or selected_additional== " ":
print("\nSorry we don't have "+str(selected_additional)+"\nBut we will change it to a gift")
您可以在此处运行我的代码:https://repl.it/repls/WrySuburbanRabbit
我遇到的问题是,当它要求一个额外的项目时我什么都不说我的意思...我只是把它留空了它打印出的声明"抱歉我们没有但是我们会把它变成礼物"。但是我想要做的是,如果我在没有要求额外的物品时什么也没有,那么我就不会打印任何像#34;对不起我们没有但是我们会把它改成礼物和" #34 ;.我很确定我需要更改代码的最后三行。
答案 0 :(得分:0)
你可以试试这个:
for selected_additional in selected_additionals:
if selected_additional not in additionals and not selected_additional.strip():
print("\nSorry we don't have "+str(selected_additional)+"\nBut we will change it to a gift")
这应该有效,因为Python将空字符串视为False-y。
答案 1 :(得分:0)
您需要更改:
if selected_additional not in additionals or selected_additional== " ":
到
if selected_additional not in additionals and selected_additional.strip() != "":
这会检查输入的项目是否在您的其他列表中,并且输入的值不是空白(只是空格)。
这将消除额外的消息。但是如果你需要一定数量的输入,你应该考虑在找到空字符串时要求用户提供更多输入。