I'm learning Python, and I need to make a mini quiz. The questions and answers are in a text file (called textfile.txt), each on its own line. At the end of the quiz, it will tell the user their score out of three.
I can get my quiz to print out the first question, and when I try inputting an answer no matter what I put (correct answer or incorrect answer), it'll tell me it's incorrect.
In the text file I have the following:
whats 1+1
2
whats 2+2
4
whats 3+3
6
And here is what I have in my .py file:
questions = open("textfile.txt", "r")
content = questions.readlines()
userScore = 0
for i in range(1):
print(content[0])
answer = input("What's the answer: ")
if answer == content[1]:
print("Correct")
userScore + 1
else:
print("Incorrect")
print(content[2])
answer = input("What's the answer: ")
if answer == content[3]:
print("Correct")
userScore + 1
else:
print("Incorrect")
print(content[4])
answer = input("What's the answer: ")
if answer == content[5]:
print("Correct")
userScore + 1
else:
print("Incorrect")
questions.close()
print("You're done the quiz, your score is: ")
print(userScore)
How do I make it read the correct answer and keep track of the users score?
First of all, use .strip() to remove the newline characters. The answers comparison might not always work because of them.
To ask every even row you can use the modulo (%) operator to get the remainder of the current line index after dividing it by two.
If the answer is correct we add 1 to the corrent_answer_count variable that we print in the end.
questions = open(r"textfile.txt", "r")
content = [line.strip() for line in questions.readlines()]
questions.close()
corrent_answer_count = 0
for i in range((len(content))):
if i % 2 == 0:
print(content[i])
answer = input("What's the answer: ")
if answer == content[i + 1]:
print("Correct")
corrent_answer_count += 1
else:
print("Incorrect")
print("Correct answer count: " + str(corrent_answer_count))
Related
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 5 years ago.
def QandA():
s_easy = open("Science (Easy).txt","r")
score = 0
for x in range (5):
print(s_easy.readline())
answer = s_easy.readline()
useranswer = input("Enter your answer as an uppercase: ")
if useranswer.isspace()or useranswer.islower():
while useranswer.isspace() or useranswer.islower():
print("You must enter a valid letter.")
useranswer = input("Enter your answer as an uppercase: ")
while useranswer != "A" or useranswer != "B":
print("You must enter a valid letter.")
useranswer = input("Enter your answer as an uppercase: ")
if answer == useranswer:
score = score + 1
else:
score = score
elif answer == useranswer:
score = score + 1
else:
score = score
print(score)
I need the while loop to ask the user to input their answer again if the useranswer is not uppercase, a space or not "A" or "B". I also need the score to increase by increments of 1 with every correct answer and to be printed at the end. I have tried to include the score, but it is just not working for me.
You need to change the or to and:
while useranswer != "A" and useranswer != "B":
#code
This is because you only wnat to prompt them again if the input isn't A and it isn't B.
I am a complete novice with Python and working on a multiple choice quiz that reads questions from a file and keeps a score that then writes to a file.
Everything was working perfectly until I added validation to the answers given by the user. Now when I run the program it says my answers are incorrect!
What have I done?
Version 1 that works
def inputandoutput():
questions_file = open_file("questions.txt", "r")
title = next_line(questions_file)
welcome(title)
score = 0
# get first block
category, question, answers, correct, explanation = next_block(questions_file)
while category:
# ask a question
print(category)
print(question)
for i in range(4):
print("\t", i + 1, "-", answers[i])
# get answer
answer = input("What's your answer?: ")
# check answer
if answer == correct:
print("\nRight!", end=" ")
score += 1
else:
print("\nWrong.", end=" ")
print(explanation)
print("Score:", score, "\n\n")
# get next block
category, question, answers, correct, explanation = next_block(questions_file)
questions_file.close()
version 2 that says I now have the wrong answers
def inputandoutput():
questions_file = open_file("questions.txt", "r")
title = next_line(questions_file)
welcome(title)
score = 0
# get first block
category, question, answers, correct, explanation = next_block(questions_file)
while category:
# ask a question
print(category)
print(question)
for i in range(4):
print("\t", i + 1, "-", answers[i])
# get answer and validate
while True:
try:
answer = int(input("What's your answer?: "))
if answer in range (1,5):
break
except ValueError:
print ("That's not a number")
else:
print ("the number needs to be between 1 and 4, try again ")
# check answer
if answer == correct:
print("\nRight!", end=" ")
score += 1
else:
print("\nWrong.", end=" ")
print(explanation)
print("Score:", score, "\n\n")
# get next block
category, question, answers, correct, explanation = next_block(questions_file)
Help?
In your original version, answer was a string; in your new version, it is an int.
If you change your try body to be:
answer = input("What's your answer?: ")
if int(answer) in range (1,5):
then you can still catch the ValueError but leave answer a string.
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 6 years ago.
I am using the newest python software and I am really stumped on printing a certain line in the code.
name = input("Before we begin, what is your name? ")
print("Cool, nice to meet you "+name+"!")
score = 0
score = int(score)
count = 0
answer1 = "dogs"
answer01 = "dog"
question1 = ""
while question1 != answer1 and count < 2:
count = count + 1
question1 = input("What animal barks? ") #Asks the user a question
if question1.lower()== answer1:
print("Correct! Off to a great start, the right answer is dogs!")
score = score + 1
break
elif question1.lower()== answer01:
print("Correct! Off to a great start, the right answer is dogs!")
score = score + 1
break
elif count == 1:
print("That is wrong",name,"but you can try again. Hint: They like bones. ")
if count == 2 and question1 != answer1:
print("Incorrect again, sorry! The right answer was dogs.")
Please do correct me if that looks wrong, I am new to python. Anyway all I want to do is print the question again without repeating the introduction (start). My actual code is much longer and is an entire quiz and I need to repeat certain sections of code from different parts of the code. Please help! Plus I am sorry if the code didn't print properly when I pasted it into the my post.
So, the problem is that your questions are hardcoded, so they repeat etc. Instead, you could provide a data structure, storing all your questions, wrong ang right answers, which you would pass to some parsing logic. For example:
questions = ['What animal barks?', ...]
answers = [('dogs', 'dog'), ...]
hints = ['They like bones', ...]
def dialog(qst, ans, hnt):
score = 0
for question, answers, hint in zip(qst, ans, hnt):
incorrects = 0
while True:
usr_ans = input(question)
iscorrect = any(usr_ans.strip().casefold() == answ.strip().casefold() for answ in answers)
if incorrects < 5 or not iscorrect:
print('That is wrong, {}, but you can try again. Hint: {}'.format(name, hint))
incorrects += 1
elif incorrects >= 5:
print('Incorrect again, sorry! The right answer was {}.'.format(' or '.join(answers))
break
else:
print('Correct! Off to a great start, the right answer is {}!'.format(usr_ans))
score += 1
break
return score
It may look a bit complicated as you're starting to learn. I recommend not to code complete things, until the point in time, where you'd already known the basics. For a great start, try official Python Tutorial, and I'd recommend Lutz's Learning Python
Sample program in which while loop is illustrated:
answer="0"
while answer!="4":
answer=input("What is 2 + 2?")
if answer!="4":
print("Wrong...Try again.")
else:
print("Yes! 2 + 2 = 4")
Here the loop will execute till the user gives the correct answer, i.e. 4.
I want to add another feature in the above code which prints how many attempts the user took to give the correct answer.
print("You gave correct answer in attempt",answer)
But I am not getting any idea how to do it.
Create a variable which stores the amount of attempts the user has taken:
attempts = 0
while True:
answer = int(raw_input("What is 2 + 2?"))
attempts += 1
if answer == 4:
print("Yes! 2 + 2 = 4")
break
print "Wrong.. try again"
print "It took {0} amount of attempts".format(attempts)
Convert the while-loop into a for-loop:
from itertools import count
for attempts in count(1):
answer = input("What is 2 + 2?")
if answer == "4":
break
print("Wrong...Try again.")
print("Correct in {} attempts!".format(attempts))
Currently working through some tutorials on Python, so if it doesn't work, do excuse my n00b level...
answer=0
attempts = 0
while answer!=4:
answer=input("What is 2 + 2?")
if answer!=4:
print("Wrong...Try again.")
attempts = attempts + 1
else:
print("Yes! 2 + 2 = 4")
print("You gave correct answer in %d attempts" % attempts)
This is my code, why won't it work for me? It asks the questions but misses the if statement that I have created.
print("What is your name?")
name = input("")
import time
time.sleep(1)
print("Hello", name,(",Welcome to my quiz"))
import time
time.sleep(1)
import random
ques = ['What is 2 times 2?', 'What is 10 times 7?', 'What is 6 times 2?']
print(random.choice(ques))
# Please note that these are nested IF statements
if ques == ('What is 2 times 2?'):
print("What is the answer? ")
ans = input("")
if ans == '4':
print("Correct")
else:
print("Incorrect")
elif ques == ('What is 10 times 7?'):
print("What is the answer? ")
ans = input("")
if ans == '70':
print("Correct")
else:
print("Incorrect")
elif ques == ('What is 6 times 2?'):
print("What is the answer? ")
ans = input("")
if ans == '12':
print("Correct")
else:
print("Incorrect")
import time
time.sleep(1)
import random
ques = ['What is 55 take away 20?', 'What is 60 devided by 2?', 'What is 500 take away 200']
print(random.choice(ques))
if ques == ('What is 55 take away 20?'):
print("What is the answer? ")
ans = input("")
if ans == '35':
print("Correct")
else:
print("Incorrect")
elif ques == ('What is 60 devided by 2?'):
print("What is the answer? ")
ans = input("")
if ans == '30':
print("Correct")
else:
print("Incorrect")
elif ques == ('What is 500 take away 200'):
print("What is the answer? ")
ans = input("")
if ans == '300':
print("Correct")
else:
print("Incorrect")
ques is at all times still equal to the full list, not to a single element of the list.
If you want use this method, I suggest doing the following:
posedQuestion = random.choice(ques)
print(posedQuestion)
if posedQuestion == "First question":
elif ...
In addition you only need to do your imports once, so only one line saying import time will do ;)
As well as the key error identified by MrHug, your code has the following problems:
Enormous amounts of unnecessary repetition;
Incorrect use of import;
Enormous amounts of unnecessary repetition;
A frankly bewildering attempt at string formatting; and
Enormous amounts of unnecessary repetition.
Note that the following code does what you are trying to do, but in a much more logical way:
# import once, at the top
import random
# use functions to reduce duplication
def ask_one(questions):
question, answer = random.choice(questions):
print(question)
if input("") == answer:
print("Correct")
else:
print("Incorrect")
# use proper string formatting
print("What is your name? ")
name = input("")
print("Hello {0}, welcome to my quiz".format(name))
# store related information together
ques = [('What is 2 times 2?', '4'),
('What is 10 times 7?', '70'),
('What is 6 times 2?', '12')]
ask_one(ques)
You could go further by storing the minimum information (i.e. the two numbers and the operator) in the list of ques, then formatting the question and calculating the outputs in the code itself.