Цикл не завершится, когда dict пуст - PullRequest
0 голосов
/ 12 сентября 2018

Использование 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 glossary
glossary = {'1: word1':'definition1',
            '2: word2':'definition2',
            '3: word3':'definition3'}

# The interactive loop
exit = False
while 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 ]

0 голосов
/ 13 сентября 2018

Может быть еще меньше:

while glossary:
    user_input = ...
0 голосов
/ 13 сентября 2018

Вы выходите из условия, if glossary == {''}:, никогда не будет истинным, потому что вы сравниваете глоссарий dict с set, который содержит один пустой строковый элемент.

Вы можете использовать объект 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.')
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...