new to Python, my code is validating except for the last few lines. I need help with counting and calculating the answers to calculate a percentage and I'm getting errors. I haven't gotten to show the percentage because I can't get past the count function. Here is the code with errors. I also need to add a timer and a way to randomize the questions.
print ("|Total score: " + str(count) + "/10")
NameError: name 'count' is not defined
print("Here is a quiz to test your trivia knowledge...")
print()
print()
print("Question 1")
print("What month does the New Year begin? a=dec, b=Jan, c=Feb, d=Mar: ")
print()
answer = input("Make your choice >>>> ")
if answer == "a":
print("Correct!")
elif answer != "a":
print ("Wrong")
print()
print()
print("Question 2")
print("an antipyretic drug reduces what in humans? a=fever, b=weight, c=hair, d=acne: ")
print()
print()
answer = input("Make your choice >>>> ")
if answer == "a":
print("Correct!")
elif answer != "a":
print ("Wrong")
print()
print()
print("Question 3")
print("Which artist performed the 1992 hit song titled Save the best For Last? a=Prince, b=U2, c=Vanessa Williams, d=cher: ")
print()
answer = input("Make your choice >>>> ")
if answer == "c":
print("Correct!")
elif answer != "c":
print ("Wrong")
print()
print()
print("Question 4")
print("Columbus day in the US is celebrated during which month? a=dec, b=Jan, c=Oct, d=Jun: ")
print()
answer = input("Make your choice >>>> ")
if answer == "c":
print("Correct!")
elif answer != "c":
print ("Wrong")
print()
print()
print("Question 5")
print("What is the largest ocean in the world? a=Indian, b=atlantic, c=Pacific, d=baltic: ")
print()
answer = input("Make your choice >>>> ")
if answer == "c":
print("Correct!")
elif answer != "c":
print ("Wrong")
print()
print()
print("Question 6")
print("Which European city hosted the 2004 Summer Olympic Games? a=Rome, b=Paris, c=Vienna, d=athens: ")
print()
answer = input("Make your choice >>>> ")
if answer == "d":
print("Correct!")
elif answer != "d":
print ("Wrong")
print()
print()
print("Question 7")
print("Which NFL team has played in the most Superbowls? a=dallas, b=Pittsburgh,c=atlanta, d=chicago: ")
print()
answer = input("Make your choice >>>> ")
if answer == "a or b":
print("Correct!")
elif answer != "a or b":
print ("Wrong")
print()
print()
print("Question 8")
print("Which US president is on the $1 bill? a=Washington, b=Lincoln, c=Jefferson, d=Clinton: ")
print()
answer = input("Make your choice >>>> ")
if answer == "a":
print("Correct!")
elif answer != "a":
print ("Wrong")
print()
print()
print("Question 9")
print("What is the official language of Iran? a=English, b=German, c=Persian, d=Dutch: ")
print()
answer = input("Make your choice >>>> ")
if answer == "c":
print("Correct!")
elif answer != "c":
print ("Wrong")
print()
print()
print("Question 10")
print("Which flower, herb and perfume ingredient can be found in abundance in Provence, France? a=rose, b=tulip, c=lavender, d=rose: ")
print()
answer = input("Make your choice >>>> ")
if answer == "c":
print("Correct!")
elif answer != "c":
print ("Wrong")
print ("\n|Congratulations!")
print ("|Here's your result.")
print ("|Total score: " + str(count) + "/10")
division = float(count)/float(20)
multiply = float(division*100)
result = round(multiply)
print ("|Total percentage is", int(result), "%")
if result >= 95:
print ("|Grade: a+ \n|Well done!")
elif result >= 80:
print ("|Grade: b \n|Good job!")
elif result >= 65:
print ("|Grade: c \n|You did okay.")
elif result >=50:
print ("|Grade: d \n|Keep trying, that wasn't very good.")
elif result >= 0:
print ("|Grade: Fail\n|You need to study.")
NameError generally means that you are trying to access a variable that has not been defined. If you check your code, you'll see that count appears for the first time here
print ("|Total score: " + str(count) + "/10")
so there's actually nothing to convert to string yet. Maybe you wanted to have a counter for correct answers? You should do something like
count = 0
if answer == "c":
print("Correct!")
count += 1
else:
print("Wrong")
Related
print("Welcome to my quiz page!")
playing = input("Do you want to play? ")
if playing.lower() == "yes": #when people answer no here, the quiz should stop but it doesn't. why?
print("Let's play! ")
score = 0
answer = input("What is the capital of Japan? ")
if answer.lower() == "tokyo":
print("Correct!")
score += 1
else:
print("Incorrect!")
answer = input("What is a female Japansese dress called? ")
if answer.lower() == "kimono":
print("Correct!")
score += 1
else:
print("Incorrect!")
answer = input("What are Japanese gang members called? ")
if answer.lower() == "yakuza":
print("Correct!")
score += 1
else:
print("Incorrect!")
print("You've got " + str(score) + " questions correct!")
print("You've got " + str((score / 3) * 100) + "%,")
When I answer "no" it still let me carry on playing the quiz instead of quitting. How can I stop it running when people answer no instead of yes?
The quiz does not stop because you have not included any code to stop the quiz when the user enters "no". To fix this, you can add an else statement after the if statement that checks if the user wants to play. The else statement should contain a break statement to exit the loop.
Here How you can do so:
print("Welcome to my quiz page!")
while True:
playing = input("Do you want to play? ")
if playing.lower() == "yes" or playing.lower() == "y":
print("Let's play! ")
score = 0
answer = input("What is the capital of Japan? ")
if answer.lower() == "tokyo":
print("Correct!")
score += 1
else:
print("Incorrect!")
answer = input("What is a female Japansese dress called? ")
if answer.lower() == "kimono":
print("Correct!")
score += 1
else:
print("Incorrect!")
answer = input("What are Japanese gang members called? ")
if answer.lower() == "yakuza":
print("Correct!")
score += 1
else:
print("Incorrect!")
print("You've got " + str(score) + " questions correct!")
print("You've got " + str((score / 3) * 100) + "%,")
else:
break
You can make this more manageable by constructing a list of questions and answers rather than writing discrete blocks of code for each.
You need to be asking the user if they want to answer questions (or not).
So...
Q_and_A = [
('What is the capital of Japan', 'Tokyo'),
('What is a female Japansese dress called', 'kimono'),
('What are Japanese gang members called', 'yakuza')
]
score = 0
for q, a in Q_and_A:
if input('Would you like to try to answer a question? ').lower() in {'n', 'no'}:
break
if input(f'{q}? ').lower() == a.lower():
print('Correct')
score += 1
else:
print('Incorrect')
print(f'Your total score is {score} out of a possible {len(Q_and_A)}')
Thus if you want to add more questions and answers you just change the list of tuples. The rest of the code doesn't need to be changed
def ask_questions():
choice = (random.choice(question))
print(choice)
if choice == question[0]:
print options[0]
answer0 = raw_input(inputs)
if answer0 == answers[0]:
print("correct")
else:
print("incorrect")
elif choice == question[1]:
print choice
print options[1]
answer1 = raw_input(inputs)
if answer1 == answers[1]:
print("correct")
else:
print("incorrect")
elif choice == question[2]:
print choice
print options[2]
answer2 = raw_input(inputs)
if answer2 == answers[2]:
print("correct")
else:
print("incorrect")
elif choice == question[3]:
print choice
print options[3]
answer3 = raw_input(inputs)
if answer3 == answers[3]:
print("correct")
else:
print("incorrect")
elif choice == question[4]:
print choice
print options[4]
answer4 = raw_input(inputs)
if answer4 == answers[4]:
print("correct")
else:
print("incorrect")
elif choice == question[5]:
print choice
print options[5]
answer5 = raw_input(inputs)
if answer5 == answers[5]:
print("correct")
else:
print("incorrect")
This is my code, is there anyway that i make a loop that keep printing my random choice question (and removes from the list the called one) need it for a quiz, when it calls the question i print options and input than use if elif else statements. Thanks!
When I see the way you're doing this, I don't like how you have 3 separate data structures when a single dict could combine them into one simple structure. Here's an example of what I'd do instead:
import random
QUESTIONS_ANSWERS = {
"What is 21 + 21": ["42", "43", "13", "12"],
"Question 2: enter the correct answer...": ["correct answer", "another answer", "incorrect answer"],
}
def ask_questions():
all_questions = QUESTIONS_ANSWERS.keys()
random.shuffle(all_questions)
for question in all_questions:
options = QUESTIONS_ANSWERS[question]
correct_option = options[0]
random.shuffle(options)
print "Q:", question
print options
answer = raw_input(">>> ")
print "correct" if (answer == correct_option) else "incorrect"
ask_questions()
This way, all the questions and options are in the same dict. The correct answer is, in this case, always the first element of the dict's value (first element of the list). These can be shuffled after you store it in a temp variable for comparison.
def ask_questions():
choice = (random.choice(question))
index = question.index(choice)
print(choice)
print(options[index])
answer = raw_input(inputs)
if answer == answers[index]:
print("correct")
else:
print("incorrect")
del question[index]
del options[index]
For the loop:
while len(questions) > 1:
ask_questions()
That is just a sketch, because you did not post code that could be run link.
Also you are mixing print('sth') (python3) and print 'sth' (python2)
I am new to Stack overflow and have only recently began learning Python Programming. I am currently using Python 2.7 so there will be differences in my code compared to Python v3.
Anyway, I decided that I wanted to write a program that I can let my nephew and niece try out. The program created is a test with mathematics.
The code may not be the best or compact as it should be but it's my first go at it.
I have attached the code I have typed so far here. Please let me know your thoughts and any feedback.
My main question though is here:
I want to store the correct answers that the user-inputs in a variable. I want to then be able to output the number of questions that the user has got correct at the end of the test.
For example, if the user decides to take on a challenge of 5 problem sets and gets 3 correct, I want the program to output, you got 3/5 correct. I have a feeling that this will be something very simple but I have not yet thought of it.
I have tried to create a variable such as answersCorrect = 0 and then just answersCorrect += 1 to increment each time an answer is correct but I can't seem to make that work so I have left it off.
Any suggestions for this?
from sys import exit
import random
from random import randint
import math
def addition():
problems = int(input("How many problems do you want to solve?\n"))
random.seed()
count = 0
answersRight = 0
while count < problems:
num_1 = randint(1,12)
num_2 = randint(1,12)
userAnswer = int(input("What is " + str(num_1) + "+" + str(num_2) + "? "))
generatedAnswer = (num_1 + num_2)
if userAnswer == generatedAnswer:
print "Correct"
answersRight += 1
else:
print "Sorry, the answer is ", generatedAnswer, "\n"
count += 1
print "running score of answers right ", answersRight, " out of ", problems
print "Would you like to solve more problems?"
repeatAnswer = raw_input("> ")
if repeatAnswer == "Yes" or repeatAnswer == "Y" or repeatAnswer == "YES":
start()
elif repeatAnswer == "No" or repeatAnswer == "N" or repeatAnswer == "NO":
print "Thank you for completing the test anyway..."
exit()
else:
print "You have not entered a valid response, goodbye!"
exit()
def subtraction():
problems = int(input("How many problems do you want to solve?\n"))
random.seed()
count = 0
answersRight = 0
while count < problems:
num_1 = randint(1,12)
num_2 = randint(1,12)
userAnswer = int(input("What is " + str(num_1) + "-" + str(num_2) + "? "))
generatedAnswer = (num_1 - num_2)
if userAnswer == generatedAnswer:
print "Correct"
answersRight += 1
else:
print "Sorry, the answer is ", generatedAnswer, "\n"
count += 1
print "running score of answers right ", answersRight, " out of ", problems
print "Would you like to solve more problems?"
repeatAnswer = raw_input("> ")
if repeatAnswer == "Yes" or repeatAnswer == "Y" or repeatAnswer == "YES":
start()
elif repeatAnswer == "No" or repeatAnswer == "N" or repeatAnswer == "NO":
print "Thank you for completing the test anyway..."
exit()
else:
print "You have not entered a valid response, goodbye!"
exit()
def multiply():
problems = int(input("How many problems do you want to solve?\n"))
random.seed()
count = 0
answersRight = 0
while count < problems:
num_1 = randint(1,12)
num_2 = randint(1,12)
userAnswer = int(input("What is " + str(num_1) + "x" + str(num_2) + "? "))
generatedAnswer = (num_1 * num_2)
if userAnswer == generatedAnswer:
print "Correct"
answersRight += 1
else:
print "Sorry, the answer is ", generatedAnswer, "\n"
count += 1
print "running score of answers right ", answersRight, " out of ", problems
print "Would you like to solve more problems?"
repeatAnswer = raw_input("> ")
if repeatAnswer == "Yes" or repeatAnswer == "Y" or repeatAnswer == "YES":
start()
elif repeatAnswer == "No" or repeatAnswer == "N" or repeatAnswer == "NO":
print "Thank you for completing the test anyway..."
exit()
else:
print "You have not entered a valid response, goodbye!"
exit()
def divide():
problems = int(input("How many problems do you want to solve?\n"))
random.seed()
count = 0
answersRight = 0
while count < problems:
num_1 = randint(1,12)
num_2 = randint(1,12)
userAnswer = int(input("What is " + str(num_1) + "/" + str(num_2) + "? "))
generatedAnswer = (num_1 / num_2)
if userAnswer == generatedAnswer:
print "Correct"
answersRight += 1
else:
print "Sorry, the answer is ", generatedAnswer, "\n"
count += 1
print "running score of answers right ", answersRight, " out of ", problems
print "Would you like to solve more problems?"
repeatAnswer = raw_input("> ")
if repeatAnswer == "Yes" or repeatAnswer == "Y" or repeatAnswer == "YES":
start()
elif repeatAnswer == "No" or repeatAnswer == "N" or repeatAnswer == "NO":
print "Thank you for completing the test anyway..."
exit()
else:
print "You have not entered a valid response, goodbye!"
exit()
def start():
# Welcome messages
print "Welcome to this amazing game called Mathemagica!"
print "I hope you are ready for an amazing challenge :D"
print "My name is Mr MATHEMAGIC and i'm here to test you on your abilities"
print "...."
print "So, to begin please enter your Name: "
name = raw_input("> ")
print "Right. ", name, " Please enter your Age: "
age = raw_input("> ")
print "Thanks! So, ", name, " are you ready to begin your Mathematics Test? (Yes / No)"
response = raw_input("> ")
# Response Dependant directing to a particular function to be CALLED
if response == "Yes" or response == "YES" or response == "Y" or response == "y":
print """Which test would you like to take first? Please select an option below:
\t1. Addition
\t2. Subtraction
\t3. Multiplication
\t4. Division
"""
# Resonse here
problemSolver = raw_input("> ")
# Evaluating what option has been selected
if problemSolver == "1":
addition()
elif problemSolver == "2":
subtraction()
elif problemSolver == "3":
multiply()
elif problemSolver == "4":
divide()
else:
print "You have not entered a valid option, Goodbye!"
exit()
elif response == "No" or response == "NO" or response == "N" or response == "n":
print "That's fine. Have a good day :)"
exit(0)
else:
print"You have not entered a valid response, Bye"
start()
You need to be careful about where you place statements with respect to whether they are inside ifs and loops or not. Here is the correct code for addition, the others will be similar:
def addition():
problems = int(input("How many problems do you want to solve?\n"))
random.seed()
count = 0
answersRight = 0
while count < problems:
num_1 = randint(1,12)
num_2 = randint(1,12)
userAnswer = int(input("What is " + str(num_1) + "+" + str(num_2) + "? "))
generatedAnswer = (num_1 + num_2)
if userAnswer == generatedAnswer:
print "Correct"
answersRight += 1
else:
print "Sorry, the answer is ", generatedAnswer, "\n"
count += 1
print "running score of answers right ", answersRight, " out of ", problems
start()
let me change the question. how would i extract all of users information(score, class number and score) from a desired class. for e.g i want to know all the users info in lets class number 1.
to help, schooldata[x]['class_code'] = the class number the user types schooldata[x]['score'] = the score obtained by that student
schooldata[x]['name'] = name of that user
[x] is the student so the first user would be [0], 2nd user [1] etc...
schooldata = []
for x in range (0,3): #the number of loops the quiz is run which is 3 times
score = 0
quiz = dict()
print ("Enter your name")
quiz['name'] = input()
print ("what class")
quiz['class_code'] = input()
print("1. 9+10=")
answer = input()
answer = int(answer)
if answer == 19:
print("correct")
score = score + 1
else:
print("wrong")
print("2. 16+40=")
answer = input()
answer = int(answer)
if answer == 56:
print("correct")
score = score + 1
else:
print("wrong")
print("3. 5+21=")
answer = input()
answer = int(answer)
if answer == 26:
print("correct")
score = score + 1
else:
print("wrong")
print("4. 5-6=")
answer = input()
answer = int(answer)
if answer == -1:
print("correct")
score = score + 1
else:
print("wrong")
print("5. 21-9=")
answer = input()
answer = int(answer)
if answer == 12:
print("correct")
score = score + 1
else:
print("wrong")
print("6. 12-11=")
answer = input()
answer = int(answer)
if answer == 1:
print("correct")
score = score + 1
else:
print("wrong")
print("7. 5*6=")
answer = input()
answer = int(answer)
if answer == 30:
print("correct")
score = score + 1
else:
print("wrong")
print("8. 1*8=")
answer = input()
answer = int(answer)
if answer == 8:
print("correct")
score = score + 1
else:
print("wrong")
print("9. 4*6=")
answer = input()
answer = int(answer)
if answer == 24:
print("correct")
score = score + 1
else:
print("wrong")
print("10. 9*10=")
answer = input()
answer = int(answer)
if answer == 90:
print("correct")
score = score + 1
else:
print("wrong")
quiz['score'] = score
schooldata.append(quiz)
print ("name - ", schooldata[0]['name'],", user score - ", schooldata[0]['score'],", class number - ", schooldata[0]['class_code'])
print ("name - ", schooldata[1]['name'],", user score - ", schooldata[1]['score'],", class number - ", schooldata[1]['class_code'])
print ("name - ", schooldata[2]['name'],", user score - ", schooldata[2]['score'],", class number - ", schooldata[2]['class_code'])
#high to low
sorted_schooldata = sorted(schooldata, key=lambda k: k['score'])[::-1]
#alphabetical
for i in sorted(schooldata, key=lambda k: k['name']):
print('%s:%s' %(i['name'], i['score']))
Updating answer based on updated question:
classdata = {}
for data in schooldata:
if classdata.get(data['class_code']):
classdata[data['class_code']].append(data)
else:
classdata[data['class_code']] = [data]
print classdata
To print class data (in orderly manner):
for class_data in sorted(classdata):
for person_data in sorted(classdata[class_data], key=lambda x: x['name']):
print person_data['class_code'], person_data['name'], person_data['score']
Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 10 years ago.
Improve this question
This code works but is not as efficent as possible. Can you tell me how to make it more efficent? I belevie there is away to not have so many functions but I have forgotten how. The script is a multi choose quiz. I have defined each question as a new function. Is this the best way to do this?
def firstq (): # 1st Question
global q1list,answer1
q1list = ["Wellington","Auckland","Motueka","Masterton"]
q1count = 0
print ("Question 1")
print ("From which of the following Towns is the suburb NEWLANDS located?")
while q1count < 4:
print (q1count," ",q1list[q1count])
q1count = q1count + 1
answer1 = int(input("What number answer do you choose?"))
if answer1 == 0: print ("Correct answer!")
elif answer1 != 0: print ("Sorry! Incorrect Answer. Better luck with the next Question.")
print("Next Question below:")
print(" ")
print(" ")
def secq (): #Second Question
global q2list,answer2 # Makes answer2 and q2list avalible anywhere on the page.
q2list = ["Wellington","Christchurch","Pairoa","Dunedin"] # List of answers to choose from.
q2count = 0 # defines what the q2 count is. SEE BELOW
print ("Question 2")# prints "question 2"
print ("What NZ town is known for L&P?") # Prints the question
while q2count < 4:
print (q2count," ",q2list[q2count]) # Whilst the number of answers (q2list) is below 4 it will print the next answer.
q2count = q2count + 1
answer2 = int(input("What number answer do you choose?")) # asks for answer
if answer2 == 2: print ("Correct answer!") # If answer is correct, prints "Correct answer"
elif answer2 != 2: print ("Sorry! Incorrect Answer. Better luck with the next Question.") # If answer is correct, prints "Sorry! Incorrect Answer. Better luck with the next Question."
print("Next Question below:") # prints "Next Question
# these provide spacing!
print(" ")
print(" ")
def thrq ():
global q3list,answer3
q3list = ["Lewis Carroll","J.K. Rowling","Louis Carroll","Other"]
q3count = 0
print ("Question 3")
print ("Who wrote the book Alice In Wonderland?")
while q3count < 4:
print (q3count," ",q3list[q3count])
q3count = q3count + 1
answer3 = int(input("What number answer do you choose?"))
if answer3 == 0: print ("Correct answer!")
elif answer3 != 0: print ("Sorry! Incorrect Answer. Better luck with the next Question.")
print("Next Question below:")
print(" ")
print(" ")
def fouq ():
global q4list,answer4
q4list = ["WA","DC","WD","WC"]
q4count = 0
print ("Question 4")
print ("What is the abbreviation for Washington?")
while q4count < 4:
print (q4count," ",q4list[q4count])
q4count = q4count + 1
answer4 = int(input("What number answer do you choose?"))
if answer4 == 1: print ("Correct answer!")
elif answer4 != 1: print ("Sorry! Incorrect Answer. Better luck with the next Question.")
print("Next Question below:")
print(" ")
print(" ")
def fivq ():
global q5list,answer5
q5list = ["Yes","No, they're found around New Zealand","No","No, they're found around the UK"]
q5count = 0
print ("Question 5")
print ("Are walruses found in the South Pole?")
while q5count < 4:
print (q5count," ",q5list[q5count])
q5count = q5count + 1
answer5 = int(input("What number answer do you choose?"))
if answer5 == 2: print ("Correct answer!")
elif answer5 != 2: print ("Sorry! Incorrect Answer. Better luck with the next Question.")
print("Next Question below:")
print(" ")
print(" ")
def sixq ():
global q6list,answer6
q6list = ["G.M.","General M's","G Motors","Grand Motors"]
q6count = 0
print ("Question 6")
print ("What is the other name for General Motors?")
while q6count < 4:
print (q6count," ",q6list[q6count])
q6count = q6count + 1
answer6 = int(input("What number answer do you choose?"))
if answer6 == 0: print ("Correct answer!")
elif answer6 != 0: print ("Sorry! Incorrect Answer. Better luck with the next Question.")
print("Next Question below:")
print(" ")
print(" ")
def sevq ():
global q7list,answer7
q7list = ["Greece","USA","Egypt","Italy"]
q7count = 0
print ("Question 7")
print ("Which of the following countries were cats most honored in?")
while q7count < 4:
print (q7count," ",q7list[q7count])
q7count = q7count + 1
answer7 = int(input("What number answer do you choose?"))
if answer7 == 2: print ("Correct answer!")
elif answer7 != 2: print ("Sorry! Incorrect Answer. Better luck with the next Question.")
print("Next Question below:")
print(" ")
print(" ")
def eigq ():
global q8list,answer8
q8list = ["I find","I see","I presume","I am"]
q8count = 0
print ("Question 8")
print ("Complete this phrase-Dr. Livingstone,")
while q8count < 4:
print (q8count," ",q8list[q8count])
q8count = q8count + 1
answer8 = int(input("What number answer do you choose?"))
if answer8 == 2: print ("Correct answer!")
elif answer8 != 2: print ("Sorry! Incorrect Answer. Better luck with the next Question.")
print(" ")
print(" ")
def end():
if answer1 == 0 and answer2 == 2 and answer3 == 0 and answer4 ==1 and answer5 ==2 and answer6 ==0 and answer7 == 2 and answer8 == 2: print("YAY, all questions correct! You have won the 1 million!")
else: print("Sorry you have some incorrect questions! You have not won any money! :(") # If all answers are correct, this will display YAY, all questions correct! You have won the 1 million! If not it will print Sorry you have some incorrect questions! You have not won any money! :(.
def printorder ():
# Defines ther order that it will be printed in
firstq()
secq()
thrq()
fouq()
fivq()
sixq()
sevq()
eigq()
end()
name = l" " # while name is blank it will continue
while name != "quit": #While the name is not quit it will continue. If name is quit it will stop.
print ("The $1,000,000 Quiz! Can you win the 1 Million?")#Prints Welcome Message
name = input("Lets Get Started! What is your name: ")# asks for name
if name == "quit":
break # if the name is quit it will stop if not....
printorder()# ....prints printorder
This is just a pointer.
Instead of
def sixq():
global q6list, answer6
...
create a function
def question(qlist, qanswer):
...
and pass in qlist and qanswer as parameters, much of the code is duplicated and can be eliminated this way. And you also eliminate the use of globals at the same time. You can return whatever value(s) you need to the calling code at the end of this function using return. (note that Python allows you to return more than one value)
Adjust above as needed, ie if you need to supply another parameter etc. Essentially you want to factor out duplicate code into a single function, and provide the necessary parameters for what makes it unique.
Finally, using a single function in place of eight, will making maintaining your code much easier. If you find a problem with your code, or simply want to change something, you'll only have to correct it in one place, rather than in 8 different functions .. this is a major benefit.