每次编译这段代码时,我都希望它能够遍历每个“if,elif”,直到找到匹配。因此它可以继续在屏幕上打印出给定的列表。
但令我惊讶的是,即使您输入“步枪”,它所做的只是给你“其他”声明。
这是我在Stackoverflow上的第一篇文章,如果我犯了一些错误,请原谅我。
非常感谢任何帮助,提前谢谢。
rifles = ["Ak47", "M4A1", "Aug", "Famas", "Galil"]
pistols = ["Glock", "USP", "Deagle", "P250", "Five-7", "Tec-9"]
shotguns = ["Buckshot", "Benelli", "M1319", "Sawed-Off"]
snipers = ["AWP", "SSG", "Cheytac", "Barret", "M24"]
grenades = ["Smoke", "High-Explosive", "Flash", "Concussion", "Molotov", "Incendiary"]
knives = ["Bayonette", "Karambit", "Machete", "Butterfly", "Katana"]
equipment = ["Kevlar", "Helmet", "Tactical-Shield", "Boots", "Nightvision"]
raw_input = input("Search: ")
def search():
if raw_input == "Rifles":
for ri in rifles:
print(ri)
break
elif raw_input is "Pistols":
for pi in pistols:
print(pi)
break
elif raw_input is "Shotguns":
for sho in shotguns:
print(sho)
break
elif raw_input is "Snipers":
for sni in snipers:
print(sni)
break
elif raw_input is "Grenades":
for gre in grenades:
print(gre)
break
elif raw_input is "Knives":
for kni in knives:
print(kni)
elif raw_input is "Equipment":
for equ in equipment:
print(equ)
else:
print("Try again...")
return
search()
答案 0 :(得分:0)
答案 1 :(得分:0)
您的代码可以用更简洁的方式表达,并且" pythonic"方式:
guns = {
"rifles" : ["Ak47", "M4A1", "Aug", "Famas", "Galil"],
"pistols" : ["Glock", "USP", "Deagle", "P250", "Five-7", "Tec-9"],
"shotguns" : ["Buckshot", "Benelli", "M1319", "Sawed-Off"],
"snipers" : ["AWP", "SSG", "Cheytac", "Barret", "M24"],
"grenades" : ["Smoke", "High-Explosive", "Flash", "Concussion", "Molotov", "Incendiary"],
"knives" : ["Bayonette", "Karambit", "Machete", "Butterfly", "Katana"],
"equipment": ["Kevlar", "Helmet", "Tactical-Shield", "Boots", "Nightvision"],
}
gun = raw_input("Search: ")
gun = gun.lower()
try:
print guns[gun]
except KeyError:
print "No gun of type %s" % gun
答案 2 :(得分:-1)
但令我惊讶的是,即使您输入步枪",它所做的只是给你"否则"言。
您的代码会检查"Rifles"
,而不是"rifles"
。如果你希望两者比较相等,你需要规范化字母大小写,例如,如下:
if raw_input.lower() == "rifles":
for ri in rifles:
...