Python Forum
Noob here. Random quiz program. Using a while loop function and alot of conditionals.
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Noob here. Random quiz program. Using a while loop function and alot of conditionals.
#1
I just started learning how to code last week and tried making a random quiz program for one of my first projects and it's not working as intended. I assume the answer is simple, since I'm new and probably missing something super obvious.

A little embarrassing, but I've been trying to figure this out for 3 days! haha
The code at the moment isn't adding the score, nor is it giving the user the correct answer if answered wrong. Please help.


import random

def proper_answer():
    while True:
        answer = int(input("> "))
        if answer == 1 or answer == 2 or answer == 3:
            break
        else:
            print("Please enter a number from the answers available")


print("Welcome to the Great Quiz Show Extravaganza!")
print("You will be given 5 random questions to answer. Are you ready?")

question_list = range(11)
question_batch = random.sample(question_list, k=5)
score = 0
answer = 0

for question in question_batch:
    if question == 1:
        print("In what year was the first-ever Wimbledon Championship held?\n1. 1877 \n2. 1888 \n3. 1890")  # answer 1
        proper_answer()
        if answer == 2 or answer == 3:
            print("I'm sorry, that's incorrect. The answer was 1877.")
        elif answer == 1:
            print("Good job. That's correct.")
            score += 1
        answer = 0
    if question == 2:
        print("Hg is the chemical symbol of which element?\n1. Cobalt \n2. Mercury \n3. Lithium")  # answer 2
        proper_answer()
        if answer == 1 or answer == 3:
            print("I'm sorry, that's incorrect. The answer was mercury.")
        elif answer == 2:
            print("Good job. That's correct.")
            score += 1
        answer = 0
    if question == 3:
        print("What is the capital city of Spain?\n1. Madrid \n2. Zaragoza \n3. Barcelona")  # answer 1
        proper_answer()
        if answer == 2 or answer == 3:
            print("I'm sorry, that's incorrect. The answer was Madrid.")
        elif answer == 1:
            print("Good job. That's correct.")
            score += 1
        answer = 0
    if question == 4:
        print("Which is the highest waterfall in the world?\n1. Yosemite Falls \n2. Iguazu Falls \n3. Angel Falls")  # answer 3
        proper_answer()
        if answer == 1 or answer == 2:
            print("I'm sorry, that's incorrect. The answer was Angel Falls.")
        elif answer == 3:
            print("Good job. That's correct.")
            score += 1
        answer = 0
    if question == 5:
        print("Which country invented tea?\n1. India \n2. China \n3. England")  # answer 2
        proper_answer()
        if answer == 1 or answer == 3:
            print("I'm sorry, that's incorrect. The answer was China.")
        elif answer == 2:
            print("Good job. That's correct.")
            score += 1
        answer = 0
    if question == 6:
        print("How long does it take to hard boil an egg?\n1. Six minutes \n2. Seven minutes \n3. Eight minutes")  # answer 2
        proper_answer()
        if answer == 1 or answer == 3:
            print("I'm sorry, that's incorrect. The answer was seven minutes.")
        elif answer == 2:
            print("Good job. That's correct.")
            score += 1
        answer = 0
    if question == 7:
        print("Name the world’s largest ocean.\n1. Pacific \n2. Atlantic \n3. Indian")  # answer 1
        proper_answer()
        if answer == 1 or answer == 2:
            print("I'm sorry, that's incorrect. The answer was Pacific.")
        elif answer == 1:
            print("Good job. That's correct.")
            score += 1
        answer = 0
    if question == 8:
        print("What color is a Himalayan poppy flower?\n1. Yellow \n2. Red \n3. Blue")  # answer 3
        proper_answer()
        if answer == 1 or answer == 2:
            print("I'm sorry, that's incorrect. The answer was blue.")
        elif answer == 3:
            print("Good job. That's correct.")
            score += 1
        answer = 0
    if question == 9:
        print("Which country did the band AC/DC originate in?\n1. America \n2. New Zealand \n3. Australia")  # answer 3
        proper_answer()
        if answer == 1 or answer == 2:
            print("I'm sorry, that's incorrect. The answer was Australia.")
        elif answer == 3:
            print("Good job. That's correct.")
            score += 1
        answer = 0
    if question == 10:
        print("When did the Cold War end?\n1. 1989 \n2. 1990 \n3. 1991")  # answer 1
        proper_answer()
        if answer == 2 or answer == 3:
            print("I'm sorry, that's incorrect. The answer was 1989.")
        elif answer == 1:
            print("Good job. That's correct.")
            score += 1
        answer = 0

print(f"Your score is {score} out of 5!")
if score == 5:
    print("Great job! You got the perfect score!")
elif score == 0:
    print("You've got a lot of learning to do.")
else:
    print("Good job! Though you've got some studying to do.")
Reply
#2
Hello.
Pretty easy one here. But don't worry, you'll learn these little things :-)

It has to do with your 'answer' variable. Have you learned about the scope of a variable yet? Essentially variables declared in the main part of your program do not carry to functions or classes. You have to pass the variable along and return it from inside the function. In your case since you're taking input from inside the function you can skip passing the variable.

def proper_answer():
    while True:
        answer = int(input("> "))
        if answer == 1 or answer == 2 or answer == 3:
            return answer     #Changed from break to return answer
        else:
            print("Please enter a number from the answers available")
Then in each of the questions you can do this

if question == 1:
        print("In what year was the first-ever Wimbledon Championship held?\n1. 1877 \n2. 1888 \n3. 1890")  # answer 1
        answer = proper_answer()     #Here we assign the returned value from proper_answer to answer
        if answer == 2 or answer == 3:
            print("I'm sorry, that's incorrect. The answer was 1877.")
        elif answer == 1:
            print("Good job. That's correct.")
            score += 1
        answer = 0
At least that's one way to do it.
monkeydesu likes this post
Reply
#3
You should have a "questions_list". Writing your questions as code is very limiting. Your program can only do one quiz, the quiz coded into the program. If the questions were data, they could be saved in files and read by your quiz program. One quiz program could do an unlimited number of quizzes.

This program uses a tuple to represent a question. Each question has a question, answer, multiple choices, and a bit of interesting trivia. A quiz consists of a list of questions. In this example the quiz list is in the program, but it could easily be read from a file.
quiz = [
    (
        "In what year was the first-ever Wimbledon Championship held?",
        "1877",
        ("1877", "1888", "1890"),
        "Spencer Gore became the first Wimbledon champion by defeating William Marshall in 1877.",
    ),
    (
        "Hg is the chemical symbol of which element?",
        "Mercury",
        ("Cobalt", "Mercury", "Lithium"),
        "The symbol Hg comes from mercury's Greek name, hydrargyrum, which means liquid silver.",
    ),
]


def ask_question(question, choices):
    """Print the question and return the user selection"""
    print(question)
    choices = dict(zip("ABCD", choices))
    for key, value in choices.items():
        print(f"{key}. {value}")
    while True:
        if (answer := input("> ").upper()) in choices:
            break
        print(f"Answer question using {', '.join(choices.keys())}")
    return choices[answer]


score = 0
for question, answer, choices, trivia in quiz:
    if ask_question(question, choices) == answer:
        score += 1
    print(trivia, "\n")
print(f"Your score is {score}")
Output:
In what year was the first-ever Wimbledon Championship held? A. 1877 B. 1888 C. 1890 > a Spencer Gore became the first Wimbledon champion by defeating William Marshall in 1877. Hg is the chemical symbol of which element? A. Cobalt B. Mercury C. Lithium > b The symbol Hg comes from mercury's Greek name, hydrargyrum, which means liquid silver. Your score is 2
Instead of printing "Correct" or "Incorrect" I insert that information in the trivia printed about each question.

To convert this to a "random quiz" it obviously needs more questions, and the questions asked could be randomly selected using the random library.
score = 0
for question, answer, choices, trivia in random.choices(quiz, k=10):
    if ask_question(question, choices) == answer:
        score += 1
    print(trivia, "\n")
print(f"Your score is {score}")
monkeydesu likes this post
Reply
#4
Thank you so much!!!!! Yeah, I know I've got a lot to learn and this code isn't written well. I plan to rewrite it in a few months as a gauge to how much I've learnt. And again thank you!
Reply
#5
(Sep-06-2022, 06:43 AM)monkeydesu Wrote: Yeah, I know I've got a lot to learn and this code isn't written well.

Just ignore people telling you how to make your program better for now. They mean well and are only trying to help but I would advise to just keep doing what you're doing and don't worry if the code is "good".

Just write the code how it first comes to mind, make it work, and you can optimize and make it better later on.
Reply
#6
I don't agree with this approach.
just write the code how it first comes to mind, make it work, and you can optimize and make it better later on.
Programming is mostly problem solving. The actual coding is a minor part. You should plan out how you want to solve the problem, then try to implement the solution in code. I strongly suggest writing down the design before you go anywhere near a computer. By doing design first, you split the programming task in half. When working on your design you can focus on the logic of your solution. You can even apply your solution, the algorithm, to to "test cases" to see if it works. All without writing a single line of code. Once the algorithm is solid, translate it into Python code. While coding you can focus on finding the right Python functions and language constructs (loops, functions, datatypes) to implement your algorithm.

If you just start typing code, hoping to come up with something that works, you end up doing design and implementation simultaneously. Both the design and the coding suffer because you never focus your attention on either. Design suffers because the design process is constantly interrupted by trying to remember commands, or reading documentation about a package you are using, or tracking down syntax errors. Coding suffers because you don't have an outline to direct your coding efforts. You are always coding to a moving target. Eventually you get the code to run(no more crashes), but it doesn't do what it is supposed to do. You often end up throwing away most of the code you wrote because it implements an algorithm that doesn't solve the problem.

If you had written down a design for your your quiz program it might have looked like this.
Quote:1 score = 0
2 start loop
3 print question
4 get input
5 validate input
6 if input is answer, add 1 to score
7 if input is not answer, print correct answer
8 end loop when there are no more questions
9 print final score
You might break out some of the steps to add detail or record unanswered questions.
print question details
Quote:print out question to look like this

What is blah blah blah?
1. choice 1
2. choice 2
3. choice 3
get input and validate details
Quote:start loop
get user input
loop until input is a number 1, 2 or 3.

What should I do if the input is not valid? Print a message? Should I print the question and choices again?
How do I make sure the input is a number?
Checking if answer is correct and update score
Quote:If user input = answer
print congratulations
add 1 to score
otherwise
print Sorry, the correct answer is correct answer

How do I get the answer back from the user input validation? Do I use a variable, or should I return it from the function?
How do I determine if the user selected the right answer? What should input validation return? A number (1, 2, 3)? Should the
correct answer also be a number? Or do I want the input validation to return the answer as text, like "Mercury", and the correct answer would also be text. That would make it easier to print out the sorry message.
After you got your program running you would run some tests, maybe with just 1 question. After all, why write code for a dozen questions until you know things work with 1.
answer = 0
print("What is your favorite color?\n1. Red\n2. Green\n3. Blue")
proper_answer()
if answer != 2:
    print("The correct answer is Green")
When you ran the test program you'd notice the no matter what you type for the answer it is always wrong. You would go back to your design and notice your had written yourself a note:
Quote:How do I get the answer back from the user input validation? Do I use a variable, or should I return it from the function?
You might step through the program with the debugger, or add some print statements and notice that even though "answer" changes inside proper_answer(), that answer is always zero outside the function. You would investigate why that is happening and learn about variable scope, that variables assigned inside a function only exist inside the function, even if they have the same name as a variable assigned outside the function. You might learn about the "global" scope specifier that allows assigning global variables from inside a function. You would read that global variables should be uses sparingly because as programs grow in size it becomes increasingly difficult to keep track of all the places where a global variable is modified. So you would modify your proper_answer() function to return the user input as @kaega2 recommends.

Whew! Got that working. Now where was I? Looking back at your written design document you notice you forgot to increment the score when the answer is correct.
Reply
#7
Sigh

This is great advice when you're putting together a whole project with multiple files after you've got some of the fine details of coding down. But I believe how you put it was...
Quote:I just started learning how to code last week[...]

There is no point planning your code out ahead of time when you just started learning the very keywords that are the backbone to every program you'll ever make and things like the scope of a variable. It's true that coding is a minor part of programming, but it is a critical one. That's why I said "Just ignore people telling you how to make your program better for now". Just emphasizing that for @deanhystad

Make programs that help you understand the code you're learning. Seeing results on screen will keep you engaged and less likely to quit. Make LOTS of mistakes, keep asking questions, they are the best way to learn

I just had to say that
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  QUIZ GUI Form_When admin panel is open, main quiz form is getting freeze Uday 4 786 Aug-25-2023, 08:24 PM
Last Post: deanhystad
Question Doubt about conditionals in Python. Carmazum 6 1,616 Apr-01-2023, 12:01 AM
Last Post: Carmazum
  [ESP32 Micropython]Total noob here, I don't understand why this while loop won't run. wh33t 9 1,754 Feb-28-2023, 07:00 PM
Last Post: buran
  Function not scriptable: Noob question kaega2 3 1,194 Aug-21-2022, 04:37 PM
Last Post: kaega2
  conditionals based on data frame mbrown009 1 905 Aug-12-2022, 08:18 AM
Last Post: Larz60+
  Efficiency with regard to nested conditionals or and statements Mark17 13 3,181 May-06-2022, 05:16 PM
Last Post: Mark17
  Nested conditionals vs conditionals connected by operators dboxall123 8 3,076 Feb-18-2022, 09:34 PM
Last Post: dboxall123
  Program for random sum Cristopher 7 1,663 Jan-15-2022, 07:38 PM
Last Post: Cristopher
  I am writing a car rental program on python. In this function I am trying to modify aboo 2 2,754 Aug-05-2021, 06:00 PM
Last Post: deanhystad
  Nested Conditionals shen123 3 2,644 Jul-28-2021, 08:24 AM
Last Post: Yoriz

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020