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.
Related
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))
I'm trying to make a multiple choice quiz using python. It seemed like something simple to make at first but now i'm scratching my head a lot trying to figure out how to do certain things.
I am using two lists; one for the questions and one for the answers. I would like to make it so that a random question is chosen from the questions list, as well as 2 random items from the answers list (wrong answers) and finally the correct answer (which has the same index as the randomly selected question).
I've got as far as selecting a random question and two random wrong answers
My first problem is getting the program to display the correct answer.
The second problem is how to check whether the user enters the correct answer or not.
I would appreciate any feedback for my code. I'm very new to this so go a little easy please!
I hope my stuff is readable (sorry it's a bit long)
thanks in advance
import random
print ("Welcome to your giongo quiz\n")
x=0
while True:
def begin(): # would you like to begin? yes/no... leaves if no
wanna_begin = input("Would you like to begin?: ").lower()
if wanna_begin == ("yes"):
print ("Ok let's go!\n")
get_username()#gets the user name
elif wanna_begin != ("no") and wanna_begin != ("yes"):
print ("I don't understand, please enter yes or no:")
return begin()
elif wanna_begin == ("no"):
print ("Ok seeya!")
break
def get_username(): #get's username, checks whether it's the right length, says hello
username = input("Please choose a username (1-10 caracters):")
if len(username)>10 or len(username)<1:
print("Username too long or too short, try again")
return get_username()
else:
print ("Hello", username, ", let's get started\n\n")
return randomq(questions)
##########
questions = ["waku waku", "goro goro", "kushu", "bukubuku", "wai-wai", "poro", "kipashi", "juru", "pero"]
answers = ["excited", "cat purring", "sneezing", "bubbling", "children playing", "teardrops falling", "crunch", "slurp", "licking"]
score = 0
if len(questions) > 0: #I put this here because if i left it in ONly inside the function, it didnt work...
random_item = random.randint(0, len(questions)-1)
asked_question = questions.pop(random_item)
###########
def randomq(questions):
if len(questions) > 0:
random_item = random.randint(0, len(questions)-1)
asked_question = questions.pop(random_item)
print ("what does this onomatopea correspond to?\n\n%s" % asked_question, ":\n" )
return choices(answers, random_item)
else:
print("You have answered all the questions")
#return final_score
def choices(answers, random_item):
random_item = random.randint(0, len(questions)-1)
a1 = answers.pop(random_item)
a2 = answers.pop(random_item)
possible_ans = [a1, a2, asked_question"""must find way for this to be right answer"""]
random.shuffle(possible_ans)
n = 1
for i in possible_ans:
print (n, "-", i)
n +=1
choice = input("Enter your choice :")
"""return check_answer(asked_question, choice)"""
a = questions.index(asked_question)
b = answers.index(choice)
if a == b:
return True
return False
begin()
You could structure the data in a simpler way, using dictionaries. Each item is a pair of a key and a value, for more info refer to this.
For example your data will look like this (each question is associated with an answer):
data = {'question1': 'answer1', 'question2': 'answer2'}
Then we can loop through this dictionary to print the answers after we randomly choose a question. Here's some sudo code for help:
# Choose a random question
# Print all the answers in the dictionary
for key, value in data.iteritems(): #its data.items() in Python 3.x
print value
# If the choice matches the answer
pop the question from the dictionary and do whatever you want to do
# Else, ask again
For more information about iterating through a dictionary refer to this.
You can use another list(for example correct_answer or such) to record the correct answer for each question. Then instead of using a1 = answers.pop(random_item) to choose a wrong answer, use
while True:
if answer[random.randint(0, len(answers)-1)] != correct_answer[question]:
break
a1 = answers.pop(id)
to avoid choosing the correct answer as an incorrect one.
EDIT
As your correct answer is already in the answers, you should not pop items when choosing some incorrect answers, otherwise it will break the indices.
You can choose two wrong answers and a correct answer like this.
correct = question_index
while True:
wrong1 = random.randint(0, len(answers)-1)
if wrong1 != correct:
break
while True:
wrong2 = random.randint(0, len(answers)-1)
if wrong1 != wrong2 and wrong1 != correct:
break
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
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
okay so im writing a code that randomly generates questions and lets the user answer but my problem is that even if the user gets the answer right it will always print incorrect
print ("what is your username")
name = input () .title()
print (name, "welcome")
import random
score=0
question=0
for i in range(10):
ops = ["+", "-", "*"]
num1 = random.randint (0,10)
num2 = random.randint (0,10)
oparator = random.choice(ops)
Q=(str(num1)+(oparator)+(str(num2)))
print (Q)
guess = input()
guess = int(guess)
if oparator =='+':
answer = (str(num1+num2))
elif oparator =='-':
answer = (str(num1-num2))
else:
oparator =='*'
answer = (str(num1*num2))
if guess == (Q):
print ("correct")
score + 1
else:
print ("incorrect")
I honestly don't understand what is wrong.
any help would be greatly thanked
p.s I know my codes a mess
You need to compare guess with answer.
print ("what is your username")
name = input().title()
print (name, "welcome")
import random
score=0
question=0
for i in range(10):
ops = ["+", "-", "*"]
num1 = random.randint (0,10)
num2 = random.randint (0,10)
oparator = random.choice(ops)
Q=(str(num1)+(oparator)+(str(num2)))
print (Q)
guess = input()
guess = int(guess)
if oparator =='+':
answer = int(str(num1+num2)) # Convert to int
elif oparator =='-':
answer = int(str(num1-num2))
else:
oparator =='*'
answer = int(str(num1*num2))
if guess == answer: # Compare user's answer with actual answer
print ("correct")
score = score + 1 # Update the score
else:
print ("incorrect")
The validation doesnt work. im not sure why, is there a way to validate a string. The questions asked are endless i need 10 questions to be asked
import random
name=(input("Please enter your name"))
print("welcome",name,"the arithmetic is about to start")
question=0
while question<10:
number=random.randint(1,10)
numbers=random.randint(1,10)
arith=random.choice("+" "-" "/")
if arith=="+":
print(number,arith,numbers)
answer=number+numbers
if arith=="-":
print(number,arith,numbers)
answer=number-numbers
if arith=="/":
print(number,arith,numbers)
answer=number/numbers
while True:
try:
usersanswer= int(input())
except ValueError:
print ("That is not a valid answer")
continue
if usersanswer==answer:
print("correct")
break
else:
print("incorrct")
The validation doesnt work. im not sure why, is there a way to validate a string
I've taking silentphoenix's answer and made it somewhat more pythonic and six'ed.
You should almost never use python2's input, because on top of being massive security hole, it sometimes does things that can be...rather unexpected.
import random
import operator # contains the python operators as functions
try:
input = raw_input # rebind raw_input to input, if it exists
# so I can just use input :P
except NameError:
pass
name = input("Hi, what is your name?\n")
print("Hi {} let's get started! Question 1".format(name))
#Get out of the habit of using string concatenation and use string
#formatting whenever possible. Strings are *immutable*;
#concatenation has to produce a lot temporary strings and is *slow*
#str.join and str.format are almost always better ideas.
#Python does not have a switch-case, so emulating one with a dictionary
operator_mapping = {'+': operator.add,
'-': operator.sub,
'*': operator.mul,
#'/': operator.truediv, #hey, division exists.
#But if you want division to actually work, you'll
#have to introduce a fudge factor :P
}
for i in range(10): # If you're just going for 10 iterations, it should be a for loop
# Brevity :P This is a list comprehension
first_number, second_number = [random.randint(1,10) for _ in range(2)]
oper = random.choice(list(operator_mapping))
answer = operator_mapping[oper](first_number, second_number)
while int(input("{} {} {} = ".format(first_number, oper, second_number))) != answer:
#while abs(float(input("{} {} {} = ".format(first_number, oper, second_number)))-answer) < 0.001: if you want truediv.
print('Wrong answer! try again!')
#If I've left the loop, user has given correct (enough) answer
if i <9: # all but last
print('Well done! Now onto question number {0}'.format(i+2))
print('Well done! You are done!')
In the third line, you ask for input. But a name is a string, so you need raw_input. raw_input takes strings, input only takes numerical values.
Python 2.7 getting user input and manipulating as string without quotations
Nowhere in your code do you update the variable questions, which I am guessing is a counter. You have to update that whenever a question is asked, using question += 1.
Finally, your code at the end does not really make sense. Based off the code, it checks for whether or not it is a string, but then compares it to the answer regardless. The if statement needs to be within the try.
The else statement does not match any outer indentation.
Finally, because of the while True: your code will never exit the loop unless the answer is wrong. At the point the entire program terminates. I see what kind of program you are trying to write, but the parameters for random number generation have to be within some kind of a while question <= 10 loop. As of now, only two lines in the program are being affected by that first while loop.
EDIT: I am working on a good example code. Hopefully this answer will help until I can finish it.
EDIT: Here is code that shows how it works within a while loop.
import random
from random import randint
name = raw_input("Hi, what is your name?\n") # Asks for name
print "Hi " +name+ " let's get started!"
score_count = 0
question_count = 0 # creates counter
while question_count <= 10: # Everything MUST BE WITHIN THIS LOOP
# makes numbers and operator
first_number = randint(1,10)
second_number = randint(1,10)
oper = random.choice("+""-""*")
# determines the problem
if oper == "+":
answer = first_number + second_number
print first_number,second_number,oper
elif oper == "-":
answer = first_number - second_number
print first_number,second_number,oper
elif oper == "*":
answer = first_number*second_number
print first_number, second_number, oper
user_answer = int(raw_input("Your answer: "))
if user_answer != answer:
print 'Wrong answer! try again!'
user_answer = int(raw_input('Your answer: '))
if user_answer == answer: # exits the while loop when the correct answer is given
if question_count < 10:
print 'Well done! Now onto question number {0}'.format(question_count+1)
score_count += 1
elif question_count == 10:
print 'Well done! You are done!'
score_count += 1
else:
print 'Something is wrong.'
question_count += 1 # updates the variable
# GOES BACK TO THE BEGINNING UNTIL question_count IS GREATER THAN OR EQUAL TO 10
print "Your score was: {}".format(score_count)
Happy coding! and best of luck!
hi im Nathan and I saw this post I am 5 years to late but I figured if someone on here is knew to python I have a much easier (in my opinion) way to do this in python 3, the code is below:
import random #random module automatically downloaded when you install python
name = input("Please enter your name ")
print("welcome",name,"the arithmetic is about to start")
question=0
while question<10:
number=random.randint(1,10) #creating a random number
numbers=random.randint(1,10) #creating a random number
list = ["+","-","/"] #creating a list (or sometimes called array)
arith=random.choice(list) #getting random operators from list (+,-,/)
question += 1 #basically means add one to question variable each time in loop
if arith=="+":
print(number,arith,numbers)
answer=number+numbers
elif arith=="-":
print(number,arith,numbers)
answer=number-numbers
elif arith=="/":
print(number,arith,numbers)
answer=number/numbers
answer = int(answer)
#from HERE
useranswer = "initialising this variable"
while useranswer == "initialising this variable":
try:
usersanswer= int(input())
if usersanswer==answer:
print("correct")
break
else:
print("incorrect")
except ValueError:
print ("That is not a valid answer")
#to HERE it is input validation this takes a while to explain in just commenting
#but if you dont know what this is then copy this link https://youtu.be/EG69-5U2AfU
#and paste into google for a detailed video !!!!!!
I hope this helps and is a more simplified commented bit of code to help you on your journey to code in python