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

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.

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 :'( ).

so i started programming 1 week ago and i am a bit confused about why my program is not subtracting 1 when answer to any question is incorrect

i cant get to subtract one from score in this python program. when i run the code it shows answer from 0 to 4 but not in negative i want the answer to be negative if too many answers are wrong. Here is the code:
***print("Hello and welcome to my quiz! ")
score = 0
# this the question i want it to add 1 if answer is correct and subtract 1 if answer is incorrect
print("question 1: what is my name? ")
ans1 = input()
if ans1 == 'mark':
print('correct')
score += 1
else:print('incorrect')
score -= 1
# second question
print("question 2: what is my age? ")
ans2 = input()
if ans2 == '19':
print('correct')
score += 1
else:print('incorrect')
score -= 1
print("question 3: what is my fathers name? ")
ans3 = input()
# third question
if ans3 == 'john':
print('correct')
score += 1
else:print('incorrect')
score -= 1
**# fourth question**
print("question 4: what is my mothers name? ")
ans4 = input()
if ans4 == 'Emily':
print('correct')
score += 1
else:print('incorrect')
score -= 1
print ('your score is', score )
# answer can be in negative***
This actually shouldn't even run.
else:print('incorrect')
score -= 1
You need to either have a one-line else statement or put all code for the else statement on the next line and properly indent it. Python is all about the whitespace.
The following should fix your issue.
else:
print('incorrect')
score -= 1
The increments are going to be invoked regardless of the answer. For example
# second question
print("question 2: what is my age? ")
ans2 = input()
if ans2 == '19':
print('correct')
score += 1
else:print('incorrect')
score -= 1
If the answer is correct, then the score will be incremented but then the score will also then be decremented, regardless. The score -=1 needs to be indented correctly, like this
# second question
print("question 2: what is my age? ")
ans2 = input()
if ans2 == '19':
print('correct')
score += 1
else:
print('incorrect')
score -= 1
If you try this across your script, the results may be more like you expect.
The program is almost fine. I am getting negative score if I answer everything uncorrectly. The last line is wrong, since you can't concatenate an integrer with a string. Also, you need to properly indent the content under the "else" statements. This would be the finished program:
print("Hello and welcome to my quiz! ")
score = 0
# this the question i want it to add 1 if answer is correct and subtract 1 if answer is incorrect
print("question 1: what is my name? ")
ans1 = input()
if ans1 == 'mark':
print('correct')
score += 1
else:
print('incorrect')
score -= 1
# second question
print("question 2: what is my age? ")
ans2 = input()
if ans2 == '19':
print('correct')
score += 1
else:
print('incorrect')
score -= 1
print("question 3: what is my fathers name? ")
ans3 = input()
# third question
if ans3 == 'john':
print('correct')
score += 1
else:
print('incorrect')
score -= 1
# fourth question**
print("question 4: what is my mothers name? ")
ans4 = input()
if ans4 == 'Emily':
print('correct')
print('your score is ' + str(score) )

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))

Loop in a loop python [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
is there a way to add a second loop to a code. So the question says to create a quiz which I've done however, for the last hour I've being trying to add a second loop so the quiz does it three times:
import random
score = 0
questions = 0
loop = 0
classnumber = ("1", "2", "3")
name = input("Enter Your Username: ")
print("Hello, " + name + ". Welcome to the Arithmetic Quiz")
classno = input("What class are you in?")
while classno not in classnumber:
print(
"Enter a valid class. The classes you could be in are 1, 2 or 3.")
classno = input("What class are you in?")
while questions < 10:
for i in range(10):
number1 = random.randint(1, 10)
number2 = random.randint(1, 10)
op = random.choice("*-+")
multiply = number1*number2
subtract = number1-number2
addition = number1+number2
if op == "-":
print("Please enter your answer.")
questions += 1
print(" Question", questions, "/10")
uinput = input(str(number1)+" - "+str(number2)+"=")
if uinput == str(subtract):
score += 1
print("Correct, your score is: ", score,)
else:
print("Incorrect, the answer is: " + str(subtract))
score += 0
if op == "+":
print("Please enter your answer.")
questions += 1
print(" Question", questions, "/10")
uinput = input(str(number1)+" + "+str(number2)+"=")
if uinput == str(addition):
score += 1
print(" Correct, your score is: ", score,)
else:
print(" Incorrect, the answer is: " + str(addition))
score += 0
if op == "*":
print("Please enter your answer.")
questions += 1
print(" Question", questions, "/10")
uinput = input(str(number1)+" * "+str(number2)+"=")
if uinput == str(multiply):
score += 1
print(" Correct, your score is: ", score,)
else:
print(" Incorrect, the answer is: " + str(multiply))
score += 0
First, please consider using functions in your code. Functions make everything neater and functions help make code reusable.
Second, there are a lot of areas where the code is superfluous. It is performing unnecessary checks in spots and several sections of the code could be rearranged to reduce the overall length and increase readability.
Nonetheless, here's a revised version of your code with some of those suggestions implemented:
import random
def RunQuiz():
name = input("Enter Your Username: ")
print("Hello, " + name + ". Welcome to the Arithmetic Quiz")
score = 0
questions = 0
loop = 0
classnumber = ("1", "2", "3")
classno = input("What class are you in?")
while classno not in classnumber:
print("Enter a valid class. The classes you could be in are 1, 2 or 3.")
classno = input("What class are you in?\n>>> ")
# End while input
# Run the 10 question quiz
for questions in range(1,11):
number1 = random.randint(1, 10)
number2 = random.randint(1, 10)
op = random.choice("*-+")
multiply = number1*number2
subtract = number1-number2
addition = number1+number2
print("Please enter your answer.")
print(" Question" + str(questions) "/10")
if( op == "-"):
# Subtraction
uinput = input(str(number1)+" - "+str(number2)+"=")
# Make it an int for proper comparison
uinput = int(uinput)
if uinput == subtract:
score += 1
print("Correct, your score is: %d" %(score,))
else:
print("Incorrect, the answer is: " + str(subtract))
score += 0
elif( op == "+"):
# Addition
uinput = input(str(number1)+" + "+str(number2)+"=")
uinput = int(uinput)
if uinput == addition:
score += 1
print(" Correct, your score is: %d" % (score,))
else:
print(" Incorrect, the answer is: " + str(addition))
score += 0
elif( op == "*" ):
# Multiplication
uinput = input(str(number1)+" * "+str(number2)+"=")
uinput = int(uinput)
if uinput == multiply:
score += 1
print(" Correct, your score is: %d" % (score,))
else:
print(" Incorrect, the answer is: " + str(multiply))
score += 0
# End if( op )
# End For 10 questions
print("\nFinal Score: %d/10" % (score,))
# End RunQuiz()
def main():
# Run the quiz 10 times
for RunCount in range(3):
print("Running quiz #%d\n" % (RunCount,))
RunQuiz()
# End For
# End main
# Call main on script execution
main()
Obviously you can rearrange the code to suit your needs. (For example, I did not know if you want the name & class number to be entered every time).
If you want the whole thing to run 3 times then put for i in xrange(3): above the first lines of the quiz then indent the rest of the code to the loop. If that is what you actually want. Good luck!

Python quiz issue

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

Categories

Resources