Define ask_question
Exit

Define ask_question

Extract the question display, input, and feedback into a function

💻

Writing code and entering commands is only available on desktop. Open this page on a larger screen to complete this chapter.

The for loop body handles everything: it displays the question, waits for input, checks the answer, and prints feedback. That is four separate jobs packed into one block. Extracting them into a function makes the loop body shorter and the function independently testable.

Defining ask_question

The function needs all the question data as parameters: the question text, the four options, and the correct answer. The body does exactly what the loop body does now — display, get input, check, print feedback:

def ask_question(text, o1, o2, o3, o4, correct):
    print(text)
    print()
    print(f"  1) {o1}")
    # ... options 2, 3, 4 ...
    answer_text = input("Your answer (1-4): ")
    answer = int(answer_text)
    is_correct = answer == correct
    print()
    print(f"You answered: {answer}")
    if is_correct:
        print("Correct!")
    else:
        print(f"Wrong! The correct answer was option {correct}.")

Where to define it

Functions must be defined before they are called. Define ask_question after QUESTIONS and before the while loop.

The while loop stays unchanged

You are not calling the function yet — that comes in the next chapter. For now, define the function and leave the while loop exactly as it is.

Instructions

You are moving the question logic out of the loop and into a dedicated function. The function needs all six pieces of question data as parameters — the same values the loop currently unpacks from each tuple.

  1. After the QUESTIONS list and total = 3, define a function named ask_question with parameters text, o1, o2, o3, o4, and correct. Defining it here ensures it exists before the while loop calls it.
  2. Inside the function, call print(text), then print() — this displays the question followed by a blank line for readability.
  3. Call print(f" 1) {o1}"), print(f" 2) {o2}"), print(f" 3) {o3}"), and print(f" 4) {o4}"), each on its own line — this displays the four answer options.
  4. Call print(), then assign input("Your answer (1-4): ") to answer_text — the blank line separates the options from the prompt visually.
  5. Assign int(answer_text) to answer — this converts the player's text input into a number so it can be compared to correct.
  6. Assign answer == correct to is_correct — this evaluates the comparison and stores the result so you can branch on it.
  7. Call print(), then print(f"You answered: {answer}") — the blank line separates the prompt from the feedback.
  8. Write if is_correct: and call print("Correct!") inside it. Add an else clause that calls print(f"Wrong! The correct answer was option {correct}.") — this gives the player immediate feedback on their answer.