Okay, so i'm trying to keep track of how many questions the player got right, but when I say 'score = +1' it adds nothing to the score. How do I do this? Here is my code:
score = 0
print('This is a 10 question quiz. Please do not use any capitol letters when answeringquestions'
)
print('1. Can elephants jump? (yes or no)')
answer_1 = input()
if answer_1 == 'yes':
print('Wrong! Elephants cannot jump.')
if answer_1 == 'no':
print('Correct! Elephants cannot jump!')
score = +1
print('(true or false) Karoake means \"Empty Orchestra\" In Japanese')
answer_2 = input()
if answer_2 == 'true':
print('Correct! Karoake does in fact mean \"Empty orchestra\" in Japanese')
score = +1
if answer_2 == 'false':
print('Wrong! Karoake does in fact mean \"Empty orchestra\" in Japanese')
print('Solve the math problem: What is the square root of 64?')
answer_3 = input()
if answer_3 == 8:
print('Good job! The square root of 64 is 8!')
score = +1
else:
print('Incorrect! the square root of 64 is 8.')
print(score)
score += 1
or
score = score + 1
Much better detailed answer:
Behaviour of increment and decrement operators in Python
It should be score += 1 you have the operator reversed.
When you say score = +1 you are saying set score to positive one.
What you're writing, score = +1, simply sets the 'score' variable to positive 1 (+1) over and over.
You really want to write, as samrap already said, either:
score += 1 - Sets the variable 'score' to one higher than what it was before
score = score + 1 OR score = (score + 1) - Sets the variable to the previous value plus 1 (The brackets, although not very python-like, help add clarity)
Related
my program keeps returning a score of 0 everytime I run it even with the corrcect answer. Also how would I go about subtractiong points for a wrong answer.
P.S, This is my first time coding anything.
score = 0
print('Math Quiz')
def check_answer(question, answer):
global score
if question == answer:
print("Correct answer!")
score = score + 1
else:
print('Sorry, wrong answer.')
question_1 = input('What is 2 times 2?\n')
check_answer(question_1, 4)
question_2 = input('What is 1 minus 1?\n')
check_answer(question_2, 0)
question_3 = input('What is 4 divided by 2?\n')
check_answer(question_3, 2)
question_4 = input('What is 3 to the third power?\n')
check_answer(question_4, 9)
question_5 = input('What is 3 times 5?\n')
check_answer(question_5, 15)
print(score)
The problem is, that input() returns a string which leads to an incompatible comparison of your data types. You could solve this by creating an integer with the value of your input like this: question_1 = int(input('What is 2 times 2?\n'))
the other problem could be solved by decreasing the score in your else block
input('') returns a string and you are comparing it to a int.
check_anser(int(question_2),0)
or comparte to string version of the numbers
check_anser(question_2,"0")
I was working on a small quiz recently and I have been trying to figure out why it inputs one answer and tries to answer all the questions with one answer I have been trying to figure this out for 2 to 3 days now, sorry if there is a simple solution I am a new coder
TLDR; code takes one answer and tries to solve all questions
import random
score = 0
n = ["What is the capital of Arizona: ", "What thing in Arizona is a part of the 7 natural wonders of the world (ABRIVEATE ANSWER TO THE 1ST LETTER OF EACH WORD): ", "what is the timezone in Arizona: "]
i = 0
answer = input(random.choice(n))
while (i < 3):
if [0]:
if answer == "Phoenix" or "phoenix":
print("Correct")
score += 1
print(score)
else:
print("incorrect")
if [1]:
if answer == "TGC" or "TGC":
print("Correct")
score += 1
print(score)
else:
print("incorrect")
if [2]:
if answer == "GMT":
print("Correct")
score += 1
print(score)
else:
print("incorrect")
i += 1
Compare your original to the below.
Note: I tried to change as little as possible and I'm not saying this is how to do it but to pass back your code with the minimum changed. It assumes you would like to ask all questions (I may have got that incorrect!).
import random
# track score
score = 0
# keep a list of which questions have been asked already
asked = []
# list of questions
n = ["What is the capital of Arizona: ", "What thing in Arizona is a part of the 7 natural wonders of the world (ABBREVIATE ANSWER TO THE 1ST LETTER OF EACH WORD): ", "what is the timezone in Arizona: "]
# loop while there are unasked questions
while len(asked) < len(n):
# set initial choice of 0,1,2 (same as positions in n)
choice = random.randint(0,2)
# if the choice has already been asked loop
while choice in asked:
choice = random.randint(0,2)
# add the valid choice to the asked list so the question in that position doesn't get asked again
asked.append(choice)
# ask the question from the list n, index position 'choice'
answer = input(n[choice])
if choice == 0:
if answer.lower() == "phoenix":
print("Correct")
score += 1
print(score)
else:
print("incorrect")
# note the 'elif' which (for reading at least) makes the code less prone to errors
elif choice == 1:
# note the '.lower()' so you don't need Tgc or TGc or TGC or tgC or ...you get it :o)
if answer.lower() == 'tgc':
print("Correct")
score += 1
print(score)
else:
print("incorrect")
elif choice == 2:
if answer.lower() == "gmt":
print("Correct")
score += 1
print(score)
else:
print("incorrect")
# print the user's score starting with a couple of line returns for separation
print('\n\nYou scored {score} points for 3 questions!'.format(score=score))
Example:
What thing in Arizona is a part of the 7 natural wonders of the world (ABBREVIATE ANSWER TO THE 1ST LETTER OF EACH WORD): TgC
Correct
1
what is the timezone in Arizona: gMt
Correct
2
What is the capital of Arizona: A
incorrect
You scored 2 points for 3 questions!
I have already tried many times to fix this problem, but I can not solve it in any way. I use an index as a variable to move the user to the next question, but after correct and incorrect answers, the index remains at 0.
score = 0
index = 0
num = 0
user_answer = ""
correct = ""
#------------------------------------------------------------------------------
question_list = ["What is this shape? \na. Square \nb. Triangle \nc. Oval \nAnswer: ", "What color is this shape? \na. Blue \nb. Red \nc. Orange \nAnswer: "]
answer_list = ["a", "c"]
def AnswerCheck (num):
global user_answer, correct, index, score
while (correct == "false"):
user_answer = input(question_list[num])
if (user_answer == answer_list[num]):
score += 1
print("Correct!")
print("Score:", score)
print("\n")
else:
print("Incorrect!")
print("Score:", score)
print("\n")
index = index + 1
while index < len(question_list):
correct = "false"
AnswerCheck(index)
So the reason why the index isn't moving is that you are not letting it execute. first things first, you need to define the variables outside of the functions then make a function called main. main will be the driver function that you will be using to execute the rest of the code. the next step is to place the index += 1 outside of the while loop, then and a return call at the end of the function to push the results back to main. finally, you need to stop the while loop that is asking the question, to do this add break. this will stop the while loop from executing if the correct answer is entered.
question_list = ["What is this shape? \na. Square \nb. Triangle \nc. Oval \nAnswer: ", "What color is this shape? \na. Blue \nb. Red \nc. Orange \nAnswer: "]
answer_list = ["a", "c"]
user_answer = ""
correct = "false"
index = 0
score = 0
def AnswerCheck (num):
global index, score, user_answer, correct
while (correct == "false"):
user_answer = input(question_list[num])
if (user_answer == answer_list[num]):
score += 1
print("Correct!")
print("Score:", score)
print("\n")
break
else:
print("Incorrect!")
print("Score:", score)
print("\n")
index = index + 1
return
def main():
while index < len(question_list):
correct = "false"
AnswerCheck(index)
main()
This code ran fine on my side let me know if you have any questions.
You have this condition while (correct == "false"), correct variable has the value "false" from the start, and you don't change correct value anywhere in the body of your loop. Hence you will never exit the loop.
And about index remaining always zero. It's not true. You can print the value of index before user_answer = input(question_list[num]) and you will see that it has changed.
The problem is that you are passing the index as an argument here AnswerCheck(index). Because int is a primitive type in Python the value of the index variable will be copied and stored in the num variable inside your AnswerCheck function.
Because of that, num in AnswerCheck and index from the outside scope are not connected in any way. That means changing index will not change the value of num and vice versa.
And you will never exit AnswerCheck as I mentioned in the beginning, so your num variable will never change, and you stuck with the num being 0.
There are a lot of ways to solve it. The most simple ones are changing your while condition or updating the num variable, depending on the desired results.
Also, consider avoiding using global it's not the best practice and can lead to some difficulties debugging. You can read more reasoning about it.
So I am making a python file that creates a dice game. It holds 5 rounds for the 2 players and accumulates their scores at the end of each round. When the round ends their final scores are printed and the winner declared. I am having trouble when trying to make a bonus roll if the scores are tied, which will repeat until one player wins. I've set a variable player1F and player2F. I have used the if function to print who is the winner depending on who scores higher.
if overallp1==overallp2:
roll=random.randint(1,6)
player1F=(roll)
if player1F>player2F:
print(player1 + ' IS THE WINNER ')
elif player1F<player2F:
print(player2 + ' IS THE WINNER ')
Every time I run the program an error occurs saying that the player1F variable is not defined. Player1F is meant to exclusively be the total for the final round, so just the one score determines the win if there is a tie. However it is saying that it is not defined
If I understand your question, here is a way to accomplish what you want:
if overallp1==overallp2:
player1F = 0
player2F = 0
while player1F == player2F:
player1F=random.randint(1,6)
player2F=random.randint(1,6)
if player1F>player2F:
print(player1 + ' IS THE WINNER ')
elif player1F<player2F:
print(player2 + ' IS THE WINNER ')
Also, the final elif can be just else, since there are no other possibilities at that point.
I'm in school, and since we are rather young students, some of my 'colleagues' do not grasp what case sensitivity is. We are making a quiz in Python. Here is the code:
score = 0 #this defines variable score, and sets it as zero
print("What is the capital of the UK?")
answer = input ()
if answer == "London":
print("Well done")
score = score + 1 #this increases score by one
else:
print("Sorry the answer was London")
print("What is the capital of France?")
answer = input ()
if answer == "Paris":
print("Well done")
score = score + 1 #this increases score by one
else:
print("Sorry the answer was Paris")
print("Your score was ",score)
They are inputting 'london' as an answer instead of 'London' and still getting the answer wrong. Any workaround?
You can use .upper() or .lower()
if answer.lower() == 'london':
You can use string1.lower() on answer and you can then make a variable for London and it string1.lower().
example:
string1 = 'Hello'
string2 = 'hello'
if string1.lower() == string2.lower():
print "The strings are the same (case insensitive)"
else:
print "The strings are not the same (case insensitive)"
You can use .capitalize()
answer = raw_input().capitalize()