Home > OS >  Flashcard toss a coin dictionary
Flashcard toss a coin dictionary

Time:08-09

kind of stuck with this code. I'm trying to print keys or values in random order from the dictionary. (Randomly whether to show the entry first or the corresponding definition) But I'm getting only a key first followed by a value. What I'm missing for the code to work? Any help will be amazing. Thank You Example:

  • Test-1 (Pressing Return Key) Definition-1
  • Definition-4 (Pressing Return Key) Test-4
  • Definition-2 (Pressing Return Key) Test-2
  • Test-3(Pressing Return Key) Definition-3 ...

from random import *

def flashcard():
    random_key = choice(list(dictionary))
    print('Define: ', random_key)
    input('Press return to see the definition')
    print(dictionary[random_key])

dictionary = {'Test-1':'Definition-1',
            'Test-2':'Definition-2',
            'Test-3':'Definition-3',
            'Test-4':'Definition-4'}

exit = False while not exit:
    user_input = input('Enter s to show a flashcard and q to quit: ')
    if user_input == 'q':
        exit = True
    elif user_input == 's':
        flashcard()
    else:
        print('You need to enter either q or s.')

CodePudding user response:

Either you can choose a random int between 0 and 1 or you can choose between 0 and 1.

def flashcard():
    k, v = choice(list(dictionary.items()))
    # toss a coin to decide whether to show the key or the value
    # alternative is randint(0, 1)
    if choice((True, False)):
        print('Define: ', k)
        input('Press return to see the definition')
        print(v)
    else:
        print('What is: ', v)
        input('Press return to see the key')
        print(k)

CodePudding user response:

Use random.random to determine whether random_key or definition should be shown first

from random import *


def flashcard():
    random_key = choice(list(dictionary))
    if random() > 0.5:
        print("Define: ", random_key)
        input("Press return to see the definition")
        print(dictionary[random_key])
    else:
        print("Define: ", dictionary[random_key])
        input("Press return to see the key")
        print(random_key)


dictionary = {
    "Test-1": "Definition-1",
    "Test-2": "Definition-2",
    "Test-3": "Definition-3",
    "Test-4": "Definition-4",
}

exit = False
while not exit:
    user_input = input("Enter s to show a flashcard and q to quit: ")
    if user_input == "q":
        exit = True
    elif user_input == "s":
        flashcard()
    else:
        print("You need to enter either q or s.")

  • Related