在下面的代码中,我尝试获取用户输入,直到它与“type\u details”字典中的值匹配为止。 但函数返回的是无效输入,而不是最终输入的正确值
Enter the preferred Type:fsafs
Please Choose the Type available in the Menu
Enter the preferred Type:Cup
Traceback (most recent call last):
File "C:\Users\Workspace-Python\MyFirstPythonProject\Main.py", line 186, in <module>
typeprice = type_details[typeValue]
KeyError: 'fsafs'
下面是代码
type_details = {'Plain':1.5,
'Waffle':2,
'Cup':1}
def getType():
type = input("Enter the preferred Type:")
if not ValidateString(type):
print("Type is not valid")
getType()
else:
check = None
for ct in type_details:
if ct.lower() == type.lower():
check = True
type=ct
break
else:
check = False
if not check:
print("Please Choose the Type available in the Menu")
getType()
return type
typeValue = getType()
typeprice = type_details[typeValue]
每次
getType()
被调用时(甚至在其内部),都会创建一个新的局部变量type
,如果它没有返回到调用函数,则其内容将丢失调用
getType()
中type
的内容未被修改像这样简单的事情怎么样
获取用户输入,检查它是否在dictionary中,如果在dictionary中返回,否则继续无限循环
相关问题 更多 >
编程相关推荐