簡體   English   中英

用戶輸入的Python控制流

[英]Python control flow with user input

我正在嘗試編寫一個詞典應用,使用用戶輸入的單詞返回定義。 同樣,如果輸入錯誤,程序會循環搜索鍵入的3個最接近的匹配項,並詢問用戶這是什么意思。 我的控制流程未正確運行,因為'y'不會脫離循環或返回定義。 我沒有收到任何錯誤消息。 有人可以告訴我如何解決嗎? 如果3個建議中的任何一個都不是用戶的意思,我也將能夠返回“沒有緊密匹配”。

因此,函數中有3種情況:單詞,具有緊密匹配項的非單詞(可能是一個錯字),沒有緊密匹配項的非單詞(可能是隨機輸入)。這是我遇到的第二種情況。

    key=input('Enter the word: ')
    key=key.lower()
    dym=get_close_matches(key,data.keys())

    def find_meaning():
        if key in data:
            return data[key]
        elif len(dym)>0:
            for i in dym:
                choice=input('Did you mean '+i + ' Y/N ')
                if choice=='Y' or 'y':
                    break
                    return data[i]
                elif choice=='N' or 'n':
                    continue

        else:
            return 'Word does not exist!'

    print(find_meaning())

從上面的腳本中刪除“ break”后,我在運行時得到以下輸出:

Tokas-MBP:Python_Mega_Course tzhu9$ python3 dictionary.py
Enter the word: rainn
Did you mean rain Y/N n
['Precipitation in the form of liquid water drops with diameters greater than 0.5 millimetre
s.', 'To fall from the clouds in drops of water.']

我打算看到的結果是程序將以第二個最接近的匹配問我“您是不是要說”,而不輸出我不是要問的單詞的定義。

嘗試這個 :

if choice=='Y' or choice=='y':
        break
        return data[i]
elif choice=='N' or choice=='n':
        continue

而且我不明白如果您要退貨,為什么會有這樣的休息。

暫無
暫無

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

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