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.
Related
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")
So I have an assessment due tomorrow (it is all finished) and was hoping to add a few more details in.
How would I:
a. Make it so that if you answer the question wrong, you can retry twice
b. if you completely fail, you get shown the answer
How would i do this? thanks
ps. The code lloks retarded, i couldn't get it in
} output = " " score = 0 print('Hello, and welcome to my quiz on Ed Sheeran!') for question_number,question in enumerate(questions): print ("Question",question_number+1)
print (question)
for options in questions[question][:-1]:
print (options)
user_choice = input("Make your choice : ")
if user_choice == questions[question][-1]:
print ("Correct!")
score += 1
print (score)
print (output)
else:
print ("Wrong!")
print (score)
print (output)
print(score)
What I have understood from your query is that you want user to input the option twice before we move to the next question.
Also you want to display the answer if the user has incorrectly answered in both the chances.
I don't know how your questions and answers are stored but you can use the below code as a pseudo code.
The below code should work:
print('Hello, and welcome to my quiz on Ed Sheeran!')
for question_number,question in enumerate(questions):
print ("Question",question_number+1)
print (question)
tmp = 0
for options in questions[question][:-1]:
print (options)
for j in range(2):
user_choice = input("Make your choice : ")
if user_choice == questions[question][-1]:
print ("Correct!")
score += 1
break
else:
print ("Wrong!")
tmp += 1
if tmp == 2:
print ('You got it wrong, Correct answer is: ' output)
print(score)
This is my code and when I enter the programme and try to find the records and get them sorted it shows up list index out of range and when I take the quiz it shows up everything all right but when I enter the CSV file there is an empty row between the input and the beginning of the file I tried deleting the empty rows and the programme works sorts the data and prints it but with the empty rows it just shows up the error mentioned above.
a=True
b=True
c=True
import random #Here i imported a random module
import csv
import operator
score=0 #I made a variable called score and set it to 0
menu1=input("What do you want to do? Take Quiz(t) See Scores(s) ")
if menu1 == ("s"):
menu2=input("How do you want it sorted? alpabetically(a) acording to score highest to lowest(s) or according to average score highest to lowest(a) ")
if menu2 == ("a"):
menu3=input("Which class are you in a b or c ")
if menu3 == ("a"):
sample = open("ClassA.csv","r")
csv1 = csv.reader(sample,delimiter=",")
sort=sorted(csv1,key=operator.itemgetter(0))
for eachline in sort:
print(eachline)
if menu3 == ("b"):
sample = open("ClassB.csv","r")
csv1 = csv.reader(sample,delimiter=",")
sort=sorted(csv1,key=operator.itemgetter(0))
for eachline in sort:
print(eachline)
menu4=input("Do you want to take the quiz now? ")
if menu4 == ("no"):
print("Thank you for Looking At the scores!")
if menu4 == ("yes"):
menu1=input("What do you want to do? Take Quiz(t) See Scores(s) ")
elif menu1 == ("t"):
while a == True: #Opens a loop called a
name=input("What is your name? ") #I asked the user their name here if name == (""):
if name.isdigit() or name == (""): #If the user enters a number or nothing something will happen
print("Incorrect Name") #This is the message that appears when the the name is a number or is nothing is incorrect
else:
a=False #Here i closed a loop
print("Welcome To my quiz " +str(name))#This is the welcoming message
while b == True:
group=input("What Class Are you A,B,C ") #Asks The User their class
if group == ("a") or group == ("b") or group == ("c") or group == ("A") or group == ("B") or group == ("C"):
break
else:
print("No such class!")
def addition(): #Here i define a function called addition
score=0 #Here the score shows score
first_number_a=random.randint(1,10) #The program gets a random number
second_number_a=random.randint(1,10) #The program gets another random number
question1=int(input("What is " +str(first_number_a)+ "+" +str(second_number_a)+ " ")) #Here the program asks the user a question
total_a=(first_number_a+second_number_a) #The answer to the question above
if question1 == total_a: #If answer is equal to the new variable c which is the answer to the question
print("Correct!") #This tells the user they got it correct
score=score+1 #This adds a point to the score
else: # if answer is not the variable
print("Incorrect!") #Here the program will print that the user is incorrect
print(total_a) #Here the program prints the correct answer if they got the question wrong
return score #This keeps the score safe
def multiplication():
score=0
first_number_m=random.randint(1,10)
second_number_m=random.randint(1,10)
question2=int(input("What is " +str(first_number_m)+ "*" +str(second_number_m)+ " "))
total_m=(first_number_m*second_number_m)
if question2 == total_m:
print("Correct!")
score=score+1
else:
print("Incorrect!")
print(total_m)
return score
def subtraction():
score=0
first_number_s=random.randint(1,10)
second_number_s=random.randint(1,10)
question3=int(input("What is " +str(first_number_s)+ "-" +str(second_number_s)+ " "))
total_s=(first_number_s-second_number_s)
if question3 == total_s:
print("Correct!")
score=score+1
else:
print("Incorrect!")
print(total_s)
return score
qw=["a" , "b" , "c"] #List Of Letters that will be randomly selected to then start a function
for i in range(0,10): #Thsi willrepeat the process listed below however many times in this example 10 times
random_Letter=random.choice(qw) #Selets a random letter
if random_Letter == "a": #If the random letter is a
score += addition() #It will use the function addition
elif random_Letter == "b":
score += multiplication()
elif random_Letter == "c":
score += subtraction()
print("your score is " +str(score)+ " Out of 10")#Tells the user their final score
if group == ("a") or group == ("A"): # If users input is as specified
f=open("ClassA.csv","a")#This opens a file
c = csv.writer(f)
c.writerow([name,score]) #Writes To A file
f.close() #This closes the file saving anything the user wrote to it
elif group == ("b") or group == ("B"):
f=open("ClassB.csv","a")
c = csv.writer(f)
c.writerow([name,score])
f.close()
elif group == ("c") or group == ("C"):
f=open("ClassC.csv","a")
f.write(name)
f.write(str(score)+ "\n")
f.close()
total newbie here.
So is there any way to stop a functioning from being executed if certain condition is met?
Here is my source code:
answer = raw_input("2+2 = ")
if answer == "4":
print "Correct"
else:
print "Wrong answer, let's try something easier"
answer = raw_input("1+1 = ")
if answer == "2":
print "Correct!"
else:
print "False"
So basically, if I put 4 on the first question, I will get the "False" comment from the "else" function below. I want to stop that from happening if 4 is input on the first question.
Indentation level is significant in Python. Just indent the second if statement so it's a part of the first else.
answer = raw_input("2+2 = ")
if answer == "4":
print "Correct"
else:
print "Wrong answer, let's try something easier"
answer = raw_input("1+1 = ")
if answer == "2":
print "Correct!"
else:
print "False"
You can place the code inside a function and return as soon any given condition is met:
def func():
answer = raw_input("2+2 = ")
if answer == "4":
print "Correct"
return
else:
print "Wrong answer, let's try something easier"
answer = raw_input("1+1 = ")
if answer == "2":
print "Correct!"
else:
print "False"
output:
>>> func()
2+2 = 4
Correct
>>> func()
2+2 = 3
Wrong answer, let's try something easier
1+1 = 2
Correct!
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.