I'm having problems whilst creating a quiz using python loops - python

The start of my code works fine but,the bottom part consisting on the score and answer doesn't. I'm doing a school project on this and need a solution quick. But I have to be using loops! The part where i'm trying to tell the user that the answer is correct isn't working. The part where i'm revealing the right answer isn't working as well. The score isn't working as well.
print ('WELCOME TO THE MULTIPLE CHOICE TEST\n')
name = input('WHAT IS YOUR NAME? ')
print ('\nHI THERE ' + name + '! LET''S PLAY A GAME!\n')
print ('I will ask you 10 questions and give you three choices for each question.\n\nYou select which choice is the correct answer. Eg. A, B,C or D\n')
score = 0
score = int(score)
qn1 = ["What's color of sky?", "a)Red", "b)Blue", "c)White", "d)Black"]
def print_question(qn_num):
print(qn_num[0])
print(qn_num[1])
print(qn_num[2])
print(qn_num[3])
print(qn_num[4])
print_question(qn1)
answer = input ()
answer =int(answer)
if answer == 2:
print ("good work")
score = score + 1
else:
print ("better luck next time")
score = score - 1

You can ask the answer in an infinite loop, and also show the score
print ('WELCOME TO THE MULTIPLE CHOICE TEST\n')
name = input('WHAT IS YOUR NAME? ')
print ('\nHI THERE ' + name + '! LET''S PLAY A GAME!\n')
print ('I will ask you 10 questions and give you three choices for each question.\n\nYou select which choice is the correct answer. Eg. A, B,C or D\n')
score = 0
score = int(score)
qn1 = ["What's color of sky?", "a)Red", "b)Blue", "c)White", "d)Black"]
def print_question(qn_num):
for st in qn_num:
print(st)
print_question(qn1)
allowed_answers = ["a", "b", "c", "d"]
wrong_answer = True
while(wrong_answer):
answer = input ("select answer: ")
if answer == 'b':
print ("good work")
score = score + 1
wrong_answer = False
elif answer not in allowed_answers:
print ("Bad input, you have to chose between " + ",".join(allowed_answers) )
else:
print ("better luck next time")
score = score - 1
print("Your score is: " + str(score))

Related

What is the best way to make a guessing loop in python?

Basically I'm trying to make a guessing game. There are 3 questions and you have 3 guesses for every question. The problem is I'm bad at coding, this is only my first time.
print("Guessing Game")
player_name = input("Hi! What's your name? ")
number_of_guesses1 = 0
number_of_guesses2 = 0
number_of_guesses3 = 0
guess1 = input("What is the most popular car company in America? ")
while number_of_guesses1 < 3:
number_of_guesses1 += 1
if guess1 == ("Ford"):
break
if guess1 == ("Ford"):
print('You guessed the answer in ' + str(number_of_guesses1) + ' tries!')
else:
guess2 = input("Try again:")
if guess2 == ("Ford"):
print('You guessed the answer in ' + str(number_of_guesses1) + ' tries!')
else:
guess3 = input("Try again:")
if guess3 == ("Ford"):
print('You guessed the answer in ' + str(number_of_guesses1) + ' tries!')
else:
print('You did not guess the answer, The answer was Ford')
guess1b = input("What color do you get when you mix red and brown?")
while number_of_guesses2 < 3:
number_of_guesses2 += 1
if guess1 == ("Maroon"):
break
if guess1b == ("Maroon"):
print('You guessed the answer in ' + str(number_of_guesses1) + ' tries!')
else:
guess2b = input("Try again:")
if guess2b == ("Maroon"):
print('You guessed the answer in ' + str(number_of_guesses1) + ' tries!')
else:
guess3b = input("Try again:")
if guess3b == ("Maroon"):
print('You guessed the answer in ' + str(number_of_guesses1) + ' tries!')
else:
print('You did not guess the answer, The answer was Maroon')
This code kind of works, but only if you get the answer wrong 2 times in a row for every question lol. I also haven't thought of a way to implement a score keeper yet (at the end I want it to say how many points you got out of 3.) The code also is obviously not done. Basically, my questions are: How come when I get the answer wrong once and then get it right on the second try it says that it took 3 tries? And if you get the answer right on the first or second try how can I make it so it ignores the remaining tries you have left? This is the error code for example if I get it right on the second try:
Traceback (most recent call last):
File "main.py", line 20, in <module>
if guess3 == ("Ford"):
NameError: name 'guess3' is not defined
By utilizing the data structures within Python and a couple of functions, you can simplify your code considerably as shown below:
from collections import namedtuple
# Create a tuyple containing the Question, number of allowed tries and the answer
Question = namedtuple("Question", ["quest", 'maxTries', 'ans'])
def askQuestion(quest: str, mxTry: int, ans: str) -> int:
""" Ask the question, process answer, keep track of tries, return score"""
score = mxTry
while score > 0:
resp = input(quest)
if resp.lower() == ans:
print('Yes, you got it')
break
else:
score -= 1
print(f'Sorry {resp} is incorrect, try again')
if score == 0:
print("Too Bad, you didn't get the correct answer.")
print(f"The correct answer is {ans}")
return score
def playGame():
# Create a list of questions defiend using the Question structure defined above
question_list =[Question('What is the most popular car company in America? ' , 3, 'ford'),
Question("What color do you get when you mix red and brown?", 3, 'maroon')]
plyr_score = 0
for q in question_list:
plyr_score += askQuestion(q.quest, q.maxTries, q.ans)
print(f'Your final score is {plyr_score}')
The above approach allows you to extend the question repertoire as well as provide a different number of max tries by question.
simply execute playGame() to run the game
Don't use a different variable to keep track of each guess, instead just use one variable, and continually update it using input(). Then you can check it over and over again, without writing a whole mess of if-else statements. For keeping track of the number correct, you can use a variable, and increment it every time a correct answer is entered.
print("Guessing Game")
player_name = input("Hi! What's your name? ")
score = 0
answer1 = "Ford"
answer2 = "Maroon"
guess = input("What is the most popular car company in America? ")
number_of_guesses = 1
while guess != answer1 and number_of_guesses < 3:
guess = input("Try again: ")
number_of_guesses += 1
if guess == answer1:
print('You guessed the answer in ' + str(number_of_guesses) + ' tries!')
score += 1
else:
print('You did not guess the answer, The answer was Ford')
guess = input("What color do you get when you mix red and brown? ")
number_of_guesses = 1
while guess != answer2 and number_of_guesses < 3:
guess = input("Try again: ")
number_of_guesses += 1
if guess == answer2:
print('You guessed the answer in ' + str(number_of_guesses) + ' tries!')
score += 1
else:
print('You did not guess the answer, The answer was Maroon')
print('You got ' + str(score) + ' out of 2 questions.')

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

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I'm a newbie here so sorry if I accidentally break any rules. Basically I'm a beginner to Python and have made a piece of code for a quiz on TV Show Trivia. I wanted to ask the community here if there are any ways to tidy it up, such as unnecessary repetition etc. Also, I wanted to know if there is a way to make it so that the quiz appears in a pop up window, with a space to type in the answer. Here is the code I have so far:
print("Shall we start?")
input("Press Enter to continue...")
score = 0
Que_1 = input("Who's missing - Rachel, Ross, Chandler, Pheobe?: ")
if Que_1 == "Monica" or "monica":
print("That's right, well done!!")
score = score + 1
else:
print("I'm sorry, that's the wrong answer :( ")
score = score - 1
Que_2 = input("What is the first name of the women Leonard from The Big Bang
Theory ended up marrying?: ")
if Que_2 == "Penny" or "penny":
print("Congratulations, that was correct!!")
score = score + 1
else:
print("Incorrect")
score = score - 1
Que_3 = input("What is the full name of the actor who plays the 10th
Doctor?: ")
if Que_3 == "David Tennant" or "david tennant":
print("Oui")
score = score + 1
else:
("Non")
score = score - 1
Que_4 = input("Which sister died in Charmed?: ")
if Que_4 == "Prue" or "prue":
print("You know it")
score = score + 1
else:
print("You don't know it")
score = score - 1
Que_5 = input("Who is the main character of 13 reasons why(Full Name)?: ")
if Que_5 == "Hannah Baker" or "hannah baker":
print("Correctumondo")
score = score + 1
else:
print("Failumundo")
score = score - 1
Que_6 = input("Complete the name 'Tracy ______': ")
if Que_6 == "Beaker" or "beaker":
print("Perfect")
score = score + 1
else:
print("Not perfect")
score = score - 1
Que_7 = input("Lily, Jas and ______ : ")
if Que_7 == "Martha" or "martha":
print("On the button")
score = score + 1
else:
print("Sucks to be you")
score = score - 1
Que_8 = input("Is Missy from Ackley Bridge straight, lesbian or bisexual?:")
if Que_8 == "Straight" or "straight":
print("Right on")
score = score + 1
else:
print("Way off")
score = score - 1
Que_9 = input("From the 4 o' Clock Club, who is Josh's brother?: ")
if Que_9 == "Nathan" or "nathan":
print("Unmistaken")
score = score + 1
else:
print("Mistaken")
score = score - 1
Que_10 = input("What does Sophie from My Parents Are Aliens have to eat in
order to shapeshift? : ")
if Que_10 == "Ice cream" or "Ice Cream" or "ice cream":
print("Amen to that")
score = score + 1
else:
print("Ughhhh just no")
score = score - 1
if score == 10:
print("10 out of 10. Your a boss at this")
elif 5 <= score < 10:
print("Your score is", score, "pretty good, try to get 10 next time")
elif 1 <= score < 10:
print("Your score is", score, "Better luck next time")
Try this code (I did not include all the questions):
questions = [
"Who's missing - Rachel, Ross, Chandler, Pheobe?: ",
"What is the first name of the women Leonard from The Big Bang Theory ended up marrying?: ",
"What is the full name of the actor who plays the 10th Doctor?: ",
"Which sister died in Charmed?: "
]
answers = [
"monica",
"penny",
"david tennant",
"prue"
]
yes_nos = [
["That's right, well done!!", "I'm sorry, that's the wrong answer :( "],
["Congratulations, that was correct!!", "Incorrect"],
["Oui", "Non"],
["You know it", "You don't know it"]
]
if __name__ == '__main__':
print("Shall we start?")
input("Press Enter to continue...")
score = 0
for i, q in enumerate(questions):
ans = input(q + '\n').lower()
if ans == answers[i]:
print(yes_nos[i][0])
score += 1
else:
print(yes_nos[i][1])
print()
if score == 10:
print("10 out of 10. Your a boss at this")
elif 5 <= score < 10:
print("Your score is", score, "\nPretty good, try to get 10 next time")
elif 1 <= score < 10:
print("Your score is", score, "\nBetter luck next time")
Easygui is great for small dialog boxes:
response = easygui.enterbox("What is your favorite ice cream flavor?")
Which will pop up a window like this.
Hope this helps!
In term of optimization, you can use the method lower()
if Que_1.lower() == "monica":
That will remove the first letter as an upper case
You can also use += 1
print("That's right, well done!!")
score += 1
You will not need to do score = score + 1
And on the first Que_1, you need to set after the else with the score that equals to 0 as it is your first if.
You may need to check dictionaries and if it can help you.
And last, you can use this question to give you some insight about what you can do.

Nest IF needed? in Python

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

Loop in a loop python [closed]

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

Python - Returning variable from function trouble

I'm currently learning Python and am creating a maths quiz.
I have created a function that loops, first creating a random maths sum, asks for the answer and then compares the input to the actual answer; if a question is wrong the player loses a point - vice versa. At the end a score is calculated, this is what I'm trying to return at the end of the function and print in the main.py file where I receive a NameError 'score' is not defined.
I have racked my head on trying to figure this out. Any help / suggestions would be greatly appreciated!
#generateQuestion.py
`def generate(lives, maxNum):
import random
score= 0
questionNumber = 1
while questionNumber <=10:
try:
ops = ['+', '-', '*', '/']
num1 = random.randint(0,(maxNum))
num2 = random.randint(0,10)
operation = random.choice(ops)
question = (str(num1) + operation + str(num2))
print ('Question', questionNumber)
print (question)
maths = eval(str(num1) + operation + str(num2))
answer=float(input("What is the answer? "))
except ValueError:
print ('Please enter a number.')
continue
if answer == maths:
print ('Correct')
score = score + 1
questionNumber = questionNumber + 1
print ('Score:', score)
print ('Lives:', lives)
print('\n')
continue
elif lives == 1:
print ('You died!')
print('\n')
break
else:
print ('Wrong answer. The answer was actually', maths)
lives = lives - 1
questionNumber = questionNumber + 1
print ('Score:', score)
print ('Lives:', lives)
print('\n')
continue
if questionNumber == 0:
print ('All done!')
return score
`
My main file
#main.py
import random
from generateQuestion import generate
#Welcome message and name input.
print ('Welcome, yes! This is maths!')
name = input("What is your name: ")
print("Hello there",name,"!" )
print('\n')
#difficulty prompt
while True:
#if input is not 1, 2 or 3, re-prompts.
try:
difficulty = int (input(' Enter difficulty (1. Easy, 2. Medium, 3. Hard): '))
except ValueError:
print ('Please enter a number between 1 to 3.')
continue
if difficulty < 4:
break
else:
print ('Between 1-3 please.')
#if correct number is inputted (1, 2 or 3).
if difficulty == 1:
print ('You chose Easy')
lives = int(3)
maxNum = int(10)
if difficulty == 2:
print ('You chose Medium')
lives = int(2)
maxNum = int(25)
if difficulty == 3:
print ('You chose Hard')
lives = int(1)
maxNum = int(50)
print ('You have a life count of', lives)
print('\n')
#generateQuestion
print ('Please answer: ')
generate(lives, maxNum)
print (score)
#not printing^^
'
I have tried a different method just using the function files (without the main) and have narrowed it down to the problem being the returning of the score variable, this code is:
def generate(lives, maxNum):
import random
questionNumber = 1
score= 0
lives= 0
maxNum= 10
#evalualates question to find answer (maths = answer)
while questionNumber <=10:
try:
ops = ['+', '-', '*', '/']
num1 = random.randint(0,(maxNum))
num2 = random.randint(0,10)
operation = random.choice(ops)
question = (str(num1) + operation + str(num2))
print ('Question', questionNumber)
print (question)
maths = eval(str(num1) + operation + str(num2))
answer=float(input("What is the answer? "))
except ValueError:
print ('Please enter a number.')
continue
if answer == maths:
print ('Correct')
score = score + 1
questionNumber = questionNumber + 1
print ('Score:', score)
print ('Lives:', lives)
print('\n')
continue
elif lives == 1:
print ('You died!')
print('\n')
break
else:
print ('Wrong answer. The answer was actually', maths)
lives = lives - 1
questionNumber = questionNumber + 1
print ('Score:', score)
print ('Lives:', lives)
print('\n')
continue
if questionNumber == 0:
return score
def scoreCount():
generate(score)
print (score)
scoreCount()
I think the problem is with these last lines in main:
print ('Please answer: ')
generate(lives, maxNum)
print ('score')
You are not receiving the returned value. It should be changed to:
print ('Please answer: ')
score = generate(lives, maxNum) #not generate(lives, maxNum)
print (score) # not print('score')
This will work.
The way it works is not:
def a():
score = 3
return score
def b():
a()
print(score)
(And print('score') will simply print the word 'score'.)
It works like this:
def a():
score = 3
return score
def b():
print(a())

Categories

Resources