亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

當字典為空時循環不會退出

當字典為空時循環不會退出

飲歌長嘯 2021-06-14 16:04:20
使用 Python 3:def show_flashcard():        """ Show the user a random key and ask them        to define it. Show the definition        when the user presses return. it then asks if user        knew definition or not if they do delets the word and        then asks if they want to continue or quit.    """    random_key = choice(list(glossary))    print('Define: ', random_key)    input('Press return to see the definition')    print(glossary[random_key])    import time    time.sleep(1) # delay for 1 seconds    print('Did you know the answer')    user_input = input('y or n: ')    if user_input == 'n':        print( 'Do not give  up you can only learn by practice')        time.sleep(1) # delay for 1 seconds        user_input = input('Enter s to show a flashcard and q to quit: ')    if user_input == 'y':        print( 'Congratulations , the word wil now be removed from the dictionary')    del (glossary[random_key])# Set up the glossaryglossary = {'1: word1':'definition1',            '2: word2':'definition2',            '3: word3':'definition3'}# The interactive loopexit = Falsewhile not exit:    if glossary == {''}:        exit = True       user_input = input('Enter s to show a flashcard and q to quit: ')    if user_input == 'q':        exit = True    elif user_input == 's':        show_flashcard()    else:        print('You need to enter either q or s.')當詞匯表為空時,我似乎無法讓這個循環自動退出。我已經嘗試了很多東西,從if glossary = 0 then exit is true,但我似乎無法到達任何地方。它讓我發瘋。
查看完整描述

2 回答

?
小唯快跑啊

TA貢獻1863條經驗 獲得超2個贊

您的退出條件 ,if glossary == {''}:永遠不會為真,因為您將詞匯表dictaset與包含單個空字符串元素的 a進行比較。


您可以dict直接在條件中使用一個對象,它會評估False它是否為空。您還可以使用break以立即退出循環:


while True:

    if not glossary:

        break

    user_input = input('Enter s to show a flashcard and q to quit: ')

    if user_input == 'q':

        break

    elif user_input == 's':

        show_flashcard()

    else:

        print('You need to enter either q or s.')


查看完整回答
反對 回復 2021-06-16
?
拉莫斯之舞

TA貢獻1820條經驗 獲得超10個贊

它可以更精簡:


while glossary:

    user_input = ...


查看完整回答
反對 回復 2021-06-16
  • 2 回答
  • 0 關注
  • 381 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號