在下面的代码中,我试图获取用户输入,直到它匹配'type_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]
这个简单的事怎么样?
获取用户输入,检查它是否在字典中,如果是则返回,否则在无限循环中继续。
type_details = {'Plain':1.5,
'Waffle':2,
'Cup':1}
def getType():
while True:
user_in = input("Enter the preferred Type: ")
if user_in in type_details:
return user_in
user_in = getType()
print(f'You entered: {user_in}')
print(f'Type Price: {type_details[user_in]}')
每次调用getType()
(甚至在其自身内部)时,都会创建一个新的局部变量type
,如果它没有返回到调用函数,其内容将丢失。
调用type
中getType()
的内容未被修改。