def ask_questions():
choice = (random.choice(question))
print(choice)
if choice == 0:
print options[0]
answer0 = raw_input(inputs)
if answer0 == answers[0]:
print("correct")
else:
print("incorrect")
elif choice == 1:
print choice
print options[1]
answer1 = raw_input(inputs)
if answer1 == answers[1]:
print("correct")
else:
print("incorrect")
elif choice == 2:
print choice
print options[2]
answer2 = raw_input(inputs)
if answer2 == answers[2]:
print("correct")
else:
print("incorrect")
elif choice == 3:
print choice
print options[3]
answer3 = raw_input(inputs)
if answer3 == answers[3]:
print("correct")
else:
print("incorrect")
elif choice == 4:
print choice
print options[4]
answer4 = raw_input(inputs)
if answer4 == answers[4]:
print("correct")
else:
print("incorrect")
elif choice == 5:
print choice
print options[5]
answer5 = raw_input(inputs)
if answer5 == answers[5]:
print("correct")
else:
print("incorrect")
def main()
date()
quiz_infos()
welcome()
ask_questions()
main()
I Would like to make a random chose of questions from list
i would like to know a way to make a random choice of the questions from the list and if that question is 1: to print the option 1 and my raw_input(inputs) same goes for question 2 3 4 etc
idk why my code dose not actually do that and prints just the question, so if elif functions dose not work!
im new to python(new in coding) so i might be doing something wrong for sure,
ny the way by variable[[[[ inputs = "What do you think the answer is?"]]]]
Thanks in regard!
the code is written in python 2.7 idle
There are simpler ways to do this, but here is your exact code modified for python 3 syntax with appropriate indentation (that works if the lists "question", "options" and "answers" as well as the constant "inputs" are all actually defined and not empty).
def ask_questions():
choice = (random.choice(question))
if choice == 0:
print(choice)
print(options[0])
answer0 = input(inputs)
if answer0 == answers[0]:
print("correct")
else:
print("incorrect")
elif choice == 1:
print(choice)
print(options[1])
answer1 = input(inputs)
if answer1 == answers[1]:
print("correct")
else:
print("incorrect")
etc...
C:\Users\me\Documents>python test.py
0
Question 1
User Input: Answer 1
correct
C:\Users\me\Documents>python test.py
4
Question 5
User Input: Answer 5
correct
As I said above, you have indentation errors in what you pasted in your submission if not also in your code. If your code hangs after printing the question, I suspect your "inputs" may be an empty string.
I personally would make each question:answer in a dictionary
Questions = {"What is your favorite Color?":"Blue","How many cats do I own?": "2"}
then you could return a random selection from the list using the KEYS method
import random
Questions = {"What is your favorite Color?":"Blue","How many cats do I own?": "2"}
random.choice(Questions.keys())
You can look here for dictionary information: Dictionary
and also here for the random module Random
Avoid adding a block of code for each question & answer by iterating the conditional statement through a single randomized list of lists.
Randomize the list of lists using .shuffle() method. The order inside the nested lists won't change, so for example L[0][0] is the question and L[0][1] is the answer of the first element of the randomized list.
Make the input case-insensitive with .lower() method.
Optional: add a count of right and wrong answers.
import random
L = [["Who is Batman's sidekick ?: ", "Robin"], ["Which is the capital of North Ireland ?: ", "Belfast"], ["What do caterpillars turn into ?: ", "Butterflies"]]
random.shuffle(L)
r = 0 # right answers count
w = 0 # wrong answers count
for i in range(0, len(L), 1):
user_input = input(L[i][0])
if user_input.lower() == L[i][1].lower():
print("That's right !")
r = r + 1
else:
print("Wrong answer")
w = w + 1
print(str(r) + " right and " + str(w) + " wrong answers")
Related
print("Welcome to my quiz page!")
playing = input("Do you want to play? ")
if playing.lower() == "yes": #when people answer no here, the quiz should stop but it doesn't. why?
print("Let's play! ")
score = 0
answer = input("What is the capital of Japan? ")
if answer.lower() == "tokyo":
print("Correct!")
score += 1
else:
print("Incorrect!")
answer = input("What is a female Japansese dress called? ")
if answer.lower() == "kimono":
print("Correct!")
score += 1
else:
print("Incorrect!")
answer = input("What are Japanese gang members called? ")
if answer.lower() == "yakuza":
print("Correct!")
score += 1
else:
print("Incorrect!")
print("You've got " + str(score) + " questions correct!")
print("You've got " + str((score / 3) * 100) + "%,")
When I answer "no" it still let me carry on playing the quiz instead of quitting. How can I stop it running when people answer no instead of yes?
The quiz does not stop because you have not included any code to stop the quiz when the user enters "no". To fix this, you can add an else statement after the if statement that checks if the user wants to play. The else statement should contain a break statement to exit the loop.
Here How you can do so:
print("Welcome to my quiz page!")
while True:
playing = input("Do you want to play? ")
if playing.lower() == "yes" or playing.lower() == "y":
print("Let's play! ")
score = 0
answer = input("What is the capital of Japan? ")
if answer.lower() == "tokyo":
print("Correct!")
score += 1
else:
print("Incorrect!")
answer = input("What is a female Japansese dress called? ")
if answer.lower() == "kimono":
print("Correct!")
score += 1
else:
print("Incorrect!")
answer = input("What are Japanese gang members called? ")
if answer.lower() == "yakuza":
print("Correct!")
score += 1
else:
print("Incorrect!")
print("You've got " + str(score) + " questions correct!")
print("You've got " + str((score / 3) * 100) + "%,")
else:
break
You can make this more manageable by constructing a list of questions and answers rather than writing discrete blocks of code for each.
You need to be asking the user if they want to answer questions (or not).
So...
Q_and_A = [
('What is the capital of Japan', 'Tokyo'),
('What is a female Japansese dress called', 'kimono'),
('What are Japanese gang members called', 'yakuza')
]
score = 0
for q, a in Q_and_A:
if input('Would you like to try to answer a question? ').lower() in {'n', 'no'}:
break
if input(f'{q}? ').lower() == a.lower():
print('Correct')
score += 1
else:
print('Incorrect')
print(f'Your total score is {score} out of a possible {len(Q_and_A)}')
Thus if you want to add more questions and answers you just change the list of tuples. The rest of the code doesn't need to be changed
I am making a small quiz and trying to learn python. The quiz takes the first answer then loops all the way to the bottom instead of asking the user the rest of the questions. It will print the first question, then ask for the answer , then it will run throught the rest of the code but it won't actually ask for the input or anything like that.
question_1 = ("ex1")
question_2 = ("ex2")
question_3 = ("ex3")
question_4 = ("ex4")
answer = input ("Please type the letter you think is correct: ")
count = 0
# answers
print (question_1)
print ("A. ")
print ("B. ")
print ("C. ")
print ("D. ")
if answer == "b" or answer == "B":
print ("Correct")
count +=1
else:
print ("Incorrect")
print (question_2)
print ("A. ")
print ("B. ")
print ("C. ")
print ("D. ")
if answer == "a" or answer == "A":
print ("Correct")
count +=1
else:
print ("Incorrect")
print (question_3)
print ("A. ")
print ("B. ")
print ("C. ")
print ("D. ")
if answer == "d" or answer == "D":
print ("Correct")
count +=1
else:
print ("Incorrect")
print (question_4)
print ("A. ")
print ("B. ")
print ("C. ")
print ("D. ")
if answer == "c" or answer == "C":
print ("Correct")
count +=1
else:
print ("Incorrect")
You are only asking for one input and then checking that answer against every question.
You will need to add a new input for every question and then check against that input
e.g.
count = 0
print('Q1')
ans1 = input('A/B/C?')
if ans1.lower() == 'c': # Checks for it as a lowercase so no need to repeat it
print('Correct')
count += 1
else:
print('Incorrect')
print('Q2')
ans2 = input('A/B/C?')
if ans2.lower() == 'b':
print('Correct')
count += 1
else:
print('Incorrect')
You need to have the input() function after each question. An input is asked for at each input, writing it once before all the questions won't work.
By the way, you might want to use lists and a loop to get the same done with less code.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
This is a quiz that I have made that asks users to translate arabic words in to english. When the user reaches the end of the quiz, it asks if the user would like to play again. If the user inputs the word yes then quiz should restart. I need help on making this loop restart when the user says yes.
The code is listed below:
import time
x = 0
print("Welcome to the Arabic Vocabulary Test...")
print("Loading...")
time.sleep(1)
correct = 0
import random
words = ["بىت","مسجد","باب","كتب","قلم","مفت ح","مكتب","سرير","كرسي"]
while x <9:
quest = random.choice(words)
print("What is" , quest, "?" )
words.remove(quest)
ans = input()
x = x+1
if quest == "بىت" and ans == "a house":
print("Correct")
correct = correct + 1
elif quest == "مسجد" and ans == "a mosque":
print("Correct")
correct = correct + 1
elif quest == "باب" and ans == "a door":
print("correct")
correct = correct + 1
elif quest == "كتب" and ans == "a book":
print("correct")
correct = correct + 1
elif quest == "قلم" and ans == "a pen":
print("correct")
correct = correct + 1
elif quest == "مفت ح" and ans == "a key":
print("correct")
correct = correct + 1
elif quest == "مكتب" and ans == "a table":
print("Correct")
correct = correct + 1
elif quest == "سرير" and ans == "a bed":
print("correct")
correct = correct + 1
elif quest == "كرسي" and ans == "a chair":
print("correct")
correct = correct + 1
else:
print("Incorrect")
print("You got" ,correct , "out of 9.")
print("")
print("Check your answers")
print('''a house = "بىت"
a mosque = "مسجد"
a door = "باب"
a book = "كتب"
a pen = "قلم"
a key = "مفت ح"
a table = "مكتب"
a bed = "سرير"
a chair = "كرسي"
''')
again = input("Would you like to play again?: ")
You can put your code in a function and call it inside a while loop:
def quiz():
// the quiz code here
while True:
quiz()
again = input("Would you like to play again?: ")
if again != "yes":
# If the answer is not `yes`, stop the loop
break
By the way, some comment about your quiz code :)
You can use a dictionary to put the words and their answer:
words = {
"بىت" : "a house",
"مسجد" : "a mosque",
...
}
Then, an alternative way to code quiz would be:
def quiz():
# Get the list of words
questions = words.keys()
# Shuffle the questions
random.shuffle(questions)
count = 0
for quest in questions:
ans = input()
# Check the answer in the dict
if ans == words[quest]:
count += 1
print("Correct")
else:
print("Incorrect")
print("You got", count, "out of", len(questions), ".")
print("")
print("Check your answers")
# Print the keys and values of the `words` dictionary
for word, value in words.items():
print(word, "=", value)
Hope it helps!
Include all the quiz code inside the while loop. If the user would like to play again, simply just reset your counter, "x", to 0.
temp_words = words
while x <9:
quest = random.choice(temp_words)
print("What is" , quest, "?" )
temp_words.remove(quest)
ans = input()
x = x+1
if quest == "بىت" and ans == "a house":
print("Correct")
correct = correct + 1
elif quest == "مسجد" and ans == "a mosque":
print("Correct")
correct = correct + 1
elif quest == "باب" and ans == "a door":
print("correct")
correct = correct + 1
elif quest == "كتب" and ans == "a book":
print("correct")
correct = correct + 1
elif quest == "قلم" and ans == "a pen":
print("correct")
correct = correct + 1
elif quest == "مفت ح" and ans == "a key":
print("correct")
correct = correct + 1
elif quest == "مكتب" and ans == "a table":
print("Correct")
correct = correct + 1
elif quest == "سرير" and ans == "a bed":
print("correct")
correct = correct + 1
elif quest == "كرسي" and ans == "a chair":
print("correct")
correct = correct + 1
else:
print("Incorrect")
print("You got" ,correct , "out of 9.")
print("")
print("Check your answers")
print('''a house = "بىت"
a mosque = "مسجد"
a door = "باب"
a book = "كتب"
a pen = "قلم"
a key = "مفت ح"
a table = "مكتب"
a bed = "سرير"
a chair = "كرسي"
''')
again = input("Would you like to play again?: ")
if again is 'yes':
x = 0
temp_words = words
def ask_questions():
choice = (random.choice(question))
print(choice)
if choice == question[0]:
print options[0]
answer0 = raw_input(inputs)
if answer0 == answers[0]:
print("correct")
else:
print("incorrect")
elif choice == question[1]:
print choice
print options[1]
answer1 = raw_input(inputs)
if answer1 == answers[1]:
print("correct")
else:
print("incorrect")
elif choice == question[2]:
print choice
print options[2]
answer2 = raw_input(inputs)
if answer2 == answers[2]:
print("correct")
else:
print("incorrect")
elif choice == question[3]:
print choice
print options[3]
answer3 = raw_input(inputs)
if answer3 == answers[3]:
print("correct")
else:
print("incorrect")
elif choice == question[4]:
print choice
print options[4]
answer4 = raw_input(inputs)
if answer4 == answers[4]:
print("correct")
else:
print("incorrect")
elif choice == question[5]:
print choice
print options[5]
answer5 = raw_input(inputs)
if answer5 == answers[5]:
print("correct")
else:
print("incorrect")
This is my code, is there anyway that i make a loop that keep printing my random choice question (and removes from the list the called one) need it for a quiz, when it calls the question i print options and input than use if elif else statements. Thanks!
When I see the way you're doing this, I don't like how you have 3 separate data structures when a single dict could combine them into one simple structure. Here's an example of what I'd do instead:
import random
QUESTIONS_ANSWERS = {
"What is 21 + 21": ["42", "43", "13", "12"],
"Question 2: enter the correct answer...": ["correct answer", "another answer", "incorrect answer"],
}
def ask_questions():
all_questions = QUESTIONS_ANSWERS.keys()
random.shuffle(all_questions)
for question in all_questions:
options = QUESTIONS_ANSWERS[question]
correct_option = options[0]
random.shuffle(options)
print "Q:", question
print options
answer = raw_input(">>> ")
print "correct" if (answer == correct_option) else "incorrect"
ask_questions()
This way, all the questions and options are in the same dict. The correct answer is, in this case, always the first element of the dict's value (first element of the list). These can be shuffled after you store it in a temp variable for comparison.
def ask_questions():
choice = (random.choice(question))
index = question.index(choice)
print(choice)
print(options[index])
answer = raw_input(inputs)
if answer == answers[index]:
print("correct")
else:
print("incorrect")
del question[index]
del options[index]
For the loop:
while len(questions) > 1:
ask_questions()
That is just a sketch, because you did not post code that could be run link.
Also you are mixing print('sth') (python3) and print 'sth' (python2)
Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 10 years ago.
Improve this question
This code works but is not as efficent as possible. Can you tell me how to make it more efficent? I belevie there is away to not have so many functions but I have forgotten how. The script is a multi choose quiz. I have defined each question as a new function. Is this the best way to do this?
def firstq (): # 1st Question
global q1list,answer1
q1list = ["Wellington","Auckland","Motueka","Masterton"]
q1count = 0
print ("Question 1")
print ("From which of the following Towns is the suburb NEWLANDS located?")
while q1count < 4:
print (q1count," ",q1list[q1count])
q1count = q1count + 1
answer1 = int(input("What number answer do you choose?"))
if answer1 == 0: print ("Correct answer!")
elif answer1 != 0: print ("Sorry! Incorrect Answer. Better luck with the next Question.")
print("Next Question below:")
print(" ")
print(" ")
def secq (): #Second Question
global q2list,answer2 # Makes answer2 and q2list avalible anywhere on the page.
q2list = ["Wellington","Christchurch","Pairoa","Dunedin"] # List of answers to choose from.
q2count = 0 # defines what the q2 count is. SEE BELOW
print ("Question 2")# prints "question 2"
print ("What NZ town is known for L&P?") # Prints the question
while q2count < 4:
print (q2count," ",q2list[q2count]) # Whilst the number of answers (q2list) is below 4 it will print the next answer.
q2count = q2count + 1
answer2 = int(input("What number answer do you choose?")) # asks for answer
if answer2 == 2: print ("Correct answer!") # If answer is correct, prints "Correct answer"
elif answer2 != 2: print ("Sorry! Incorrect Answer. Better luck with the next Question.") # If answer is correct, prints "Sorry! Incorrect Answer. Better luck with the next Question."
print("Next Question below:") # prints "Next Question
# these provide spacing!
print(" ")
print(" ")
def thrq ():
global q3list,answer3
q3list = ["Lewis Carroll","J.K. Rowling","Louis Carroll","Other"]
q3count = 0
print ("Question 3")
print ("Who wrote the book Alice In Wonderland?")
while q3count < 4:
print (q3count," ",q3list[q3count])
q3count = q3count + 1
answer3 = int(input("What number answer do you choose?"))
if answer3 == 0: print ("Correct answer!")
elif answer3 != 0: print ("Sorry! Incorrect Answer. Better luck with the next Question.")
print("Next Question below:")
print(" ")
print(" ")
def fouq ():
global q4list,answer4
q4list = ["WA","DC","WD","WC"]
q4count = 0
print ("Question 4")
print ("What is the abbreviation for Washington?")
while q4count < 4:
print (q4count," ",q4list[q4count])
q4count = q4count + 1
answer4 = int(input("What number answer do you choose?"))
if answer4 == 1: print ("Correct answer!")
elif answer4 != 1: print ("Sorry! Incorrect Answer. Better luck with the next Question.")
print("Next Question below:")
print(" ")
print(" ")
def fivq ():
global q5list,answer5
q5list = ["Yes","No, they're found around New Zealand","No","No, they're found around the UK"]
q5count = 0
print ("Question 5")
print ("Are walruses found in the South Pole?")
while q5count < 4:
print (q5count," ",q5list[q5count])
q5count = q5count + 1
answer5 = int(input("What number answer do you choose?"))
if answer5 == 2: print ("Correct answer!")
elif answer5 != 2: print ("Sorry! Incorrect Answer. Better luck with the next Question.")
print("Next Question below:")
print(" ")
print(" ")
def sixq ():
global q6list,answer6
q6list = ["G.M.","General M's","G Motors","Grand Motors"]
q6count = 0
print ("Question 6")
print ("What is the other name for General Motors?")
while q6count < 4:
print (q6count," ",q6list[q6count])
q6count = q6count + 1
answer6 = int(input("What number answer do you choose?"))
if answer6 == 0: print ("Correct answer!")
elif answer6 != 0: print ("Sorry! Incorrect Answer. Better luck with the next Question.")
print("Next Question below:")
print(" ")
print(" ")
def sevq ():
global q7list,answer7
q7list = ["Greece","USA","Egypt","Italy"]
q7count = 0
print ("Question 7")
print ("Which of the following countries were cats most honored in?")
while q7count < 4:
print (q7count," ",q7list[q7count])
q7count = q7count + 1
answer7 = int(input("What number answer do you choose?"))
if answer7 == 2: print ("Correct answer!")
elif answer7 != 2: print ("Sorry! Incorrect Answer. Better luck with the next Question.")
print("Next Question below:")
print(" ")
print(" ")
def eigq ():
global q8list,answer8
q8list = ["I find","I see","I presume","I am"]
q8count = 0
print ("Question 8")
print ("Complete this phrase-Dr. Livingstone,")
while q8count < 4:
print (q8count," ",q8list[q8count])
q8count = q8count + 1
answer8 = int(input("What number answer do you choose?"))
if answer8 == 2: print ("Correct answer!")
elif answer8 != 2: print ("Sorry! Incorrect Answer. Better luck with the next Question.")
print(" ")
print(" ")
def end():
if answer1 == 0 and answer2 == 2 and answer3 == 0 and answer4 ==1 and answer5 ==2 and answer6 ==0 and answer7 == 2 and answer8 == 2: print("YAY, all questions correct! You have won the 1 million!")
else: print("Sorry you have some incorrect questions! You have not won any money! :(") # If all answers are correct, this will display YAY, all questions correct! You have won the 1 million! If not it will print Sorry you have some incorrect questions! You have not won any money! :(.
def printorder ():
# Defines ther order that it will be printed in
firstq()
secq()
thrq()
fouq()
fivq()
sixq()
sevq()
eigq()
end()
name = l" " # while name is blank it will continue
while name != "quit": #While the name is not quit it will continue. If name is quit it will stop.
print ("The $1,000,000 Quiz! Can you win the 1 Million?")#Prints Welcome Message
name = input("Lets Get Started! What is your name: ")# asks for name
if name == "quit":
break # if the name is quit it will stop if not....
printorder()# ....prints printorder
This is just a pointer.
Instead of
def sixq():
global q6list, answer6
...
create a function
def question(qlist, qanswer):
...
and pass in qlist and qanswer as parameters, much of the code is duplicated and can be eliminated this way. And you also eliminate the use of globals at the same time. You can return whatever value(s) you need to the calling code at the end of this function using return. (note that Python allows you to return more than one value)
Adjust above as needed, ie if you need to supply another parameter etc. Essentially you want to factor out duplicate code into a single function, and provide the necessary parameters for what makes it unique.
Finally, using a single function in place of eight, will making maintaining your code much easier. If you find a problem with your code, or simply want to change something, you'll only have to correct it in one place, rather than in 8 different functions .. this is a major benefit.