Storing correct answers and keeping track - python

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

Related

Why is my Python code ignoring my if-statement and not quitting when I add the answer "no"?

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

Error: variable referenced before assignment

import random
import time
print ("Welcome to the Game")
print ("You must complete the next 10 Multiplication Questions to be truly ready for the challenges of life")
print ("")
choice = input("Are you ready? Y / N: ")
print("")
def play():
while questions != 10:
num1 = random.randrange(9,17)
num2 = random.randrange(6,17)
print("What does " + str(num1) + " x " + str(num2) + " = ")
guess1 = input("Your guess?: ")
answer1 = (num1*num2)
if int(guess1) == answer1:
print("Correct")
time.sleep(1)
counter = counter + 1
questions = questions + 1
print("")
else:
print("Your answer was Wrong")
time.sleep(1)
print("The real answer was")
time.sleep(1)
print (str(answer1))
questions = questions + 1
print("")
if questions == 10:
print ("You got " + str(counter) + " out of 10")
return
play()
From the information available for now, I would say that this is because you did not assign any value for
questions
variable
To solve this, simply add
questions = 10 # or other value you may want
at the very start of the play() function
You need to initialize questions variable to 0 before while loop and also initialize counters variable to 0 and return statement should be outside while loop.
Below is the corrected code
import random
import time
print ("Welcome to the Game")
print ("You must complete the next 10 Multiplication Questions to be truly ready for the challenges of life")
print ("")
choice = input("Are you ready? Y / N: ")
print("")
def play():
#initialization
questions,counter =0,0
while questions != 10:
num1 = random.randrange(9,17)
num2 = random.randrange(6,17)
print("What does " + str(num1) + " x " + str(num2) + " = ")
guess1 = input("Your guess?: ")
answer1 = (num1*num2)
if int(guess1) == answer1:
print("Correct")
time.sleep(1)
counter = counter + 1
questions = questions + 1
print("")
else:
print("Your answer was Wrong")
time.sleep(1)
print("The real answer was")
time.sleep(1)
print (str(answer1))
questions = questions + 1
print("")
if questions == 10:
print ("You got " + str(counter) + " out of 10")
# return outside while loop
return
play()
An example for you:
#!/usr/bin/env python3.6
import time
from random import randrange
def play():
counter = 0
for i in range(10):
num1 = randrange(9, 17)
num2 = randrange(6, 17)
print(f"What does {num1} x {num2} = ")
guess = input("Your guess?: ")
answer = str(num1 * num2)
if guess == answer:
print("Correct\n")
counter += 1
else:
print("Your answer was Wrong")
print(f"The real answer was {answer}\n")
time.sleep(0.5)
print("You got " + str(counter) + " out of 10")
def main():
print(
"Welcome to the Game\n"
"You must complete the next 10 Multiplication Questions "
"to be truly ready for the challenges of life\n"
)
choice = input("Are you ready? Y / N: ")
if choice.upper() == "N":
return
print()
play()
if __name__ == "__main__":
main()

Calling a function in an if statement?

I'm trying to write an if statement where if the user enters "yes" a game runs but when I cannot figure out how to do this, I can't find it online.
userName = input("Hello, my name is Logan. What is yours? ")
userFeel = input("Hello " + userName + ", how are you? ")
if userFeel == "good":
print ("That's good to hear")
elif userFeel == "bad":
print ("Well I hope I can help with that")
q1 = input("Do you want to play a game? ")
if q1 == "yes":
print ("Alright, lets begin")
import random
print ("This is a guessing game")
randomNumber = random.randint(1, 100)
found = False
yes = "yes"
while not found:
userGuess = input('Your Guess: ') ; userGuess = int(userGuess)
if userGuess == randomNumber:
print ("You got it!")
found = True
elif userGuess>randomNumber:
print ("Guess Lower")
else:
print ("Guess Higher")
elif game == "no":
print ("No? Okay")
q2 = input("What do you want to do next? ")
This is because you have named both your variable for your input "game" and your function call "game". rename one or the other and your code should work as intended.
If you are using Python2.*, You should use raw_input instead of input.
And no matter what version of Python you are using, you should not use the same name for both the function and your variable.

Unexpected EOF while Parsing In Russian Roulette

Im doing a little home project since I'm learning python (beginner) and I made my self a Russian roulette game and it comes up with Unexpected EOF while Parsing on the last line. So if some could help me out on whats going wrong I will be very thankful.
import random
print ("Welcome to Russian Roulette without guns :/ ")
amount = input("How many players? 2 or 3 or 4:")
if amount == ("2"):
print ("Player 1 Name")
player_1 = input(" ")
print ("Player 2 Name")
player_2 = input(" ")
print (player_1)
enter = input("Click Enter:")
if enter == (""):
number = random.randint(1, 2)
print (number)
if number == 1:
print (player_1)
print ("You dead")
print ("---------")
print (player_2)
print ("You win")
else:
print (player_2)
enter_2 = input("Click Enter:")
if enter_2 == (""):
number_2 = random.randint(1, 2)
if number_2 == 1:
print (player_2)
print ("You Lose")
print ("---------")
print (player_1)
print ("You win")
elif amount == ("3"):
print ("Player 1 Name")
player_1 = input(" ")
print ("Player 2 Name")
player_2 = input(" ")
print ("Player 3 Name ")
player_3 = input(" ")
print (player_1)
enter_3 = input("Click Enter:")
if enter_3 == (""):
number_3 = random.randint(1, 1)
print (number)
if number == 3:
print (player_1)
print ("You Dead")
print ("Your Out")
print ("-------------")
print ("{0}, {1} You are still in".format(player_1, player_2)
On the last line, you are missing a closing parenthesis. It should be:
print ("{0}, {1} You are still in".format(player_1, player_2))
EOF is end of file so it usually an an unexpected termination of the program, which is most likely caused by one of a few things, in python: if you missed closing parentheses, or a missing ; in the last line/ line before (so it runs as one line with out the ;). however i can tell you that you are missing closing parentheses at the end of the last print statement. also just a small improvement i would suggest, comment your code python is quite easy to read but its good practice for languages that are not as easy to read.

python programming help (calculate percentage)

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

Categories