在我的代码中使用字典并比较用户的输入,但是当用户输入任何内容并且只是输入时,输入程序就会结束并给我一个关键错误。我尝试使用'Try和Except',但这样程序循环到我不想要的开始处,我希望将程序保留在子循环中,直到用户输入边界内的某些东西。字典中的KeyError问题
ftablet=open("tablet.txt").readlines() devicelist=["phone","tablet"]
dtablet = {}
for line in ftablet:
(key,val) = line.split(":")
dtablet[str(key)] = val.strip(",")
while True:
counter=0
device=""
while device not in (devicelist):
device=input(What is your device?: ").lower().replace(" ","")
print()
if device == "tablet":
usermodel=""
while usermodel != (dtablet["phonemodels"]):
print(dtablet["modelquestion"])
usermodel=input("Enter MODEL Here: ").lower().replace(" ","")
if usermodel in (dtablet["phonemodels"]):
name=""
while name != (dtablet[usermodel]):
print(dtablet["namequestion"])
print("Enter any of these : ",(dtablet[model]))
name=input("Enter NAME Here: ").upper().replace(" ","")
if name in (dtablet[usermodel]):
storage=""
while storage != (dtablet[name]):
print(dtablet["storagequestion"])
print("Enter any of these : ",(dtablet[name]))
storage=input("Enter STORAGE Here: ").upper().replace(" ","")
if storage in (dtablet[name]):
problem=input("What is the PROBLEM with your tablet?\nEnter Here: ").upper()
print()
for word in problem.split():
if word in (dtablet[storage]):
print(dtablet[word])
print("Thanks for using my troubleshooting program")
counter=1
if counter==0:
print("We dont have your keyword in out database")
else:
print("Sorry! We do not have that device in out database please choose from the ones listed above.")
这是我的文本文件,我转换成名为'dtablet'的字典。
modelquestion:什么是您的平板电脑的型号?
namequestion:什么是您的平板电脑的名称?
storagequestion:什么是您的平板电脑的存储?
problemquestion:你的平板电脑有什么问题?
phonemodels:苹果,三星,索尼
苹果:IPAD1,IPAD2,IPAD3
三星:TAB1,TAB2,TAB3
索尼:XPERIAZ2,XPERIAZ3,XPERIAZ4
IPAD1: 16GB,32GB,64GB
IPAD2:16GB,32GB,64GB
IPAD3:16GB,32GB,64GB
TAB1:16GB,32GB,64GB
TAB2:16GB,32GB,64GB
TAB3:16GB,32GB,64GB
XPERIAZ1:16GB,32GB ,64GB
XPERIAZ2:16GB,32GB,64GB
XPERIAZ3:16GB,32GB,64GB
16GB:破裂,断裂
32GB:破裂,断裂
64GB:破裂,断裂
破碎:问题=破裂的解决方案=带上手机到维修 店
BROKEN:问题=破碎的解决方案=把你的手机送到维修店
提供整个回溯可能会有帮助。 – Arpan
@Arpan突出显示仅在问题标记为[tag:python]标记时才起作用。有一个挂起的编辑添加它。 –
你确定有一个关键''模型''如果你打印出'dtable.keys()'会怎么样? –