learner in the Python (with version 2.7.5).
Currently I am working on a simple quiz script that allows the user to re-answer a question, and limit the number of chances the user can answer a question incorrectly.
So a total limit of 5 is set and a message (e.g. "END!") would be displayed to the user when the limit is reached. The limit is shared across all questions.
When I was testing the below-mentioned script, I found several problems.
1) Even the question 1 is wrongly answered for 5 times, question 2 would still be displayed, how could I prevent the next question from appearing if the limit was already reached?
2) I would like to ask where should I insert the code for the end message ("END!") if the limit was reached?
Thanks a lot!
def quiz():
score = 0
counter = 0
print "Please answer the following questions:"
print "Question 1 - ?"
print "a."
print "b."
print "c."
while counter <5:
answer = raw_input("Make your choice:")
if answer == "c":
print("Correct!")
score = score +1
else:
print("Incorrect!")
counter = counter +1
print "Question 2 - ?"
print "a."
print "b."
print "c."
while counter <5:
answer2 = raw_input("Make your choice:")
if answer2 == "a":
print("Correct!")
score = score +1
else:
print("Incorrect!")
counter = counter +1
print
print ("Your score is ") + str(score)
p.s. the code seems a bit off-placed with the copy and paste function. Sorry for causing the inconvenience
You should really refactor this to make it a little less repetitious. So I'd put the question and answer logic into their own function and pass in the question text and correct answer. However, using your code as-is, every time you increment the counter, you need to check if it's > 5 and just use while True for the loop. So for each question:
correct = "a"
while True:
answer = raw_input("Make your choice:")
if answer == correct:
print("Correct!")
score = score +1
break
else:
print("Incorrect!")
counter = counter +1
if counter == 5:
print "END!"
return
break
You are always printing the second question without checking if the limit of wrong answers has been reached. Before printing the second question you could do something like
if counter >= 5:
print "END!"
return
The return statement inside the conditional would terminate the quiz function if the limit has been reached. This needs to be done before printing any question.
Also, you could improve your code using a list of questions with answers and a simple for loop to iterate over all the questions and avoid repeating the same logic every time.
Related
Hi :) I am making a quiz using python, i would like a user to answer 3 questions, and with each correct or incorrect answer, a user_score variable will get update.
What goes wrong is that when question 1 is answer and user moves to question 2, the user_score variable gets reset.
the while loop i use to process the user answers is below:
def check_submitted_answers(answer):
perfect_answers = ['Mohammad','Abraham','Jesus']
all_answers = ['Mohammad','Moses','Jesus','Solomon','Abraham']
user_score = 0
while True:
if answer not in all_answers:
print('Error: Please select one of the choices above')
answer = input('Your answer is: ').capitalize()
else:
if answer in perfect_answers:
print('Correct answer!!You got +1 point')
user_score = user_score + 1
perfect_answers.remove(answer)
break
else:
print('Wrong answer.. You gained 0 points')
user_score = user_score + 0
break
else:
return answer
Whenever a new question comes in , the user_score variable is set to 0 again, i want the old value to be stored instead. thank you =)
yes, as GodWin pointed out, user_score lives only inside the function. Since you never return it, you will never access it from outside. I recommend sth like:
user_score = 0
def check_submitted_answers(answer):
global user_score
perfect_answers = ['Mohammad','Abraham','Jesus']
all_answers = ['Mohammad','Moses','Jesus','Solomon','Abraham']
while True:
if answer not in all_answers:
print('Error: Please select one of the choices above')
answer = input('Your answer is: ').capitalize()
else:
if answer in perfect_answers:
print('Correct answer!!You got +1 point')
user_score = user_score + 1
perfect_answers.remove(answer)
break
else:
print('Wrong answer.. You gained 0 points')
break
else:
return answer
check_submitted_answers("Jesus")
print(user_score) #prints 1
and I suspect you might wanna give some more details next time, because I am also a bit confused, like quamrana is. Hope this helped you tho ;). Let me know if this fixed your problem :D
I'm working on a game for my assignment and I'm stuck on a part where I need to display a message like "Great you are a master at this" IF the user answers correctly 5 times in a row, what I did was something like this :
if correct_guesses == 5 and incorrect_guesses == 0 :
print("""CONGRATULATIONS! You have figured it all out Great work mate!!""")
I've already set up strings that record correct and incorrect guesses for the answers
Right now my code will execute the code and print if the correct guesses equal to 5 but if I get a single guess wrong it will not display, any help?
You need to reset the counter every time the answer is wrong. The structure can look like this:
game_is_running = True # we run the game as long as this is True
counter = 0
while game_is_running:
was_correct = ask_question() # ask_question() is a function that prints the question and check if it was answered correctly. It correct, return True otherwise return False
if was_correct: # if the answer was correct, we increase the counter
counter += 1
else: # if it was false, we reset it to 0 (we need 5 IN A ROW, right?)
counter = 0
if counter == 5: # if we had 5 correct answers in a row, we print and then the game is finished
print("CONGRATULATIONS! You have figured it all out! Great work mate!!")
game_is_running = False
In my program it's supposed to ask the user a question and give them 3 chances to guess the correct answer. But my "while" loop seems to give the user a 4th chance to answer the question and bypassing the "max_attempts" variable.
print('Quiz program!\n')
answer = input('What is the capital of Wisconsin? ')
attempt = 1
max_attempts = 4
while answer != 'Madison':
attempt += 1
print('You got it wrong, please try again.\n')
answer = input('What is the capital of Wisconsin? ')
if attempt == max_attempts:
print('You used the maximum number of attempts, sorry. The correct answer is "Madison"')
break
else:
print(f"Correct! Thanks for playing. It took you {attempt} attempt(s).")
All the above answers are correct, just adding a slightly different variant.
print('Quiz program!\n')
attempt = 1
max_attempts = 4
while attempt < max_attempts:
attempt += 1
answer = input('What is the capital of Wisconsin? ')
if answer == 'Madison':
print("Correct!")
break
else:
print('You got it wrong, please try again.\n')
print("Thanks for playing. It took you %s attempt(s)." %(attempt-1))
You have max_attempts = 4 - change that to 3.
You should check if the counter attempt attempt is equal to max_attempts at the beginning of the loop, before you increment the counter again, and you should set max_attempt to 3 instead:
print('Quiz program!\n')
answer = input('What is the capital of Wisconsin? ')
attempt = 1
max_attempts = 3
while answer != 'Madison':
if attempt == max_attempts:
print('You used the maximum number of attempts, sorry. The correct answer is "Madison"')
break
attempt += 1
print('You got it wrong, please try again.\n')
answer = input('What is the capital of Wisconsin? ')
else:
print(f"Correct! Thanks for playing. It took you {attempt} attempt(s).")
The problem is with your condition. It should be
attempt < max_attempts:
I also tried implementing it in a more readable way
def main():
introduction()
attempt=1
while attemptValid(attempt) and answerIsWrong(askQuestion(), attempt):
attempt += 1
def attemptValid(attempt):
max_attempts=4
if attempt < max_attempts:
return 1
print('You used the maximum number of attempts, sorry. The correct answer is "Madison"')
return 0
def answerIsWrong(answer, attempt):
if answer != 'Madison':
return 1
print(f"Correct! Thanks for playing. It took you {attempt} attempt(s).")
return 0
def introduction():
print('Quiz program!\n')
def askQuestion():
return input('What is the capital of Wisconsin? ')
main()
Surely, by adjusting the variable max_attempts to 2, 3, 4, 5 you will eventually find the right number to give you the correct behaviour. But I believe it is more important to know how to think of this issue. I would suggest to think in terms of loop invariants: Make up a condition that is always true in the loop and enforce it while you write the loop. In this case, let's make the value of attempt and the number of time of input() calls equal, and see if your loop is right:
print('Quiz program!\n')
answer = input('What is the capital of Wisconsin? ')
attempt = 1
max_attempts = 4
So your attempt set to 1 after input(). This part is OK, and satisfied the invariant (even it is before the loop). Then the loop:
while answer != 'Madison':
attempt += 1
print('You got it wrong, please try again.\n')
answer = input('What is the capital of Wisconsin? ')
if attempt == max_attempts:
print('You used the maximum number of attempts, sorry. The correct answer is "Madison"')
break
You increment attempt, then print, then call input(). I will put the attempt line right after input() call to be consistent with the code above but either case, at right before the if statement, we still have value of attempt equals to number of times we called input(). That is why you have this behaviour.
Now on how to change your code: you now knows what is "invariant" in the loop. You have to decide (1) when to do the check of attempt == max_attempts and (2) what is the right value of max_attempts to check. Other people's answer already gave you the solution.
I have just finished this code , added my final print line and now suddenly when I test it , it doesn't print out what I want it to print.
import random
name=input("Welcome to this Arithmetic quiz,please enter your name:")
score = 0
for i in range(10):
number1=random.randint(20,50)
number2=random.randint(1,20)
oper=random.choice('+-*')
correct_answer = eval(str(number1)+oper+str(number2))
answer = (int(input('What is:'+str(number1)+oper+str(number2)+'=')) == correct_answer)
if answer == correct_answer:
print('Correct!')
score +=1
else:
print('Incorrect!')
print("You got",score,"out of 10")
When I ever I give the right answer it still gives me Incorrect leading it to tell me that I got 0/10.
To match the symptoms reported I believe that your code is actually:
import random
name=input("Welcome to this Arithmetic quiz,please enter your name:")
score = 0
for i in range(10):
number1=random.randint(20,50)
number2=random.randint(1,20)
oper=random.choice('+-*')
correct_answer = eval(str(number1)+oper+str(number2))
answer = (int(input('What is:'+str(number1)+oper+str(number2)+'=')) == correct_answer)
if answer == correct_answer:
print('Correct!')
score +=1
else:
print('Incorrect!')
print("You got",score,"out of 10")
Note the indentation of the else statement is aligned with the if, not the for. Given that this line:
answer = (int(input('What is:'+str(number1)+oper+str(number2)+'=')) == correct_answer
assigns a boolean to the variable answer, not the answer that the user entered. You can do 2 things:
remove the == correct_answer part resulting in:
answer = int(input('What is:'+str(number1)+oper+str(number2)+'='))
or
change the if statement to:
if answer:
Here are the problems with your code:
You are incrementing score regardless of whether the answer is correct or not. Increase the indentation of score += 1 so that it lines up with the print that indicates a correct answer.
The else is bound to the for statement. Indent it so that it is bound to the if statement. Indent the print that follows it accordingly.
Your assignment to answer isn't just picking up the answer, but it's comparing it to the expected answer. So it will be True or False. You are then comparing that boolean value to the answer again, so of course the result if False. Change the assignment to:
answer = int(input('What is:'+str(number1)+oper+str(number2)+'='))
Probably the first two items were just posting errors, and the last one is what's preventing your code from working.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
Can someone explain this piece of code to allow me to understand def functions better, i need to know how the code below acts as a counter and adds up the score at the end of the test,:
for i in range(questions): #ask 10 questions
if quiz():
score +=1
this code was for a test I created, if it can be explained thanks alot, also can someone maybe give an alternative version of this piece of code, the whole code is below :
import random
import math
import operator as op
name = input("What is your name? ")
print("Hi {}! Welcome to the Arithmetic quiz...".format(name))
score = 0
questions = 10
def quiz():
x = random.randint(1, 10)
y = random.randint(1, 10)
ops = {'+': op.add,'-': op.sub,'*': op.mul}
keys = list(ops.keys())
opt = random.choice(keys)
operation = ops[opt]
answer = operation(x, y)
print ("What is {} {} {}?".format(x, opt, y)) #prints the question
user_answer= int(input("Your answer: ")) #prompts users answer
if user_answer != answer: #validate users answer to correct answer
print ("Incorrect. The right answer is",answer"")
return False
else:
print("Correct!")
return True
for i in range(questions): #ask 10 questions
if quiz():
score +=1 #counter
print("{}: You got {}/{} questions correct.".format(name, score, questions,))#'question' if (score==1) else 'questions'
thanks <3
i need to know how the code at the top of the page allows a counter to add up all the correct answers in the quiz
Formatting matters in Python, so take care:
for i in range(questions): #ask 10 questions
if quiz():
score +=1
quiz() gets called 10 times, and returns True if a question was answered correctly. In this case, the variable score will be incremented.
The quiz function asks a single question, takes the user's input, checks it and prints a message accordingly. It is defined in the block of code following def quiz(): and it is called (run) with quiz(). It also returns the value True if the answer was correct or False if it was incorrect.
So, every time it is called, its return value is checked and if it's True (if quiz(): is equivalent to if quiz() == True:), the counter score is incremented.
In fact, you can add True (which actually equals 1) and False (==0) to an integer, so your code (note the indenting):
for i in range(questions): #ask 10 questions
if quiz():
score +=1
could be written:
for i in range(questions): #ask 10 questions
score += quiz()