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

时间:2018-09-09 03:31:30

标签: python python-3.x

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

2 个答案:

答案 0 :(得分:2)

这样简单的事情怎么样?

获取用户输入,检查它是否在字典中,然后返回,否则继续在无限循环中进行。

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

答案 1 :(得分:0)

每次调用lst = int( input("Enter list values : ")) def count(lst): even = 0 odd = 0 for i in lst: if i%2 ==0: even+=1 else: odd+=1 return even,odd print(even,odd) even,odd = count(lst) print("Even : () Odd : () :".format(even,odd)) (甚至在内部),都会创建一个新的局部变量$list_user='a,b,c'; mysqli_query($conn,"SELECT post_id FROM post WHERE user IN ($list_user) GROUP BY user ORDER BY post_id DESC"); ,如果不将其内容返回给调用函数,其内容将会丢失。

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