python中的函数不会返回分配给变量的最新字符串值

2024-05-28 21:04:07 发布

您现在位置:Python中文网/ 问答频道 /正文

在下面的代码中,我尝试获取用户输入,直到它与“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]

Tags: the代码inifchecktypenotdetails
2条回答

每次getType()被调用时(甚至在其内部),都会创建一个新的局部变量type,如果它没有返回到调用函数,则其内容将丢失

调用getType()type的内容未被修改

像这样简单的事情怎么样

获取用户输入,检查它是否在dictionary中,如果在dictionary中返回,否则继续无限循环

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]}')

相关问题 更多 >

    热门问题