Always scared to post here, but I'm stumped and also not sure what I'm doing wrong here, because I don't receive any errors. It appears the arguments in this function just don't work. I guess it's because it appears the conditions aren't met?
question = [f'{name}, what is 1+1', f'{name}, what is 2+2', f'{name}, what is 2+1']
answer = ['2','4','3']
def generateQuestion():
question_show = print(random.choice(question))
answer = input()
if question_show == question[0] and answer == answer[0]:
score = score + 1
print(f"Correct, your score is now {score}")
if question_show == question[1] and answer == answer[1]:
score = score + 1
print(f"Correct, your score is now {score}")
if question_show == question[2] and answer == answer[2]:
score = score + 1
print(f"Correct, your score is now {score}")
If I call that generateQuestion() function is shows the question and allows for input but nothing happens after that.
You are not comparing it correctly answer == answer[0] will never be True. If you read the input in the answer then it is no longer holds the old data.
Store the input in other variable like user_answer and the compare like user_answer == answer[0]
You haven't indented your code that is supposed to be the body of generateQuestion. Try this:
def generateQuestion():
question_show = print(random.choice(question))
answer = input()
Related
I am trying to make a quiz which uses an external text file. The textfile looks like:
Are apples green?TRUE
Are pears green?TRUE
etc etc
I have used x.partition("?")[0]) to split between the question mark so question is to the left and answer to the right.
When I run the program however, the answer doesn't seem to match the csAnswer and I'm not sure why.
I have tried csAnswer.rstrip but it still outputs 'incorrect'.
How can I amend this?
def csQuestions():
for x in questionFile:
print(x.partition("?")[0])
answer = input("Input answer, TRUE OR FALSE: ")
csAnswer = (x.partition("?")[2])
csAnswer.rstrip("\n")
print("cs is ",csAnswer,"answer input is ",answer)
if answer == csAnswer:
print("correct answer")
elif answer !=csAnswer:
print("incorrect")
Try like this (Use .strip() and assign to the variable):
def csQuestions():
for x in questionFile:
que,ans = x.split("?")
print(que)
answer = input("Input answer, TRUE OR FALSE: ")
csAnswer = ans
csAnswer = csAnswer.strip()
print("cs is ",csAnswer,"answer input is ",answer)
if answer == csAnswer:
print("correct answer")
elif answer != csAnswer:
print("incorrect")
To be honest, I wouldn't do it with partition, I would modify the text file so that it is Are apples green?"TRUE so that we can use the split method like this:
for questionandanswer in questionFile:
question = questionandanswer.split('"')[0]
answer = questionandanswer.split('"')[1]
When running your code the code got confused with spaces, etc, now that wouldnt happen anymore. I reccomend using this(its ur code but modified for .split):
questionFile = open(r'C:\Users\incan\OneDrive\Documentos\Code\try.txt', 'r')
def csQuestions():
for x in questionFile:
print(x.split('"')[0])
answer = input("Input answer, TRUE OR FALSE: ")
csAnswer = x.split('"')[1]
csAnswer.rstrip("\n")
print("cs is ",csAnswer,"answer input is ",answer)
if answer == csAnswer:
print("correct answer")
elif answer !=csAnswer:
print("incorrect")
csQuestions()
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.
The assignment was to make a guessing game where the parameter is the answer. At the end if the person gets it right, it prints a congratulatory statement and returns the number of tries it took, if they type in quit, it displays the answer and tries == -1. other than that, it keeps looping until they get the answer correct.
def guessNumber(num):
tries = 1
while tries > 0:
guess = input("What is your guess? ")
if guess == num:
print ("Correct! It took you" + str(tries)+ "tries. ")
return tries
elif guess == "quit":
tries == -1
print ("The correct answer was " + str(num) + ".")
return tries
else:
tries += 1
When i run it, no matter what i put in it just keeps asking me for my guess.
Since you called your variable num so I'm guessing it's a integer, you were checking equality between an integer and a string so it's never True. Try changing the num to str(num) when comparing, so:
def guessNumber(num):
tries = 1
while tries > 0:
guess = input("What is your guess? ")
if guess == str(num):
print ("Correct! It took you {0} tries. ".format(tries))
return tries
elif guess == "quit":
tries = -1
print ("The correct answer was {0}.".format(num))
return tries
else:
tries += 1
Is the code properly indented?
The body of the function you are defining is determined by the level of indentation.
In the example you pastes, as the line right after the def has less indentation, the body of the function is 'empty'.
Indenting code is important in python
Additionally, for assigning one value to a variable you have to use a single '=', so the:
tries == -1
should be
tries = -1
if you want to assign the -1 value to that variable.
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.
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()