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()
Related
This question already has answers here:
How do I forward-declare a function to avoid `NameError`s for functions defined later?
(17 answers)
Closed 29 days ago.
name = input("Please enter your name: ")
is not defined on line 15. Is there a way to make this work? I tried switching this line of code:To the bottom but then it does not prompth the user if they want to play.
Is there also a way i can prompth the user what subject they want to get tested on, then it will call the function to that subject and prompth the user with questions regarding that subject.
You're accessing variables/functions that are not defined or not within the scope where they are being accessed.
You need to define the math_Questions() function before you call it, that means moving it above the while loop at the top level.
Additionally, the variables incorrect and correct are not accessed within your function as they are not within the scope of the function. You can either create new variables inside the function or declare them as global variables at the top level, the former is the more preferred approach as you should avoid global variables where possible as it reduces the modularity of your code.
Working example
def math_Questions():
incorrect = 0
correct = 0
ans1 = input("Question 1: Ron had 6 bags of flour but used up 4 bags on Sunday. How many bags of flour did he have left?: ")
if ans1 == "2":
print("\nCorrect! " + ans1 + " is the right answer.")
correct += 1
else:
print("\nYou are way off. Start from the very beginning, or continue with the next one.")
incorrect += 1
print("")
print('So far, you answered correctly to {0} questions and incorrectly to {1}. Keep Going!'.format(correct, incorrect))
print("")
ans2 = input("Question 2: The Miller parking lot was full at the capacity of 15 this morning, now at the end of the day, 12 left the lot. How many cars are left in the parking lot?: ")
if ans2 == "3":
print("\nCorrect! " + ans2 + " is the right answer.")
correct += 1
else:
print("\nYou are way off. Start from the very beginning, or continue with the next one.")
print("")
print('So far, you answered correctly to {0} questions and incorrectly to {1}. Keep Going!'.format(correct, incorrect))
ans3 = input("Question 3: Mrs. Sheridan has 11 cats. How many more cats does Mrs. Sheridan need to have 43 cats?: ")
if ans3 == "32":
print("\nCorrect! " + ans3 + " is the right answer.")
correct += 1
else:
print("\nYou are way off. Start from the very beginning, or continue with the next one.")
print("")
print('So far, you answered correctly to {0} questions and incorrectly to {1}. Keep Going!'.format(correct, incorrect))
ans4 = input("Shelly bought a bed sheet for $1699. She gave the shopkeeper $2000. What amount will be returned by the shopkeeper?: ")
if ans4 == "301":
print("\nCorrect! " + ans4 + " is the right answer.")
correct += 1
else:
print("\nYou are way off. Start from the very beginning, or continue with the next one.")
print("")
print('So far, you answered correctly to {0} questions and incorrectly to {1}. Keep Going!'.format(correct, incorrect))
return (correct, incorrect)
name = input("Please enter your name: ")
print("")
run = int(input("Hello " + name + ", would you like to play a game? (Enter 1 to continue, 2 to exit): "))
print("")
while run == 1:
print("I will be asking a series of questions in each categories: mathematical, scientifical. Each question getting harder.")
correct, incorrect = math_Questions()
print("correct:", correct, ", incorrect: ", incorrect)
As for prompting the user for the subjects they want to get tested on, you can just make new functions for each subject and call based on the subject the user selects:
if (subject == "chemistry"):
chem_questions()
I would also suggest storing the question and answer pairs within a dict or json object to make the code more readable and the program more modular and scalable.
Firstly, you need to properly format your code for a start. Correct indents are important in python. Each indent should be exactly 4 spaces, no more, no less. It also makes your code much easier to read.
Secondly, you should declare your methods and classes first, then your code to call those methods.
Thirdly, you need to be careful of initialising variables that then get called in the function (ie correct = 0 and incorrect = 0). This is generally bad practice. In order to work they need to be re-declared in method as global. In your case, just declare them in method ONLY. Your code should look more like:
def math_questions():
correct = 0
incorrect = 0
ans1 = input("Question 1: Ron had 6 bags of flour but used up 4 bags on Sunday. How many bags of flour did he have left?: ")
if ans1 == "2":
print("\nCorrect! " + ans1 + " is the right answer.")
correct += 1
else:
print("\nYou are way off. Start from the very beginning, or continue with the next one.")
incorrect += 1
print("")
print('So far, you answered correctly to {0} questions and incorrectly to {1}. Keep Going!'.format(correct, incorrect))
print("")
ans2 = input("Question 2: The Miller parking lot was full at the capacity of 15 this morning, now at the end of the day, 12 left the lot. How many cars are left in the parking lot?: ")
if ans2 == "3":
print("\nCorrect! " + ans2 + " is the right answer.")
correct += 1
else:
print("\nYou are way off. Start from the very beginning, or continue with the next one.")
print("")
print('So far, you answered correctly to {0} questions and incorrectly to {1}. Keep Going!'.format(correct, incorrect))
ans3 = input("Question 3: Mrs. Sheridan has 11 cats. How many more cats does Mrs. Sheridan need to have 43 cats?: ")
if ans3 == "32":
print("\nCorrect! " + ans3 + " is the right answer.")
correct += 1
else:
print("\nYou are way off. Start from the very beginning, or continue with the next one.")
print("")
print('So far, you answered correctly to {0} questions and incorrectly to {1}. Keep Going!'.format(correct, incorrect))
ans4 = input("Shelly bought a bed sheet for $1699. She gave the shopkeeper $2000. What amount will be returned by the shopkeeper?: ")
if ans4 == "301":
print("\nCorrect! " + ans4 + " is the right answer.")
correct += 1
else:
print("\nYou are way off. Start from the very beginning, or continue with the next one.")
print("")
print('So far, you answered correctly to {0} questions and incorrectly to {1}. Keep Going!'.format(correct, incorrect))
name = input("Please enter your name: ")
print("")
run = int(input("Hello " + name + ", would you like to play a game? (Enter 1 to continue, 2 to exit): "))
print("")
while run == 1:
print("I will be asking a series of questions in each categories: mathematical, scientifical. Each question getting harder.")
math_questions()
Furthermore, I would recommend breaking down your code into smaller chunks and re-use code where possible. All your if statements have the same format and lend themselves to being put into another function or some loop. Look at:
def question_answered_correctly(new_question, correct_answer):
ans = input(new_question)
return ans == correct_answer:
def math_questions():
correct = 0
incorrect = 0
question_list = [
{
'question': "Question 1: Ron had 6 bags of flour but used up 4 bags on Sunday. How many bags of flour did he have left?: ",
'answer': '2'},
{
'question': "Question 2: The Miller parking lot was full at the capacity of 15 this morning, now at the end of the day, 12 left the lot. How many cars are left in the parking lot?: ",
'answer': '3'},
{
'question': "Question 3: Mrs. Sheridan has 11 cats. How many more cats does Mrs. Sheridan need to have 43 cats?: ",
'answer': '32'},
{
'question': "Question 4: Shelly bought a bed sheet for $1699. She gave the shopkeeper $2000. What amount will be returned by the shopkeeper?: ",
'answer': '301'}
]
for question in question_list:
if question_answered_correctly(question['question'], question['answer']):
print("\nCorrect! " + question['answer'] + " is the right answer.")
correct += 1
else:
print("\nYou are way off. Start from the very beginning, or continue with the next one.")
incorrect += 1
print("")
print('So far, you answered correctly to {0} questions and incorrectly to {1}. Keep Going!'.format(correct, incorrect))
name = input("Please enter your name: ")
print("")
run = int(input("Hello " + name + ", would you like to play a game? (Enter 1 to continue, 2 to exit): "))
print("")
while run == 1:
print("I will be asking a series of questions in each categories: mathematical, scientifical. Each question getting harder.")
math_questions()
I need to add a loop to my program somewhere where can I add it in\
def start():
#introduction
print("Here is a quiz to test your knowledge of Pixar")
print("please enter the lower letter of the answer or it will not work")
person = input("Enter you Name: ")
points = -50
#Q1 ask a question
print("What year was toy story released")
answer = input("A. 1995 B. 2002 C.1999 = ")
# a is answer
if answer == "a":
print ("Your Right")
points += 11.1
else:
print ("you need to get better")
print ("the correct answer 1995 was ")
#Q10
print("What was the name of the bad guy in up")
answer = input("A. Kevin Wilson B. Charles Muntz C. Mike whiting = ")
if answer == "b":
print("that’s a righta")
points += 78.45
points += 0.25
else:
print("not quite")
print("the correct answer was Charles Muntz")
print("Well done" , person)
print("Your final score is {}".format(points))
print("you are the best" , person)
print("I Know" , person)
if op.lower() in {'q', 'quit', 'e', 'exit'}:
print("Goodbye!")
I want to add the loop so when you finish you go back to the start but I don't know how to do that could someone help me.
Consider using a While loop. Specifically, just inserting all your code as follows should do the job:
**While True:**
.....
.....
I have not run your code, but I think a break statement would be needed for your final "if" statement (in order to not run endlessly), specifically:
if op.lower() in {'q', 'quit', 'e', 'exit'}:
print("Goodbye!")
break
Apart from those edits, I think that all the inputting and whatnot should be fine.
This is my first Python program where I've used if, while and functions. I've also passed parameters. The problem is the IF. Can you help me? I wanted the program to give the user two tries to answer and then end. If correct then it ends but if not correct it doesn't stop, keeps looping.
"""this is a quiz on computer science"""
q1Answer="c"
def questionOne():
print("Here is a quiz to test your knowledge of computer science...")
print()
print("Question 1")
print("What type of algorithm is insertion?")
print()
print("a....searching algorithm")
print("b....decomposition ")
print("c....sorting algorithm ")
print()
def checkAnswer1(q1Answer): #q1Answer is a global variable and is needed for this function so it goes here as a parameter
attempt=0 #These are local variables
score=0
answer = input("Make your choice >>>> ")
while attempt <1:
if answer==q1Answer:
attempt= attempt+1
print("Correct!")
score =score + 2
break
elif answer != q1Answer:
answer =input("Incorrect response – 1 attempt remaining, please try again: ")
if answer ==q1Answer:
attempt = attempt + 1
print("Correct! On the second attempt")
score =score + 1
break
else:
print("That is not correct\nThe answer is "+q1Answer )
score =0
return score # This is returned so that it can be used in other parts of the program
##def questionTwo():
## print("Question 2\nWhat is abstraction\n\na....looking for problems\nb....removing irrelevant data\nc....solving the problem\n")
def main():
q1answer = questionOne()
score = checkAnswer1(q1Answer)
print ("Your final score is ", score)
main()
The problem is you aren't incrementing the attempt if they get it wrong the second time. You need another attempt = attempt + 1 (Or alternatively attempt += 1) after the break
So your elif block would look like:
elif answer != q1Answer:
answer =input("Incorrect response – 1 attempt remaining, please try again: ")
if answer ==q1Answer:
attempt = attempt + 1
print("Correct! On the second attempt")
score =score + 1
break
attempt = attempt + 1
This allows the attempt counter to increment even if they fail the second time, tiggering the fail and end of loop.
You just add attempt +=1 after the loops.
q1Answer="c"
def questionOne():
print("Here is a quiz to test your knowledge of computer science...")
print()
print("Question 1")
print("What type of algorithm is insertion?")
print()
print("a....searching algorithm")
print("b....decomposition ")
print("c....sorting algorithm ")
print()
def checkAnswer1(q1Answer): #q1Answer is a global variable and is needed for this function so it goes here as a parameter
attempt=0 #These are local variables
score=0
answer = input("Make your choice >>>> ")
while attempt <1:
if answer==q1Answer:
attempt= attempt+1
print("Correct!")
score =score + 2
break
elif answer != q1Answer:
answer =input("Incorrect response – 1 attempt remaining, please try again: ")
if answer ==q1Answer:
attempt = attempt + 1
print("Correct! On the second attempt")
score =score + 1
break
else:
print("That is not correct\nThe answer is "+q1Answer )
score =0
attempt += 1
break
return score # This is returned so that it can be used in other parts of the program
##def questionTwo():
## print("Question 2\nWhat is abstraction\n\na....looking for problems\nb....removing irrelevant data\nc....solving the problem\n")
def main():
q1answer = questionOne()
score = checkAnswer1(q1Answer)
print ("Your final score is ", score)
main()
What is the problem with my code? At the moment it is asking the question about name but nothing else? I think it is something with calling upon items from a list; I used string, but I think that is incorrect. Can anyone help me with what I should do?
subs=["Multiplication" , "Addition" , "Subtraction"]
import random
score=0
def addition_sub1():
a=random.randint(1,20)
b=random.randint(1,20)
question1=int(input("What is" +str(a)+ "+" +str(b)+ ""))
c=(a+b)
if question == c:
print("Correct!")
score=score+1
else:
print("Incorrect!")
return score
def subtraction_sub1():
d=random.randint(1,20)
e=random.randint(1,20)
question2=int(input("What is" +str(a)+ "+" +str(b)+ ""))
f=(d+e)
if question2 == f:
print("Correct!")
score=score+1
else:
print("Incorrect!")
return score
def Multiplication_sub1():
g=random.randint(1,20)
h=random.randint(1,20)
question2=int(input("What is" +str(a)+ "+" +str(b)+ ""))
i=(d+e)
if question2 == i:
print("Correct!")
score=score+1
else:
print("Incorrect!")
return score
name=input("What is your name? ")
print("Welcome to my quiz " +name)
for i in range(0,9):
op=random.choice(subs)
if op == str(0):
Multiplication_sub1()
if op == str(1):
addition_sub1()
if op == str(2):
subtraction_sub1()
random.choice will return a random element from the list. So the code should be:
if op == "Multiplication":
Multiplication_sub1()
if op == "Addition":
addition_sub1()
if op == "Subtraction":
subtraction_sub1()
However, I'd like to give you a few suggestions.
It's fine to have variables with the same name in different functions. You can call them a, b, and question in all functions.
Since the three if conditions are mutually exclusive, you should replace the two at the bottom with elif.
I've started learning Python at school for around a month now, and I have decided to make a quiz. I have added in a scoring system so if you were to answer a question incorrectly, it would tell you your score. However, this is not working and it always will give you a score of 0. Also, is there a way of only putting one else statement if they were to fail a question, instead of one for each question? Thanks :)
Here's an example of the code(Python 3.2.3):
#QUIZ
print("Welcome to the quiz")
print("Please choose a difficulty:")
difficulty = input("A) Hard B)Easy")
if difficulty == "A":
score = 0
print("")
def question(score):
print("You chose the hard difficulty")
print("Where is the Great Victoria lake located?")
answer1 = input("A) Canada B)West Africa C)Australia D)North America")
if answer1 == "C":
print("Correct")
score = score+1
else:
print("you failed the quiz")
print("Score:",score)
quit()
def question2(score):
print("Who is most responsible for cracking the Enigma Code")
answer2 = input("A) Alan Turing B) Jeff Bezos C) George Boole D) Charles Babbage")
if answer2 == "A":
print("Correct")
score = score+1
else:
print("you failed the quiz")
print("Score:",score)
quit()
def diff_easy(difficulty):
if difficulty == "B":
score2 = 0
print("")
def question4(score2):
print("You chose the easy difficulty")
print("What is the capital of Australia?")
answer1 = input("A) Canberra B) Sydney C)Melbourne")
if answer1 == "A":
print("Correct")
score2 = score2+1
else:
print("you failed the quiz")
print("Score:",score2)
quit()
def question5(score2):
print("When was the Great Fire of London?")
answer2 = input("A) 1666 B) 1555 C)1605")
if answer2 == "A":
print("Correct")
score2 = score2+1
else:
print("you failed the quiz")
print("Score:",score2)
quit()
if difficulty == "A":
question(score)
question2(score)
if difficulty == "B":
diff_easy(difficulty)
question4(score2)
question5(score2)
This is because the score variable you see inside your functions is a copy of the score variable you set, being passed by value (I strongly suggest you revise this topic). You need a way to pass the status around.
Soon you will discover objects, for now (and never more in the future!), a simple solution is making the score variable a global. Just replace
def question2(score):
with
def question2():
in all of your question functions and add global score as the first statement in each, like this:
def question5():
global score
print("When was the Great Fire of London?")
answer2 = input("A) 1666 B) 1555 C)1605")
if answer2 == "A":
print("Correct")
score = score + 1
else:
print("you failed the quiz")
print("Score:", score)
quit()
Replace all the occurences of score2 with score and you are done.
Of course you can use a single if: else branch for all questions. I will not give you the full solution, so that you can exercise, but here is a hint: make a function that will take three arguments:
the question
a list of possible answers
the correct answer
let's call this function quiz. Now you can use it like this:
quiz("When was the Great Fire of London?", ["1666", "1555", "1605"], "1666")
quiz("What is the capital of Australia?", ["Canberra", "Sydney", "Melbourne"], "Canberra")
The statements like
score2 = score2+1
in your code have no effect, because they modify a local variable.
For the other question: you should use a data structure to store questions and answers, so that you can iterate over them without repeating the same code many times.