Home > Mobile >  Can't check if key belongs to values
Can't check if key belongs to values

Time:03-05

The short() function below doesn't work. full() works completely fine. Is there a solution, or do I have to make another directory where key and value are swapped?

import random

elements = {"Sc":"Scandium",
           "Ti":"Titanium",
           "V":"Vanadium",
           "Cr":"Chromium",
           "Mn":"Manganum",
           "Fe":"Ferrum"}


def short():
    question = random.choice(list(elements.values()))
    print(question)
    answer = input("What is the short name of this element?: ")
    if answer == elements[question]:
        print("Right")


def full():
    question = random.choice(list(elements.keys()))
    print(question)
    answer = input("What is the full name of this element?: ")
    if answer == elements[question]:
        print("Right")


mode = input("Do you want to guess the short or full name? (sh/fu): ").lower()

if mode == "sh":
    short()

elif mode == "fu":
    full()

CodePudding user response:

I changed my mind. You don't need a reverse dict.

Just structure short() slightly differently:

import random

elements = {"Sc":"Scandium",
           "Ti":"Titanium",
           "V":"Vanadium",
           "Cr":"Chromium",
           "Mn":"Manganum",
           "Fe":"Ferrum"}

def short():
    question = random.choice(list(elements.keys()))
    print(elements[question])
    answer = input("What is the short name of this element?: ")
    if answer == question:
        print("Right")

def full():
    question = random.choice(list(elements.keys()))
    print(question)
    answer = input("What is the full name of this element?: ")
    if answer == elements[question]:
        print("Right")

mode = input("Do you want to guess the short or full name? (sh/fu): ").lower()

if mode == "sh":
    short()

elif mode == "fu":
    full()

short() now selects a key at random just like full(), but asks the question in terms of the long name which is easily accessible in the forwards direction.

  • Related