So, i have been learning from a video on youtube about basic multiple choice quiz with few possilble answers like a, b, c.
but, if the user enters r or 44 the code just wont count it as a right answer.
I want the code to print the user the question again. Ive tried to write something but now it is moving on to the next question only if the user enters the right question.
def test_run2(questions):
score = 0
for question in questions:
while True:
user_answer = input(question.prompt)
user_answer.lower()
if user_answer == "a" or "b" or "c":
if user_answer == question.answer:
score = score + 1
break
# For each of your questions
running = True
while running:
print("") # Put question in here
if answer in possibleAnswers:
# Check if correct or wrong, etc.
running = False
else:
print("Please provide a valid answer")
# Repeat again for next question
Note that this is just a snippet, you need to add the other sections of your code to it where applicable.
Related
I am new to python and I making a quiz which asks the user if they would like to play on easy, medium, or hard then the code displays the questions depending on what difficulty the user has chosen. I have all the questions and answers in dictionaries (1 dictionary for each difficulty such as a dict for easy questions and answers and a dict for hard questions and answers etc) and I have this part of the code which checks if the users answer is right or wrong. The problem is that the part of the code which checks if the answer is right or wrong can only use one dictionary at a time. The other problem is that I don't know how to make it that if the user picks easy then the code prints out the easy questions from the easy dict.The part if answer.lower() == Question_list_easy[ques]: only allows 1 dict which is why I think the code only allows one dict at a time. I have tried if chooses == "easy": print (Question_list_easy) but it doesn't work. Please help me.
import random
quiz_difficulty = input("Would you like to play on easy, medium, or hard\n").lower()
if quiz_difficulty == "easy":
print (Question_list_easy)
if quiz_difficulty == "medium":
print (Question_list_medium)
if quiz_difficulty == "hard":
print (Question_list_hard)
Question_list_easy = {
"How many days are there in a year?":"365",
"How many hours are there in a day?":"24",
"How many days are there in a week?":"7"
}
Question_list_medium = {
"How many weeks are there in a year?":"52",
"How many years are there in a decade?":"10",
"How many days are there in a fortnight?":"14"
}
Question_list_hard = {
"How many years are there in a millennium?":"1000",
"How many days are there in 2 years?":"730",
"How many years are there in a half a century?":"50"
}
#The part which asks the questions and verifies if the answer the user does is coreect or incorrect. It also randomizes the questions
question = list (Question_list_easy.keys())
#input answer here
while True:
if not question:
break
ques = random.choice(question)
print(ques)
while True:
answer = input('Answer ' )
# if correct, moves onto next question
if answer.lower() == Question_list_easy[ques]:
print("Correct Answer")
break
else:
#if wrong, Asks the same question again
print("Wrong Answer, try again")
question.remove(ques)
Notwithstanding the fact that some of the answers to the questions are wrong, here's a way to achieve your objective with less code. The key feature here is the use of a dictionary where the key/value pairs are the difficulty level mapped to the appropriate dictionary of questions. This obviates the need for if/then/else when choosing the difficulty level and is thus more extensible should you ever want to add more levels of difficulty:-
Question_list_easy = {
"How many days are there in a year?": "365",
"How many hours are there in a day?": "24",
"How many days are there in a week?": "7"
}
Question_list_medium = {
"How many weeks are there in a year?": "52",
"How many years are there in a decade?": "10",
"How many days are there in a fortnight?": "14"
}
Question_list_hard = {
"How many years are there in a millennium?": "365",
"How many days are there in 2 years?": "730",
"How many days are there in a half a century?": "50"
}
qmap = {'easy': Question_list_easy,
'medium': Question_list_medium,
'hard': Question_list_hard}
questions = None
while questions is None:
inp = input('Would you like to play easy, medium, or hard? ')
questions = qmap.get(inp)
while len(questions) > 0:
_i = random.randint(0, len(questions) - 1)
_key = list(questions)[_i]
inp = input(_key+' ')
if inp == questions[_key]:
print('Correct')
questions.pop(_key)
else:
print('Incorrect. Try again')
This looks pretty close, but I think the part you're missing is where you could say:
if quiz_difficulty == "easy":
question_list = Question_list_easy
if quiz_difficulty == "medium":
question_list = Question_list_medium
if quiz_difficulty == "hard":
question_list = Question_list_hard
Then, in your section where you ask the question, you would just use question_list instead of specifically referencing Question_list_easy.
Put the part which asks the questions in a function, and pass the appropriate dict into the function, like this:
def ask_the_questions(q_dict):
#The part which asks the questions ons
question = list (q_dict.keys())
... etc ...
Then call the function with the appropriate dict, for example:
ask_the_question(Question_list_easy)
I have changed your code as follow:
question = ''
question_set = ''
if quiz_difficulty == "easy":
question = list (Question_list_easy.keys())
question_set = Question_list_easy
if quiz_difficulty == "medium":
question = list (Question_list_medium.keys())
question_set = Question_list_medium
if quiz_difficulty == "hard":
question = list (Question_list_hard.keys())
question_set = Question_list_hard
while True:
if not question or not question_set:
break
ques = random.choice(question)
print(ques)
while True:
answer = input('Answer ' )
# if correct, moves onto next question
if answer.lower() == question_set[ques]:
print("Correct Answer")
break
else:
#if wrong, Asks the same question again
print("Wrong Answer, try again")
question.remove(ques)
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 2 years ago.
Improve this question
So I'm fairly new to this whole coding scene and I'm doing some beginner projects to build upon what I've learned.
Essentially what I'm trying to do is get the program to restart back at the top of the loop if the user wants to roll again, or accidently types something else that is not "yes" or "no".
In addition, is there a way to skip a certain line of code, so that way the user isn't asked if they want to roll twice?
Should I be using functions instead?
Couldn't find any info that helped me directly so thought I would ask, any info at all would be helpful, thanks!
import random
useless_varaible1 = 1
useless_varaible2 = 1
# this is the only way I know to set a while loop, I know yikes.
while useless_varaible1 == useless_varaible2:
lets_play = input('Do you wish to roll? Yes or no: ')
if lets_play.lower() == 'yes':
d1 = random.randint(1, 6)
d2 = random.randint(1, 6)
ask = input('Do you wish to roll again? ')
if ask.lower() == 'yes':
# How do I return to give the user another chance?
elif ask.lower() == 'no':
print('Alright, later!')
break
elif lets_play.lower() == 'no':
print('Alright, later!')
break
else:
print('Not any of the options, try again...')
# how do I return to the top to give the user another chance?
(Original code as image)
You've asked a couple of questions in one, but I'll try and answer them with an example. First off, to have an infinite running while loop, you can just set it to True (basically the same as your 1=1 statement, just easier).
Your second question regarding functions is typically yes - if some code needs to be repeated multiple times, it's usually good to extract it to a function.
Your third question regarding skipping a line of code - easiest way to do this is if/else statements, like you've already done. One thing that can be improved, is by using continue; it restarts the loop from the beginning, whereas break breaks out of the loop.
Here's a simple code example for your scenario:
import random
def roll():
print('First roll:', random.randint(1, 6))
print('Second roll:', random.randint(1, 6))
play = input('Do you wish to roll? Yes or no: \n')
while True:
if play.lower() == 'yes':
roll()
play = input('Do you wish to roll again? \n')
elif play.lower() == 'no':
print('Alright, later!')
break
else:
play = input('Not any of the options, try again... Yes or no: \n')
Hey I would do it like this
import random
useless_variable = 1
lets_play = input("Do you want to roll. yes or no: ")
if lets_play.lower() == "yes":
while useless_variable == 1:
useless_variable == 0
d1 = random.randint(1,6)
d2 = random.randint(1,6)
print("You got a: ", d1, "from the first dice")
print("You got a: ", d2, "from the seond dice")
ask = input("Wanna roll again(yes or no):")
if ask.lower() == "yes":
useless_variable = 1
else:
break
If you want to do an infinite loop then while True: Otherwise you can put in your while something like while condition == true and in your answer when is "no" change the condition to false.
I would do it like this
def roll():
if(lets_play.lower() == "yes"):
//Code here
elif lets_play.lower() == "no":
//Code here
else:
print("invalid")
while True:
lets_play = input("Roll?")
if lets_play.lower() == "exit":
break
else:
roll()
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
I am a beginner student in a python coding class. I have the majority of the done and the program itself works, however I need to figure out a way to make the program ask if wants a subtraction or an adding problem, and if the user would like another question. I asked my teacher for assistance and he hasn't gotten back to me, so I'm simply trying to figure out and understand what exactly I need to do.
import random
x = int(input("Please enter an integer: "))
if x < 0:
x = 0
print('Negative changed to zero')
elif x == 0:
print('Zero')
elif x == 1:
print('Single')
else:
print('More')
maximum = 10 ** x;
maximum += 1
firstnum = random.randrange(1,maximum) # return an int from 1 to 100
secondnum = random.randrange(1, maximum)
compsum = firstnum + secondnum # adds the 2 random numbers together
# print (compsum) # print for troubleshooting
print("What is the sum of", firstnum, " +", secondnum, "?") # presents problem to user
added = int(input("Your answer is: ")) # gets user input
if added == compsum: # compares user input to real answer
print("You are correct!!!")
else:
print ("Sorry, you are incorrect")
You'll want to do something like this:
def foo():
print("Doing good work...")
while True:
foo()
if input("Want to do more good work? [y/n] ").strip().lower() == 'n':
break
I've seen this construct (i.e., using a break) used more often than using a sentinel in Python, but either will work. The sentinel version looks like this:
do_good_work = True
while do_good_work:
foo()
do_good_work = input("Want to do more good work? [y/n] ").strip().lower() != 'n'
You'll want to do more error checking than me in your code, too.
Asking users for input is straightforward, you just need to use the python built-in input() function. You then compare the stored answer to some possible outcomes. In your case this would work fine:
print('Would you like to test your adding or subtracting skills?')
user_choice = input('Answer A for adding or S for subtracting: ')
if user_choice.upper() == 'A':
# ask adding question
elif user_choice.upper() == 'S':
# ask substracting question
else:
print('Sorry I did not understand your choice')
For repeating the code While loops are your choice, they will repeatedly execute a statement in them while the starting condition is true.
while True: # Condition is always satisfied code will run forever
# put your program logic here
if input('Would you like another test? [Y/N]').upper() == 'N':
break # Break statement exits the loop
The result of using input() function is always a string. We use a .upper() method on it which converts it to UPPERCASE. If you write it like this, it doesn't matter whether someone will answer N or n the loop will still terminate.
If you want the possibility to have another question asked use a while loop and ask the user for an input. If you want the user to input whether (s)he want an addition or substraction you already used the tools to ask for such an input. Just ask the user for a string.