Home > front end >  Choosing random function from a list
Choosing random function from a list

Time:11-01

I've defined several variables with the questions, answers and category (Prize amount) for a "who wants to be a millionaire" kind of game. Then I have this function who runs based on those Questions, answers and whatnot. I've tried to use the random function of python through shuffle, choice, choices and haven't had success.

CodePudding user response:

What you're putting into the list isn't the function, it's the result of having already called the function -- the act of building the list itself calls questionnaire three times before you have a chance to pick an element out of it.

Putting each question into an object rather than having sets of unique named variables makes it easier to pick a random question as a unit. You could use a dict for this; I usually use NamedTuple.

from random import choice
from typing import List, NamedTuple, Tuple


class Question(NamedTuple):
    question: str
    answers: List[str]
    correct: str
    amount: int
    cat: int


questions = [
    Question(
        "QUESTION: What is the biggest currency in Europe?",
        ["A) Crown", "B) Peso", "C) Dolar", "D) Euro"],
        "D", 25, 1
    ),
    Question(
        "QUESTION: What is the biggest mountain in the world?",
        ["A) Everest", "B) Montblanc", "C) Popocatepepl", "D) K2"],
        "A", 25, 2
    ),
    Question(
        "QUESTION: What is the capital of Brasil?",
        ["A) Rio de Janeiro", "B) Brasilia", "C) Sao Paolo", "D) Recife"],
        "B", 25, 3
    ),
]


def questionnaire(q: Question) -> Tuple[int, bool]:
    """Presents the user with the given question.
    Returns winnings and whether to continue the game."""
    print(q.question)
    for answer in q.answers:
        print(answer)
    usr_input_answer = input(
        " What's your answer? "
        "Please select between A, B, C, D or R for Retirement. "
    ).upper()
    if usr_input_answer == q.correct:
        return q.amount, True
    elif usr_input_answer == "R":
        print("Congratulations on retirement!")
    else:
        print("Game over!")
    return 0, False


money = 0
keep_playing = True
while keep_playing:
    winnings, keep_playing = questionnaire(choice(questions))
    money  = winnings

CodePudding user response:

Firstly: I suggest you to create and keep all the questions within a dictionary.

Secondly: In rnd.choice = you try to overwrite the function by writing = which is used to give value to the thing that comes before the equation mark. Try looking up here.

Lastly: The function questionnaire() doesn't return a value, so you don't wanna use it like rnd.choice=([questionnaire(question1,answers1,correct1,amount1,cat1), ...

  • Related