Currently in the process of making a True or False quiz. Would anyone be kind enough to help me out with the code? As I am unable to display the amount of questions the user wants to answer. The questions are all arranged in an array however, I am having trouble with it.
For example:
-There are 20 questions and the quiz asks the user for how many questions they want to answer
-User enters 5 questions
-Quiz displays 5 random questions out of the 20 in the list
Thank you in advance!
questionlist = [" "]
answerslist=[" "]
score = 0
questions = 0
while True :
questions = int(input("How many questions do you want to answer today? "))
if questions <= len(questionslist) :
break
print("I only have ", len(questions_list), " in my database")
while len(questionslist) > 0 :
I need help after this please
Using python 2.7:
import random
questions_answers = {"Question1?":"answer1","Question2?":"answer2","Question3?":"answer3","Question4?":"answer4","Question5?":"answer5"}
score = 0
while True :
questions = int(raw_input("How many questions do you want to answer today? "))
if questions == 0:
break
if questions > len(questions_answers) :
print("I only have {} in my database".format(len(questions_answers)))
break
for i in range(1, questions+1):
rand_item = random.choice(questions_answers.keys())
print(rand_item)
answer = raw_input("Enter your answer:")
if answer == questions_answers[rand_item]:
print("Correct")
score+=1
else:
print("Wrong")
print ("Your score is {} out of {}".format(score, questions))
Break this problem into steps, then focus on the code for each separate part.
I would retrieve the user input for how many questions he/she desires and create a loop which retrieves questions from this hash map at random for the requested number of questions! In order to retrieve the questions at random you should use a random generator that will return a number between 0 and 1. You should then multiply this number by the length of the quiz and cast this number to an integer. This will then be the index to your array. You must then store the question number in another array and check to see if this question was already asked the next time a random question was picked.
In psuedo code form:
number_of_questions = retrieve_user_input()
questions_asked_thus_far = [] //empty array
question_number = 1
while (question_number<=number_of_questions):
question_number = int(random_number_generator * quiz_array.length)
if question_number is not in questions_asked_thus_ far
questions_asked_thus_far.append(question_number)
question_number ++
print question_number
Related
i'm a beginner in python and I am coding a multiplicator challenge in terminal. I need to call the function randint in order to ask random questions about multiplication tables. The problem is that in my iterative loop, the number printed is always the same, it generates a random one but it is the same in every loop, that's a big problem for me, here's my code
from random import *
nombreQuestions = int(input("How many questions ? : "))
score = 0
choixTable= int(input("On which number do you want to get asked on ? : "))
multi=(randint(1,10))
for nombreQuestions in range(nombreQuestions):
question=str(choixTable)+" x "+str(multi)+" = "
reponse = int(input(question))
if reponse == choixTable*multi:
print("Well played")
else:
print("Wrong !")
Thank you very much
You only call randint at the start at line 6 where it is set once before you enter the loop
This means that each iteraction uses the same value
To fix this you need to set multi inside the loop (instead of outside)
from random import *
nombreQuestions = int(input("How many questions ? : "))
score = 0
choixTable= int(input("On which number do you want to get asked on ? : "))
for nombreQuestions in range(nombreQuestions):
multi=(randint(1,10)) # multi is now set every loop
question=str(choixTable)+" x "+str(multi)+" = "
reponse = int(input(question))
if reponse == choixTable*multi:
print("Well played")
else:
print("Wrong !")
Add multi=... in the loop so it will execute on every loop Iteration.
from random import *
nombreQuestions = int(input("How many questions ? : "))
score = 0
choixTable= int(input("On which number do you want to get asked on ? : "))
for nombreQuestions in range(nombreQuestions):
multi=(randint(1,10))
question=str(choixTable)+" x "+str(multi)+" = "
reponse = int(input(question))
if reponse == choixTable*multi:
print("Well played")
else:
print("Wrong !")
If you want to generate a random number each time then you need to call the randint() method inside the loop not outside.
Which mean this line multi=(randint(1,10)) should be used inside for loop.
Just like this,
from random import *
nombreQuestions = int(input("How many questions ? : "))
score = 0
choixTable= int(input("On which number do you want to get asked on ? : "))
for nombreQuestions in range(nombreQuestions):
multi = randint(1,10)
question=str(choixTable)+" x "+str(multi)+" = "
reponse = int(input(question))
if reponse == choixTable*multi:
print("Well played")
else:
print("Wrong !")
One thing more, specifying the name of the function in the import statement is more preferred i.e., instead of importing like from random import * use from random import randint
Essentially what im trying to do with this code is a quiz. I've made 2 lists, one with the questions another with the answers. I'm not exactly sure if theres a way to check the index of the randomly chosen question with the index of the where the answer is.
here are the two lists and the most relevant code to what im trying here.
questions = ["What is an example of a topology?: ", "What is the best topology for a large network?: ", "What does the '#' do in python?: ", "What is the '%' of this operator in python?: ","What is the most efficient searching algorithm?: ","What is a LAN?: "]
answers = ["Mesh","Star","Comment","Modulus", "Merge","Local Area Network"]
while play == True:
question = choice(questions)
print(question)
x = (questions.index(question))
y =
answer = input(" ")
As you can probably tell, i got a little confused with comparing the index of the question to the answer, so stopped there and looked for help. Any ideas?
You can choose a random index and then use it to get your question/answer:
index = choice(range(len(questions)))
question = questions[index]
answer = answers[index]
You could also use random.randint (instead of random.choice):
index = randint(0, len(questions) - 1)
random.randrange is another option:
index = randrange(len(questions))
I would approach this first by combining the answers and questions to one nested list for simplicity, But I will post for you both scenarios.
First combine the lists
quiz_list = [[i, x] for i,x in zip(questions,answers)]
Then run your while loop
while True:
question = random.choice(quiz_list)
print(question[0])
user_answer = input("Your Answer:")
if user_answer.lower() == question[1].lower():
print("Congratulations! You got it right")
else:
print("Wrong Answer! Try again")
If you want to run with both lists use the index assuming they will not shuffle or sort for whatever reason.
while True:
question = random.choice(questions)
print(question)
user_answer = input("Your Answer:")
if user_answer.lower() == answers[questions.index(question)].lower():
print("Congratulations! You got it right")
else:
print("Wrong Answer! Try again")
questions.index(question) Returns the index of the question
Note: I convert both the user answer and list answer to lowercase for better comparison.
Just use zip to link questions and answers and form a Question Bank:
...
qbank = list(zip(questions, answers))
while play == True:
question, correct_answer = choice(qbank)
input_answer = input(" ")
...
The qbank obj will be a list of tuples of form (question, answer), so the multiple assignment in the loop is just doing a random choice from this list, and giving you the question answer pair. You can then compare the correct_answer with the input_answer to see if the user got it right.
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.
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
Can someone explain this piece of code to allow me to understand def functions better, i need to know how the code below acts as a counter and adds up the score at the end of the test,:
for i in range(questions): #ask 10 questions
if quiz():
score +=1
this code was for a test I created, if it can be explained thanks alot, also can someone maybe give an alternative version of this piece of code, the whole code is below :
import random
import math
import operator as op
name = input("What is your name? ")
print("Hi {}! Welcome to the Arithmetic quiz...".format(name))
score = 0
questions = 10
def quiz():
x = random.randint(1, 10)
y = random.randint(1, 10)
ops = {'+': op.add,'-': op.sub,'*': op.mul}
keys = list(ops.keys())
opt = random.choice(keys)
operation = ops[opt]
answer = operation(x, y)
print ("What is {} {} {}?".format(x, opt, y)) #prints the question
user_answer= int(input("Your answer: ")) #prompts users answer
if user_answer != answer: #validate users answer to correct answer
print ("Incorrect. The right answer is",answer"")
return False
else:
print("Correct!")
return True
for i in range(questions): #ask 10 questions
if quiz():
score +=1 #counter
print("{}: You got {}/{} questions correct.".format(name, score, questions,))#'question' if (score==1) else 'questions'
thanks <3
i need to know how the code at the top of the page allows a counter to add up all the correct answers in the quiz
Formatting matters in Python, so take care:
for i in range(questions): #ask 10 questions
if quiz():
score +=1
quiz() gets called 10 times, and returns True if a question was answered correctly. In this case, the variable score will be incremented.
The quiz function asks a single question, takes the user's input, checks it and prints a message accordingly. It is defined in the block of code following def quiz(): and it is called (run) with quiz(). It also returns the value True if the answer was correct or False if it was incorrect.
So, every time it is called, its return value is checked and if it's True (if quiz(): is equivalent to if quiz() == True:), the counter score is incremented.
In fact, you can add True (which actually equals 1) and False (==0) to an integer, so your code (note the indenting):
for i in range(questions): #ask 10 questions
if quiz():
score +=1
could be written:
for i in range(questions): #ask 10 questions
score += quiz()
I am having some problems creating a quiz for my son for his revision. It is a quiz which reads a text file, and displays questions in a random order. The quiz stops when he has answered every question twice.
So he can time himself, how would I add a timer in there which starts when the first question is displayed, and prints when he has answered every question correctly twice? I am using python 3.3.
Here is the code so far:
import random
import time
#open the text file
myfile = open("james.txt")
mylines = myfile.read().splitlines()
wrong = 0
#make blank lists
questions = []
answers = []
scores = []
#Seperate the file into Question and answer
for linenumber in range(0, len(mylines), 2):
questions.append(mylines[linenumber])
answers.append(mylines[linenumber+1])
scores.append(0)
#Ask Question
for questionnumber in range(0,len(questions)):
while scores[questionnumber] <2:
questions.append(mylines[linenumber])
questionnumber = random.randint(0,len(questions))
print(questions[questionnumber])
print(scores)
#Generate Possible Answer
possibleanswers = []
possibleanswers.append(answers[questionnumber])
for answerposition in range(1,3):
randomnum = random.randint(0,len(answers)-1)
while answers[randomnum] in possibleanswers:
randomnum = random.randint(0,len(answers)-1)
possibleanswers.append(answers[randomnum])
#Shuffle Answers
random.shuffle(possibleanswers)
for answernumber in range(0,len(possibleanswers)):
print(answernumber+1,possibleanswers[answernumber])
input1 = int(input())
givenanswer = possibleanswers[input1-1]
if givenanswer == answers[questionnumber]:
print("Yes")
scores[questionnumber] = scores[questionnumber]+1
else:
print("No, the answer was",questionnumber)
wrong = wrong+1
questionnumber = random.randint(0,len(questions))
randint is inclusive, so it can return any number up to and including len(questions). If it returns the largest possible number, then you'll get an IndexError. For instance, if questions is three elements long, then questions[3] will be out of range.
Reduce the allowable range of your random numbers:
questionnumber = random.randint(0,len(questions)-1)
Edit: there also appears to be a typo in your #ask question loop, that causes questions to grow larger than answers.
for questionnumber in range(0,len(questions)):
while scores[questionnumber] <2:
questions.append(mylines[linenumber])
# ^^^ this line
This appears to be a copy-paste mistake. It doesn't make much sense to append to questions here, since it should already be fully populated after the #Seperate code. I suggest removing this line.