Python quiz issue - python

So, I have to design a basic quiz and it's fairly simple at the moment.
Essentially, I have 10 questions and I have incorporated a scoring system and I have managed to create a percentage system.
Here is my code:
# Quiz Game
import random
import sys
score = 0 # -> initial score
print("Your score is currently " + str(score))
qa = [('In which Australian state was the highest temperature of 53 deg C recorded? ', 'Queensland'),
('What animal is featured on the 2c coin? ', 'Frilled neck lizard'),
('What Australian company is the largest surfwear manufacturer? ' , 'Quicksilver'),
('How many ships were in the First Fleet? ', '11'),
('In what year was decimal currency introduced in Australia? ', '1966'),
('What was Sir Donald Bradman’s batting average? ', '99.94'),
('How much of Australia is classified as desert A) 8% B) 16% C) 25% D) 35% ', 'D'),
('On which Australian decimal banknote did a portrait of Henry Lawson appear? A) $5 B) $10 C) $20 D) $50 E) $100 ','B'),
('True or False, Bathurst is held at Mt. Panome? ', 'False'),
("Who was Australia's former F1 driver to Daniel Ricciardo? ", 'Mark Webber')]
random.shuffle(qa)
for q,a in qa:
user_answer = input(q)
if user_answer.lower() == a.lower():
# -> determining if the answer is correct or not
print("Correct!")
score = score+1
print('Your score is currently ' + str(score)) # -> scoring system
print ("Your Percentage is: ")
print((score/10)*100) # -> this is the percentage calculation
if score==2:
print('Congratualtions, you have beaten the quiz')
else:
print("Incorrect!")
print("The answer is " + a)
My current issue is I am unsure as to how I can do the following:
1) If the user gets 7 correct answers, quit early and display a winner message.
2) If the user gets 3 incorrect answers, quit early and display a loser message.
How can I do this? I am fairly new to python and haven't used it in a while so I'm a little rusty. I need to keep this platform but any additions you guys think of would be greatly appreciated.
Thank you in advanced.

Here's some pseudo code to get you started. You basically have the right idea.
score = 0
incorrect = 0
for q,a in qa:
user_answer = input(q)
if user_answer.lower() == a.lower():
score += 1
else:
incorrect += 1
if score == 7:
print('some message')
break
if incorrect == 3:
print('some message')
break

You need to have a while loop, which checks for either of your conditions:
import random
import sys
# qa = [...]
random.shuffle(qa)
correct = 0
incorrect = 0
while correct != 3 or incorrect != 7:
for q,a in qa:
print('Your current score is: {}'.format(correct))
print('Your percentage is: {}'.format((correct/10)*100))
user_answer = input(q)
if user_answer.lower() == a.lower():
correct +=1
print('Correct!')
else:
incorrect += 1
print('Incorrect! The correct answer is {}'.format(a))
if correct == 3:
print('You won!')
if incorrect == 7:
print('You lose!')
# End of code

Related

can we create a quiz in python using only functions and also keep track of scores

I wanted to create a function which can keep track of the scores from each of the questions and then use it in another function which returns the final result to the user. I have no idea of how to do so.
# Function for question 1
def ask_question_one(difficulty):
score = 0
print("What is the capital city of Canada?")
answer = input()
if difficulty <= 3:
if answer == "Ottawa" or answer == "ottawa":
score = score + 10
print("Your score is:", score)
else:
print(score)
elif difficulty > 3 and difficulty <= 7:
if answer == "Ottawa" or answer == "ottawa":
score = score + 30
print ("your score is:", score)
else:
print("You have given an incorrect answer. You lose 5 points.")
score = score - 5
print("Your score is:", score)
else:
count = 1
while count < 3:
answer = input()
if answer != "Ottawa" or answer != "ottawa":
score = score - 5
print("Your score is:", score)
score = score + 50
print("Your score after two tries is:", score)
def display_result(difficulty, score):
if difficulty <= 3 and score > 30:
print("Your difficulty level is", str(difficulty) + " and your score is", str(score))
# Top-level code.
set_difficulty = int(input("Please enter a difficuty level between 1 and 10: "))
if set_difficulty == "":
print("You did not enter a difficulty level. Try again! Exiting quiz.")
exit()
elif set_difficulty == 0:
print("0(zero) is not a valid difficulty. Exiting quiz.")
exit()
elif set_difficulty > 10:
print("Select a difficulty level less than 10.")
exit()
else:
print("....Let's begin the quiz....")
ask_question_one(set_difficulty)
here is what i have done so far
Please explain the comment correctly. Then maybe I can answer (I am putting this here because I don't have enough reputation for posting comments :'( ).

User will get different points depending on which try to get their question right

I am trying to create a score system for my game. For each of the three tries, the user will get different points for getting the question right. For example, if the user gets the question right on the first try, he or she will receive 3 points. If they get it right on the second try, they will receive two points (one point on the third try and zero points if they run out of the three tries). How would I be able to do this?
total_score = 0
correct_answer = 2004
print('What was the year when Arsenal last won the Premier League?')
try:
for x in range(1, 4):
user_guess = int(input(f'Attempt {x}. '))
if user_guess == correct_answer:
total_score += 1
print(f'Good job! Your current score {total_score}')
break
else:
print(f'Incorrect! {total_score}')
except(ValueError):
print('Enter a numerical value for year.')
Like this
total_score = 0
correct_answer = 2004
MAX_POINTS = 4
print('What was the year when Arsenal last won the Premier League?')
try:
for x in range(1, MAX_POINTS):
user_guess = int(input(f'Attempt {x}. '))
if user_guess == correct_answer:
total_score += MAX_POINTS - x
print(f'Good job! Your current score {total_score}')
break
else:
print(f'Incorrect! {total_score}')
except(ValueError):
print('Enter a numerical value for year.')
MUST READ THE COMMENTS TO UNDERSTAND HOW IT WORKS..
total_score = 0
correct_answer = 2004
user_guess = '' # A blank string for user response. Strings can be reassigned later.
print('What was the year when Arsenal last won the the Premier League?')
for x in range(1, 4):
try: # This is the actual place to use exception handling
user_guess = int(input('Attempt ' + str(x) + ': '))
except ValueError:
print('You did not enter a numerical value for year.')
break
if user_guess == correct_answer:
total_score += (4-x) # will add (4-1), (4-2), (4-3) in subsequent loop runs.
print('Good Job! Your Current score: ' + str(total_score))
break
else:
print('Uh oh! You didn\'t get that right. Current score: ' + str(total_score) + '. Try Again..')
if x == 3: # To check if the three attempts have been used or not.
print('Alas! You are out of attempts. Try back later')
break
else:
continue

Python quiz code improvement, maybe with a popup? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I'm a newbie here so sorry if I accidentally break any rules. Basically I'm a beginner to Python and have made a piece of code for a quiz on TV Show Trivia. I wanted to ask the community here if there are any ways to tidy it up, such as unnecessary repetition etc. Also, I wanted to know if there is a way to make it so that the quiz appears in a pop up window, with a space to type in the answer. Here is the code I have so far:
print("Shall we start?")
input("Press Enter to continue...")
score = 0
Que_1 = input("Who's missing - Rachel, Ross, Chandler, Pheobe?: ")
if Que_1 == "Monica" or "monica":
print("That's right, well done!!")
score = score + 1
else:
print("I'm sorry, that's the wrong answer :( ")
score = score - 1
Que_2 = input("What is the first name of the women Leonard from The Big Bang
Theory ended up marrying?: ")
if Que_2 == "Penny" or "penny":
print("Congratulations, that was correct!!")
score = score + 1
else:
print("Incorrect")
score = score - 1
Que_3 = input("What is the full name of the actor who plays the 10th
Doctor?: ")
if Que_3 == "David Tennant" or "david tennant":
print("Oui")
score = score + 1
else:
("Non")
score = score - 1
Que_4 = input("Which sister died in Charmed?: ")
if Que_4 == "Prue" or "prue":
print("You know it")
score = score + 1
else:
print("You don't know it")
score = score - 1
Que_5 = input("Who is the main character of 13 reasons why(Full Name)?: ")
if Que_5 == "Hannah Baker" or "hannah baker":
print("Correctumondo")
score = score + 1
else:
print("Failumundo")
score = score - 1
Que_6 = input("Complete the name 'Tracy ______': ")
if Que_6 == "Beaker" or "beaker":
print("Perfect")
score = score + 1
else:
print("Not perfect")
score = score - 1
Que_7 = input("Lily, Jas and ______ : ")
if Que_7 == "Martha" or "martha":
print("On the button")
score = score + 1
else:
print("Sucks to be you")
score = score - 1
Que_8 = input("Is Missy from Ackley Bridge straight, lesbian or bisexual?:")
if Que_8 == "Straight" or "straight":
print("Right on")
score = score + 1
else:
print("Way off")
score = score - 1
Que_9 = input("From the 4 o' Clock Club, who is Josh's brother?: ")
if Que_9 == "Nathan" or "nathan":
print("Unmistaken")
score = score + 1
else:
print("Mistaken")
score = score - 1
Que_10 = input("What does Sophie from My Parents Are Aliens have to eat in
order to shapeshift? : ")
if Que_10 == "Ice cream" or "Ice Cream" or "ice cream":
print("Amen to that")
score = score + 1
else:
print("Ughhhh just no")
score = score - 1
if score == 10:
print("10 out of 10. Your a boss at this")
elif 5 <= score < 10:
print("Your score is", score, "pretty good, try to get 10 next time")
elif 1 <= score < 10:
print("Your score is", score, "Better luck next time")
Try this code (I did not include all the questions):
questions = [
"Who's missing - Rachel, Ross, Chandler, Pheobe?: ",
"What is the first name of the women Leonard from The Big Bang Theory ended up marrying?: ",
"What is the full name of the actor who plays the 10th Doctor?: ",
"Which sister died in Charmed?: "
]
answers = [
"monica",
"penny",
"david tennant",
"prue"
]
yes_nos = [
["That's right, well done!!", "I'm sorry, that's the wrong answer :( "],
["Congratulations, that was correct!!", "Incorrect"],
["Oui", "Non"],
["You know it", "You don't know it"]
]
if __name__ == '__main__':
print("Shall we start?")
input("Press Enter to continue...")
score = 0
for i, q in enumerate(questions):
ans = input(q + '\n').lower()
if ans == answers[i]:
print(yes_nos[i][0])
score += 1
else:
print(yes_nos[i][1])
print()
if score == 10:
print("10 out of 10. Your a boss at this")
elif 5 <= score < 10:
print("Your score is", score, "\nPretty good, try to get 10 next time")
elif 1 <= score < 10:
print("Your score is", score, "\nBetter luck next time")
Easygui is great for small dialog boxes:
response = easygui.enterbox("What is your favorite ice cream flavor?")
Which will pop up a window like this.
Hope this helps!
In term of optimization, you can use the method lower()
if Que_1.lower() == "monica":
That will remove the first letter as an upper case
You can also use += 1
print("That's right, well done!!")
score += 1
You will not need to do score = score + 1
And on the first Que_1, you need to set after the else with the score that equals to 0 as it is your first if.
You may need to check dictionaries and if it can help you.
And last, you can use this question to give you some insight about what you can do.

I'm having problems whilst creating a quiz using python loops

The start of my code works fine but,the bottom part consisting on the score and answer doesn't. I'm doing a school project on this and need a solution quick. But I have to be using loops! The part where i'm trying to tell the user that the answer is correct isn't working. The part where i'm revealing the right answer isn't working as well. The score isn't working as well.
print ('WELCOME TO THE MULTIPLE CHOICE TEST\n')
name = input('WHAT IS YOUR NAME? ')
print ('\nHI THERE ' + name + '! LET''S PLAY A GAME!\n')
print ('I will ask you 10 questions and give you three choices for each question.\n\nYou select which choice is the correct answer. Eg. A, B,C or D\n')
score = 0
score = int(score)
qn1 = ["What's color of sky?", "a)Red", "b)Blue", "c)White", "d)Black"]
def print_question(qn_num):
print(qn_num[0])
print(qn_num[1])
print(qn_num[2])
print(qn_num[3])
print(qn_num[4])
print_question(qn1)
answer = input ()
answer =int(answer)
if answer == 2:
print ("good work")
score = score + 1
else:
print ("better luck next time")
score = score - 1
You can ask the answer in an infinite loop, and also show the score
print ('WELCOME TO THE MULTIPLE CHOICE TEST\n')
name = input('WHAT IS YOUR NAME? ')
print ('\nHI THERE ' + name + '! LET''S PLAY A GAME!\n')
print ('I will ask you 10 questions and give you three choices for each question.\n\nYou select which choice is the correct answer. Eg. A, B,C or D\n')
score = 0
score = int(score)
qn1 = ["What's color of sky?", "a)Red", "b)Blue", "c)White", "d)Black"]
def print_question(qn_num):
for st in qn_num:
print(st)
print_question(qn1)
allowed_answers = ["a", "b", "c", "d"]
wrong_answer = True
while(wrong_answer):
answer = input ("select answer: ")
if answer == 'b':
print ("good work")
score = score + 1
wrong_answer = False
elif answer not in allowed_answers:
print ("Bad input, you have to chose between " + ",".join(allowed_answers) )
else:
print ("better luck next time")
score = score - 1
print("Your score is: " + str(score))

Need quiz scoring function

I have to create a basic 3 question quiz on farming. It needs to ask the 3 questions, output whether you got it correct or incorrect and if you got it incorrect you can try again. It also needs to have a score function. I have completed the questions and the incorrect/correct part of the specification but no matter what I try I cannot get the score function to work. I have tried:
score = 0
def counter(score)
score = score + 1
def counter(score)
score = 0
score = score + 1
def counter(score)
global score
score = 0
score = score + 1
and then following that once the answer was correct the line read :
counter(score)
I have also tried
score = 0
then
score = score + 1
but nothing is working and I cannot figure out what is going wrong. It also needs to print how many the user got right at the end.
CODE:
score = 0
def quiz():
print("Here is a quiz to test your knowledge of farming...")
print()
print()
print("Question 1")
print("What percentage of the land is used for farming?")
print()
print("a. 25%")
print("b. 50%")
print("c. 75%")
answer = input("Make your choice: ")
if answer == "c":
print("Correct!")
score = score + 1
else:
print("Incorrect.")
answer = input("Try again! ")
if answer == "c":
print("Correct")
score = score + 1
else:
print("Incorrect! Sorry the answer was C.")
print()
print()
print("Question 2")
print("Roughly how much did farming contribute to the UK economy in 2014.")
print()
print("a. £8 Billion.")
print("b. £10 Billion.")
print("c. £12 Billion.")
answer = input("Make your choice: ")
if answer == "b":
print("Correct!")
score = score + 1
else:
print("Incorrect.")
answer = input("Try again! ")
if answer == "b":
print("Ccrrect!")
score = score + 1
else:
print("Incorrect! Sorry the answer was B.")
print()
print()
print("Question 3.")
print("This device, which was invented in 1882 has revolutionised farming. What is it called?")
print()
print("a. Tractor")
print("b. Wagon.")
print("c. Combine.")
answer == input("Make your choice. ")
if answer == "a":
print("Correct!")
score = score + 1
else:
print("Incorrect.")
answer == input("Try again! ")
if answer == "a":
print("Correct!")
score = score + 1
else:
print("Incorrect! Sorry the answer was A.")
print("You got {0}/3 right!".format(score))
A n00b (and working) way would be to do something like
score = 0
def quiz():
global score
The global keyword makes use of the global variable (which you declared outside your function quiz). Since you've not indented your code properly it's unclear if you're printing the last statement inside or outside the quiz function, but that doesn't matter. If you place both score and printing inside the quiz function or both outside you'll be fine. Good luck with homework!
So python scope is defined by indents (as mentioned by the comment above). So any statement that creates a layer of scope is seperated by an indent. Examples include classes, functions, loops, and boolean statements. Here is an example of this.
Class A:
def __init__(self, msg):
self.message = msg
def print_msg(self): # prints your message
print self.message
def is_hi(self):
if self.message == "hi":
return true
else:
return false
This shows the different layers of scope that can exist.
Your code is not working right now because you are defining a function and then putting nothing in its scope. You would have to put anything within the scope of the function for that error to go away but that is probably not what you are looking for.
Operators in any programming language are your bread and butter for transforming data from one state to another or for comparing data. We have three types: Arithmetic operators, Relational operators and Logical operators. It is crucial you understand them well and I would advise you to visit https://www.geeksforgeeks.org/basic-operators-python/ for reference. I can see from your answer above that there is some confusion between the assignment operator and the comparison operator:
This is the comparison operator:
answer == input("Make your choice. ")
What you expect to happen is that an input is read from the keyboard and set into the answer variable, but what's actually happening is your testing for a conditional comparison, in this case between an empty variable (called answer) and a python built-in function. What will happen is python will silently return a boolean describing the outcome of the conditional statement but will never set your variable to the new value because you didn't use the assignment operator.
This is the assignment operator:
answer = input("Make your choice. ")
A single equal symbol can make a big difference!
Now your code will correctly set the value a user types from their keyboard into the answer variable thanks to the power of the assignment operator.
I've refactored your code below to demonstrate the difference between assignment and comparison operations. I've also demonstrated using the newline character (\n) to create spaces between your text blocks.
import sys
def quiz():
score = 0
print("Here is a quiz to test your knowledge of farming...\n\n")
print("Question 1")
print("What percentage of the land is used for farming?")
print("a. 25%")
print("b. 50%")
print("c. 75%")
answer = input("Make your choice: ")
if answer == "c":
print("Correct!\n\n")
score = score + 1
else:
print("Incorrect! Sorry the answer was C.\n\n")
print("Question 2")
print("Roughly how much did farming contribute to the UK economy in 2014.\n")
print("a. £8 Billion.")
print("b. £10 Billion.")
print("c. £12 Billion.")
answer = input("Make your choice: ")
if answer == "b":
print("Correct!\n\n")
score = score + 1
else:
print("Incorrect! Sorry the answer was B.\n\n")
print("Question 3.")
print("This device, which was invented in 1882 has revolutionised farming. What is it called?\n")
print("a. Tractor")
print("b. Wagon.")
print("c. Combine.")
answer = input("Make your choice: ")
if answer == "a":
print("Correct!")
score = score + 1
else:
print("Incorrect! Sorry the answer was A.")
print("You got {}/3 right!".format(score))
if __name__ == "__main__":
quiz()

Categories

Resources