簡體   English   中英

python中的函數未返回分配給變量的最新字符串值

[英]Latest String value assigned to a variable is not returned by the function in python

在下面的代碼中,我試圖獲取用戶輸入,直到它與“ 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 ,如果不將其內容返回給調用函數,其內容將會丟失。

調用getType()type的內容未修改。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM