Python Quiz Scoring and Conditional Statement Problems - python

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.

Related

Building randomized multiple choice quiz in Python. How to pull up additional questions?

I am a new programmer working on my very first Python program ever.
I am building a little quiz game in Python. The code contains ten possible quiz questions. In order to win, the user must get four of them correct in a row. To make the game more playable, I've set the questions to be assigned to a random number generator.
So far, so good, but I'm not sure how to ask the program to go BACk and run the number generator again after the user has completed the first question. I don't think I quite understand how to frame the loop?
Here's my code. I imagine there's a more elegant way to write this, but with each question having different multiple choice options, I wasn't sure of the best way to throw everything in an elegant loop.
How can I tweak this so the user actually gets more than one question?
import random
#Intro message
print("Welcome to Where In The World Is The Civil ConFLiCT Trophy?")
print("Brought to you by Extra Points.")
user_name = input ("What is your name?")
print("Okay, " + str(user_name) + ". Here is the deal.")
print("")
print("Bob Diaco has stolen the critically important college football landmark, the Civil ConFLiCT Trophy.")
print("That trophy belongs in a musuem! Or at least, somewhere in the catacombs of the UCF athletic department.")
user_choice = input ("Will you help us find it?")
#decision tree around "will you help us find it"
if user_choice == "no":
print("then why the hell did you play this game?")
elif user_choice == "yes":
print("Great. Let's follow our first clue.")
else:
print("Please answer yes or no. I'm too stupid to program anything else.")
#here is where I'm gonna try to put my question variables
question_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
user_score = 0
wrong_answer = "Sorry, that was incorrect. Now Bob Diaco got away."
right_answer = "Correct! To the next clue!"
#The goal here is for the user to answer four questions correctly.
#Each correct answer should increase their score by one. A failed answer should end the game.
computer_action = random.choice(question_list)
if computer_action == 1:
print("Diaco is on the run towards the school with the smallest enrollment in FBS. Where should we go?")
print("A. Navy.")
print("B. Tulsa.")
print("C. SMU.")
print("D. Rice.")
user_answer_1 = input("Please answer A, B, C or D.")
if user_answer_1 == "B":
print(right_answer)
user_score + 1
computer_action = random.choice(question_list)
else:
print(wrong_answer)
elif computer_action == 2:
print("That dastardly Diaco absconded with the trophy and is off to the city that hosted the Salad Bowl, which was a real college football game that we didn’t make up.")
print("A. Phoenix, AZ")
print("B. Cleveland, OH")
print("C. Evansville, IN")
print("D. Santa Fe, NM.")
user_answer_2 = input("Please answer A, B, C or D.")
if user_answer_2 == "A":
print(right_answer)
user_score + 1
computer_action = random.choice(question_list)
else:
print(wrong_answer)
elif computer_action == 3:
print("Now Diaco has fled to the campus of the last D-1 school to drop football completely. Note: I said D-1, NOT FBS! ")
print("A. Hofstra.")
print("B. Idaho.")
print("C. Jacksonville.")
print("D. Seton Hall.")
user_answer_3 = input("Please answer A, B, C or D.")
if user_answer_3 == "C":
print(right_answer)
user_score + 1
computer_action = random.choice(question_list)
else:
print(wrong_answer)
elif computer_action == 4:
print("Bob Diaco has taken the trophy and fled to the only school on this list where John Heisman did NOT coach.")
print("A. Wooster")
print("B. Oberlin")
print("C. Auburn")
print("D. Rice")
user_answer_4 = input("Please answer A, B, C or D.")
if user_answer_4 == "A":
print(right_answer)
user_score + 1
computer_action = random.choice(question_list)
else:
print(wrong_answer)
elif computer_action == 5:
print("So close! But we just missed it. Now Diaco has taken the trophy to where Amos Alonzo Stagg coached immediately after leaving Chicago. ")
print("A. Northwestern")
print("B. Notre Dame")
print("C. San DIego State")
print("D. Pacific")
user_answer_5 = input("Please answer A, B, C or D.")
if user_answer_5 == "D":
print(right_answer)
user_score +1
computer_action = random.choice(question_list)
else:
print(wrong_answer)
elif computer_action == 6:
print("Gasp, we missed it again! Now, the trophy is hiding at the stadium with the smallest capacity in FBS. Or at least, according to Wikipedia.")
print("A. Coasta Carolina.")
print("B. Charlotte.")
print("C. Ball State.")
print("D. Nevada.")
user_answer_6 = input("Please answer A, B, C or D.")
if user_answer_6 == "B":
print(right_answer)
user_score + 1
computer_action = random.choice(question_list)
else:
print(wrong_answer)
elif computer_action == 7:
print("Aww hamburgers, the trophy is on the move again! This time, it’s allegedly bound for the campus of the P5 program with the worst bowl winning percentage!")
print("A. Wake Forest.")
print("B. Duke.")
print("C. Indiana.")
print("D. Iowa State.")
user_answer_7 = input("Please answer A, B, C or D.")
if user_answer_7 == "C":
print(right_answer)
user_score + 1
computer_action = random.choice(question_list)
else:
print(wrong_answer)
elif computer_action == 8:
print("Rats, it looks like we just missed it! Now I hear the trophy is headed to the campus with the highest winning percentage in all of FBS football.")
print("A. Ohio State.")
print("B. Michigan.")
print("C. Notre Dame.")
print("D. Boise State.")
user_answer_8 = input("Please answer A, B, C or D.")
if user_answer_8 == "D":
print(right_answer)
user_score + 1
computer_action = random.choice(question_list)
else:
print(wrong_answer)
elif computer_action == 9:
print("Legend has it, the trophy was mailed to the campus of the FBS record holder for most passing touchdowns in a single game.")
print("A. Hawaii.")
print("B. Houston.")
print("C. Texas Tech.")
print("D. Wisconsin.")
user_answer_9 = input("Please answer A, B, C or D.")
if user_answer_9 == "B":
print(right_answer)
user_score + 1
computer_action = random.choice(question_list)
else:
print(wrong_answer)
elif computer_action == 10:
print("Rumor has it, the trophy is off to the city where Woody Hayes got his first head coaching job!.")
print("A. Columbus, OH.")
print("B. Oxford, OH.")
print("C. Granville, OH.")
print("D. Athens, OH.")
user_answer_10 = input("Please answer A, B, C or D.")
if user_answer_10 == "C":
print(right_answer)
user_score + 1
computer_action = random.choice(question_list)
else:
print(wrong_answer)
if user_score == 4:
print("Congrats! You've finally aprehended Bob Diaco and the mythical Civil ConFliCT Trophy. It can now be sent to the College Football Hall of Fame to be properly enjoyed by everybody. Except UConn, probably.")
print("")
Put:
while user_score < 4:
On the line right above
computer_action = random.choice(question_list)
And then take every line below the while and tab it out once to put all of that in the while loop. (If you're using a decent text editor, you should just be able to select all those lines and hit tab. If not, I strongly recommend switching to like Notepad++ or Thonny or something)
Then remove the if statement that checks the user score (That's the while loop's job now.) And put the "You've won!" stuff below and outside of the loop.
Whenever your program reaches the bottom of a while loop, it jumps to the top if the condition in the loop header (In this case that's user_score < 4) is still true, otherwise it leaves the loop. So in this case, the code will exit the loop and print the "Congrats!" message when the user's score is no longer less than 4.

How do I fix my algorithm from messing up my input in my choose your own adventure game?

I'm working on a choose your own adventure text game on python and I added an algorithm that makes it so if you press the H key your hunger is shown and if you press T the time left is shown. But when I run my code the script runs but after the first input option is entered for your name, the breakfast yes/no input question gets printed again and again no matter what is entered. When i delete my algorithm, it runs fine and goes into the next step. I know I probably made a very stupid mistake but I am fairly new and I would greatly appreciate it if I could get some help. Thank you!
My code:
import keyboard
hunger = 100
timeLeft = 100
yes_no = ["yes", "no"]
breakfast = ["eggs", "cereal"]
name = input("What is your name?\n")
print("Hello, " + name + "! This is the BREAKFAST STORY.")
answer = ""
while answer not in yes_no:
answer = input("You wake up one morning and are very hunrgy, do you get breakfast? (yes/no?)")
if answer == "yes":
print("You enter the kitchen, your hunger gets worse every second.")
elif answer == "no":
print("You starve to death. The End!")
quit()
answer = ""
while answer not in breakfast:
answer = input("What do you eat? (eggs/cereal?) ")
if answer == "eggs":
print("Good job! You fed yourself, you stayed alive and you live a happy life")
quit()
elif answer == "cereal":
print("Sorry, the cereal was 10 years overdue, you die terribly!. Rest in peace,"+ name +".")
quit()
#algorithm
if(keyboard.is_pressed('t')):
timeLeftFunction()
elif(keyboard.is_pressed('h')):
hungerFunction()
def timeLeftFunction():
timeLeft -= 20
print("TIME LEFT:"+timeLeft+"%")
def hungerFunction():
hunger -= 30
print("HUNGER"+"%")

How can i add or fix my program so it loops to the start

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.

Simple choice game Python IDLE 3.4 How to proceed with different choices?

I'm very new to programming and was doing a simple choice game:
Answer = (input("You meet a bear, what do you do? A) Give the bear a hug B) Run away"))
if Answer == ("A)"):
print("The bear chopped your hand off!")
else:
print("Good choice, but the bear is running after you")
But how do I go on? Like add an option after having proceeded with a chopped of hand or running through the forest (2 choices at least for both previous outcomes)
Here is a start you can hopefully figure out how to expand on :)
def main():
print("Tristan Aljamaa's Simple Python Choice Game")
print("===========================================")
print("Instructions: Type A) or B) etc. whenever prompted\n")
game()
def game():
Answer = (input("You meet a bear, what do you do?\n A) Give the bear a hug\n B) Run away \nEnter A) or B):"))
if Answer == ("A)"):
print("The bear chopped your hand off!")
player_died()
else:
print("Good choice, but the bear is running after you")
player_ran()
def player_died():
print("You died, the bear eventually ate you...")
Answer = (input("Game Over!\n\nEnter N) for New Game:"))
if Answer == ("N)"):
main()
else:
print("Good Bye!")
def player_ran():
Answer = (input("You find an exit from the forest, what do you do\n A) Exit forest\n B) Run around in forest \nEnter A) or B):"))
if Answer == ("A)"):
print("You exited the forest")
player_crossedRoad()
else:
print("You (although insanly) chose to run around in the forest")
player_stillRunsinForest()
def player_crossedRoad():
print("You get the idea...")
main() #for testing on this online editor use the below line when calling the .py file on your computer
if __name__ == "__main__":main()
Try the game out here
You could create different functions/procedures for different cases. For example:
def choppedHand():
selection = input("The bear chopped your hand off! What do you do now? \n 1.Fight the bear with one hand.\n 2. Scream and search for help.\n 3. Cry and beg for mercy")
if selection == "1":
fight()
elif selection == "2":
scream()
else:
cry()
def run():
selection = input ("Good choice, but the bear is running after you. What do you do now? 1.Run through the trees. 2.Run in the plain")
#etc etc, same as top.
Answer = (input("You meet a bear, what do you do?\n 1.Give the bear a hug.\n 2.Run away."))
if Answer == ("1"):
choppedHand()
else:
run()
This is just an example, but using functions you can create different options for different cases and call a function in other parts of your code. For example you character can lose his arm in a different situation and in this case you just need to recall you function choppedHand().
I hope this was what you were looking for.
def invalid():
print("Answer not valid")
def game():
Answer = input("You meet a bear, what do you do?\nA) Give the bear a hug\nB) Run away\n>? ")
if Answer == ("A"):
print("The bear chopped your hand off!")
Answer2 = input("The bear is still around you, what will you do?\nA) Bleed out and accept your fate\nB) Try to fight back\n>? ")
if Answer2 == ("A"):
print("You bled out and died")
elif Answer2 == ("B"):
print("You attempt to fight back\nYou have failed, and died")
elif Answer == ("B"):
Answer3 = input("You find a tree and the bear is still running, what do you do?\nA) Climb the tree\nB) Hide behind the tree\n>? ")
if Answer3 == ("A"):
print("You went up the tree, and the bear went away!")
print("You walked home and went to bed")
elif Answer3 == ("B"):
Answer4 = input("You fell down a hill and slid into a village, what do you do?\nA) Trade with a villager\nB) Head home\n>? ")
if Answer4 == ("A"):
Answer5 = input("There is only one merchant, will you trade?\nA) Yes\nB) No")
if Answer5 == ("A"):
print("You traded two gold coins for a sword made of strong steel")
print("You headed home")
elif Answer5 == ("B"):
print("You did not trade, so you headed home")
else:
invalid()
elif Answer4 == ("A"):
print("You headed home")
else:
invalid()
else:
invalid()
else:
invalid()
game()

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