Storing the output of a while loop in a variable - python

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

Related

Simon Says challenge activity

I am brand new to coding and working my way through an intro class via Zybooks. This challenge activity is asking me to add one point to user_score for every letter that is a match and break the loop when there is a mismatch. Simon_pattern and user_pattern are both input. This is the code I have so far:
user_score = 0
simon_pattern = input()
user_pattern = input()
for character in simon_pattern:
for input in user_pattern:
if input == character:
user_score += 1
continue
if input != character:
break
print('User score:', user_score)
The code works, but the returned value is wrong. Given simon_pattern ='RRGBRYYBGY'and user_pattern = 'RRGBBRYBGY' the output should be User Score: 4, but my User Score is coming out as 3.
I'm not quite sure what part of my code needs fixing and unfortunately zybooks does not give you any hints. Thanks in advance for the help of this awesome community!!
Hi and welcome to coding! A few notes: Notice how the input() function is used to gather input from the user? Because of this, it is considered a keyword and it is bad practice to name your variables input, because it will overwrite the reference to the function.
Now considering your problem. Instead of a nested loop I would use a single for lop and check the characters at each index within both strings. If they match, add a point. Otherwise, break the loop. You also want to stop the loop if it goes beyond the number of characters in either pattern. One trick for that is to find the minimum length between both patterns. The min function is useful for this.
user_score = 0
simon_pattern = input()
user_pattern = input()
length = min(len(simon_pattern), len(user_pattern))
for i in range(length):
if user_pattern[i] == simon_pattern[i]:
user_score += 1
else:
break
print('User score:', user_score)
This should work :
user_score = 0
simon_pattern = input()
user_pattern = input()
for simon_character, user_character in zip(simon_pattern, user_pattern):
if simon_character == user_character:
user_score += 1
else:
break
print('User score:', user_score)
Be careful not to redefine the Python keywords such as input or print for example. The rest of your program could be modified if you need to reuse these functions

Use a Boolean variable that will act as a switch in the code. If the user still has guesses remaining out of the 3

My program is a guessing game that has three questions the user tey to guess the answers of the 3 questions and they have only three chances if they did make three mistakes the program restart again but if they answer the 3 questions before their 3 chances finished they get their score at the end.
The problem
When the user enters a wrong answer from their first try it automatically goes to the second question.
number_of_guesses = 0
print("Guess the Animal\n")
while number_of_guesses < 3:
number_of_guesses += 1
guess1 = (input("Which bear lives at the North Pole?"))
if number_of_guesses == 3:
break
if guess1 != ("polar bear"):
print("please try again")
else:
print("correct answer")
guess2 = (input("Which is the fastest land animal?"))
if number_of_guesses == 3:
break
if guess2 != ("cheetah"):
print("please try again")
else:
print("correct answer")
I'm trying to make it look like this:
Guess the Animal
Which bear lives at the North Pole? grizzly
Sorry Wrong Answer, try again teddy
Sorry Wrong Answer, try again black
The Correct answer is polar bear
Lob Kei We Ran asa Tie ia ote hn Bie Molo tee)
Correct Answer
Which is the largest animal? elephant
Sorry Wrong Answer, try again blue whale
Correct Answer
Your Score is 2
The following function returns True when the question is answered correctly and False otherwise:
def question(q, a):
for i in range(3):
x = input(f'{q}\n' if i == 0 else 'Wrong answer, try again:\n')
if x == a:
print('Correct answer')
return True
print(f'The correct answer is "{a}"')
return -1
To support multiple questions and print the total score in the end you can try:
questions = {
'Which bear lives at the North Pole?': 'polar bear',
'Which is the fastest land animal?': 'cheetah',
'Which is the largest animal?': 'blue whale',
}
print(f'Your score is {sum(question(q, a) for q, a in questions.items())}')
You need to start again at the top of the while loop when they have given an incorrect answer.
So, you see wherever you have print("please try again").
After this, put down continue in a new line.
This will cause the program to start again at the top of the while loop.

Python Simple Quiz Program - How to solve the question loop

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.

While loop exceeds max number attempts (3) when asking for an answer

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.

My Program is not printing what I want it to print

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.

Categories

Resources