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
it doesn't come up with a error, it just doesn't complete its while loop. A question is asked from the list and if the user inputs the correspoinging answer for the answer key, a point is scored
#Music Quiz
import random
print ("Welcome To the Maths Quiz")
name = input("Please enter your name : ")
neigh = input("Please enter your area : ")
#Questions and Answers
randomQuestions = { 1 :"What is Stormzy's new single?",
2 :"What is Lethal Bizzles's new single?",
3 :"Who sang Umberella?",
4 :"Who sang The Hills?",
5 :"Who featured with MNEK to sing Never Foget You?",
6 :"Who is married to Kim Kardashian?",
7 :"What is Kanye's first childs name?",
8 :"What date did Wiz Khalifa and A$AP Rocky perform at the o2?"}
#Defines the questions to the answers
qAns = { "What is Stormzy's new single?" : "WickedSkengMan4",
"What is Lethal Bizzles's new single?" : "Dude",
"Who sung Umberella?" : "Rihanna",
"Who sung The Hills?" : "The Weekend",
"Who featured with MNEK to sing Never Foget You?" : "Zara Larson",
"Who is married to Kim Kardashian?" : "Kanye West",
"What is Kanye's first childs name?" : "North West",
"What date did Wiz Khalifa and A$AP Rocky perform at the o2?" : "17/10/15"}
#askedqs is where the aske questions are stored so they cannot be `reasked`
askedqs = {}
#While statement makes sure it can only happen 5 times
score = 0
x = 0
#While x is less than 5 means thatonly 5 times can it be looped before it doesnt qualify and the code moves on
while x < 5:
#Choses the random question from the array by selecting a number out of the amount of questions
rand1 = random.randint(1,8)
#If the randm number is in the list that stores the asked questions, it is redifined
if rand1 in askedqs:
randomNum = random.randint(1,8)
while rand1 notin askedqs:
rand1 = random.randint(1,8)
print(randomQuestions[rand1])
cQuestion = randomQuestions[rand1]
userAnswer = input("")
if userAnswer.lower() == qAns[rand1].lower():
print("Well done! \n")
score +=1
else:
print("Wrong answer! ", qAns[cQuestion].lower(), "\n")
askedQs[rand1] = cQuestion
rand1 = random.randint(1,8)
x = x + 1
print ("Hello World")
Help on any other errors is also appriceated
I changed almost everything ;)
#Music Quiz
import random
print("Welcome To the Maths Quiz")
name = input("Please enter your name : ")
neigh = input("Please enter your area : ")
# list of Questions and Answers
data = [
("What is Stormzy's new single?", "WickedSkengMan4"),
("What is Lethal Bizzles's new single?", "Dude"),
("Who sung Umberella?", "Rihanna"),
("Who sung The Hills?", "The Weekend"),
("Who featured with MNEK to sing Never Foget You?", "Zara Larson"),
("Who is married to Kim Kardashian?", "Kanye West"),
("What is Kanye's first childs name?", "North West"),
("What date did Wiz Khalifa and A$AP Rocky perform at the o2?", "17/10/15")
]
# number of asked question
asked_number = []
score = 0
# repeat 5 times
for _ in range(5):
rand = random.randint(0, len(data)-1)
while rand in asked_number:
rand = random.randint(0, len(data)-1)
# get question and asnwer
question, answer = data[rand]
answer = answer.lower()
print(question)
user_answer = input("").lower()
if user_answer == answer:
print("Well done! \n")
score +=1
else:
print("Wrong answer! ", answer, "\n")
asked_number.append(rand)
I tried to change as little as possible while getting it working correctly. I also tried to avoid hardcoding the number of questions and redundancy such as having the questions defined twice as it can lead to errors later on:
#Music Quiz
import random
print ("Welcome To the Maths Quiz")
name = input("Please enter your name : ")
neigh = input("Please enter your area : ")
#Questions and Answers
qAns = [ ("What is Stormzy's new single?", "WickedSkengMan4"),
("What is Lethal Bizzles's new single?", "Dude"),
("Who sung Umberella?", "Rihanna"),
("Who sung The Hills?", "The Weekend"),
("Who featured with MNEK to sing Never Foget You?", "Zara Larson"),
("Who is married to Kim Kardashian?", "Kanye West"),
("What is Kanye's first childs name?", "North West"),
("What date did Wiz Khalifa and A$AP Rocky perform at the o2? (DD/MM/YY)", "17/10/15") ]
#askedqs is where the aske questions are stored so they cannot be `reasked`
askedqs = {}
score = 0
#only loop 5 times
for x in range(5):
while True:
#Choses the random question from the array by selecting a number out of the amount of questions
rand = random.randint(0, len(qAns)-1)
if rand not in askedqs:
askedqs[rand] = True
break
question, answer = qAns[rand]
print(question)
userAnswer = input("")
if userAnswer.lower() == answer.lower():
print("Well done! \n")
score +=1
else:
print("Wrong answer! ", answer, "\n")
print("Quiz complete,", name, "of", neigh + ",", "your score was", score)
I also fixed what I think was an error in that you only added questions to the 'asked' list if they were answered incorrectly. That could have been an indentation error, whitespace is very important in Python.
I also think you might want to print something better at the end, and use the name and neighbourhood that you asked the user to provide.
Related
You have to build a dictionary (Or any other container of your choice) which contains multiple True/false type quiz questions.
Every participant/user will attempt 5 rounds and in each round random quiz questions will be displayed to the user/participant.
If the participant answers the quiz question correct, then congratulate him and add the scores.
At the end display the details and score of the participant.
from random import sample
Questions = ['Russia has a larger surface area than Pluto.','There are as many stars in space than there are grains of sand on every beach in the world.',
'For every human on Earth there are 1.6 million ants.','On Jupiter and Saturn it rains diamonds.', 'Scotland’s national animal is the phoenix.',
'A banana is a berry.',
'An octopus has three hearts.',
'There are 10 times more bacteria in your body than actual body cells.',
'Rhode Island is the closest US state to Africa.',
'Shakespeare made up the name “Sarah” for his play Merchant of Venice.',
'Python is a case sensitive language','Python is a interpreted language','Python is a machine language','Python runs on the chrome browser',
'Python is developed by Guido van Rossum', 'Secondary storage, similar to main memory, also stores programs and data',"Each computer has its own machine language which is made of streams of 0's and 1's",
'Symbolic languages use mnemonics to represent the various machine language instructions',
'Only the machine and symbolic languages can be understood by computer hardware',
'One benefit to the use of symbolic languages is improved programming efficiency compared to a machine language',
'High level languages are portable to many different computers',
'the process of converting a high-level language to machine language is known as compilations',
'The software used to write programs is known as a text editor',
'A source file contains code written in a programming language that is to be sent to the compiler',
'One purpose of preprocessor commands is to tell the preprocessor to make substitutions in code',
]
Answers = ['True','False','True','True','False','True','True','True','False','True','True','True','False','False','True','True','True','True','True','True','True','True',
'True','True','True']
name=input("enter your name: ")
print("Hello",name,"welcome to the quiz world")
print("Answer the following questions in true and false format")
print(" ___________________ "+"let's start"+" ___________________")
print(" ")
num_right = 0
score1=0
key = list(zip(Questions, Answers))
s = sample(key, 5)
for i in s:
print(i[0])
user_answer = input('Your answer(true or false): ')
if user_answer.lower() == i[1].lower():
print('Correct!!!')
num_right += 1
score1+=1
else:
print('Not Correct')
print('{}/5 Questions Correct'.format(num_right))
print(" ")
print(" score: ",score1)
print(" ")
print(" ")
print("welcome to the second round")
print(" ")
num_right = 0
score2=0
key = list(zip(Questions, Answers))
s = sample(key, 5)
for i in s:
print(i[0])
user_answer = input('Your answer: ')
if user_answer.lower() == i[1].lower():
print('Correct!!!')
num_right += 1
score2+=1
else:
print('Not Correct')
print('{}/5 Questions Correct'.format(num_right))
print(" ")
print("score: ",score2)
#3 round
print(" ")
print(" ")
print("welcome to the third round")
print(" ")
num_right = 0
score3=0
key = list(zip(Questions, Answers))
s = sample(key, 5)
for i in s:
print(i[0])
user_answer = input('Your answer: ')
if user_answer.lower() == i[1].lower():
print('Correct!!!')
num_right += 1
score3+=1
else:
print('Not Correct')
print('{}/5 Questions Correct'.format(num_right))
print(" ")
print("score: ",score3)
# 4 round
print(" ")
print(" ")
print("welcome to the fourth round")
print(" ")
num_right = 0
score4=0
key = list(zip(Questions, Answers))
s = sample(key, 5)
for i in s:
print(i[0])
user_answer = input('Your answer: ')
if user_answer.lower() == i[1].lower():
print('Correct!!!')
num_right += 1
score4+=1
else:
print('Not Correct')
print('{}/5 Questions Correct'.format(num_right))
print(" ")
print("score: ",score4)
# 5 round
print(" ")
print(" ")
print("welcome to the fifth round")
print(" " )
num_right = 0
score5=0
key = list(zip(Questions, Answers))
s = sample(key, 5)
for i in s:
print(i[0])
user_answer = input('Your answer: ')
if user_answer.lower() == i[1].lower():
print('Correct!!!')
num_right += 1
score5+=1
else:
print('Not Correct')
print('{}/5 Questions Correct'.format(num_right))
print(" --------------------------------------------------------------------- ")
print("score: ",score5)
print(" " )
print(" ")
print("congratulations!!!! you attempted all rounds ")
print("participant name: ",name)
print("final score: ",score1+score2+score3+score4+score5)
but i want that user will be given different questions each time without repetation of questions
I suggest that at the end of each round you remove the 5 questions that have been asked during the round.
for x in s:
key.remove(x)
Of course key should be initialized just once at the beginning.
You'll have to remove all the other occurences of key = list(zip(Questions, Answers)).
This is a multi-choice quiz for kids where they input their age and the algorithm determines what quiz they do (A or B). People less than 8 will do Quiz A but people less than 5 will get a warning message that they are too young to play but can play if they want to. People older than 8 do Quiz B but people who are older than 11 get a warning message stating that they are too old to play but can play if they want to. Note: I don't really care about the repeats/play again right now just want a way to simplify the base structure of the code without using complicated stuff and classes. Thanks for reading!
questions = ["What is 1 + 1",
"Who is the 45th president of the United States?",
"True or False... The Toronto Maple Leafs have won 13 Stanley Cups?",
"What was the last year the Toronto Maple Leafs won the Stanley Cup?",
"True or False... The current Prime Minister of Canada is Pierre Elliot Tredeau?"]
answer_choices = ["a)1\nb)2\nc)3\nd)4\n:",
"a)Barack Obama\nb)Hillary Clinton\nc)Donald Trump\nd)Tom Brady\n:",
":",
"a)1967\nb)1955\nc)1987\nd)1994\n:",
":"]
correct_choices = [{"b", "2"},
{"c", "donald trump"},
{"true", "t"},
{"a", "1967"},
{"false", "f"}]
answers = ["1 + 1 is 2",
"The 45th president is Donald Trump",
"",
"The last time the Toronto Maple Leafs won the Stanley Cup was 1967",
"The current Prime Minster of Canada is Justin Tredeau"]
questions_b = ["Who painted the Mona Lisa",
"Which planet is closest to the sun?",
"How many valves does the heart have?",
"What nut is in the middle of a Ferrero Rocher?",
"How many minutes in a game of rugby league?"]
answer_choices_b = ["a)Vincent Van Gogh\nb)Leonardo da Vinci\nc)Michelangelo\nd)Pablo Picasso\n:",
"a)Mercury\nb)Venus\nc)Mars\nd)Neptune\n:",
"a)Three\nb)One\nc)Five\nd)Four\n:",
"a)Walnut\nb)Hazelnut\nc)Almond\nd)Macadamias\n:",
"a)80 minutes\nb)60 minutes\nc)40 minutes\nd)20 minutes\n:"]
correct_choices_b = [{"b", "Leonardo da Vinci"},
{"a", "Mercury"},
{"d", "Four"},
{"b", "Hazelnut"},
{"a", "80 minutes"}]
answers_b = ["Leonardo da Vinci painted the Mona Lisa",
"Mercury is the planet closest to the sun",
"The heart has four valves",
"A hazelnut is in the middle of a Ferrero Rocher",
"There are 80 minutes in a game of rugby league"]
run = "y"
def quiz_a():
score = 0
for question, choices, correct_choice, answer in zip(questions, answer_choices, correct_choices, answers):
print(question)
user_answer = input(choices).lower()
if user_answer in correct_choice:
print("Correct")
score += 1
else:
print("Incorrect", answer)
print(score, "out of", len(questions), "that is", float(score / len(questions)) * 100, "%")
def quiz_b():
score = 0
for question, choices, correct_choice, answer in zip(questions_b, answer_choices_b, correct_choices_b, answers_b):
print(question)
user_answer = input(choices).lower()
if user_answer in correct_choice:
print("Correct")
score += 1
else:
print("Incorrect", answer)
print(score, "out of", len(questions), "that is", float(score / len(questions)) * 100, "%")
#start of program
#Quiz B is people age 8 to 11
#Quiz A is people less than 8
age = int(input("How old are you?: "))
while run == "y":
if age <= 5:
leave = input("You are too young. Do you still want to play? y/n: ")
if leave == "n":
print("Goodbye")
break
elif leave == "y":
print("Starting now. You will be doing Quiz A")
quiz_a()
else:
break
elif age > 11:
leave = input("You are too old. Do you still want to play? y/n: ")
if leave == "n":
print("Goodbye")
break
elif leave == "y":
print("Starting now. You will be doing Quiz B")
quiz_b()
play_again = input("Do you want to do the other quiz? y/n: ")
if play_again.lower() == "y":
print("Okay starting Quiz A")
quiz_a()
print("Thanks for playing! Goodbye")
break
else:
print("Goodbye")
break
else:
break
elif age <= 5 and age < 8:
print("Starting now. You will be doing Quiz A")
quiz_a()
else:
if age <= 8:
print("Starting now. You will be doing Quiz B")
quiz_b()
You can easily solve this using OOP. As you could see you can have Quiz class which represent a Quiz question, and to hold all questions you can create list of Quiz objects.
class Quiz(object):
"""docstring for Quiz."""
def __init__(self, question, options, answer):
super(Quiz, self).__init__()
self.question = question
self.options = options;
self.answer = answer
def show(self):
print(self.question, self.options, self.answer)
q = Quiz("this is question", ["apple", "banana", "cherry"], 1)
q.show()
This question already has answers here:
How do I terminate a script?
(14 answers)
Closed 2 years ago.
I'm trying to create a game in python, a game of multiple choice called "Who wants to be a millionaire?" and the problem is I want the program to stop executing the second question once the user failed to answer the first one.
print("What is the tallest being in existence?")
input(("If you want to see the choices just press enter. " + name))
print("Is it A, Dinosaur?")
print("B, The one and only, Giraffe")
print("C,The soul of the ocean Whale")
print("or D, None")
print("So what do you believe is the answer ? " + name + " ")
answer_1 = input()
if answer_1 == Q1_answer:
print("Correct! You Have Earned 100,000$ ")
score = +100000
if answer_1 != Q1_answer:
print("Im sorry, You have lost the game.")
print("Which famous inventor was born in 1856?")
print("A Einstein")
print("B, Tesla")
print("C, Napoleon")
print("D, Newton")
answer_2 = input()
if answer_2 == Q2_answer.lower():
print("Correct! It is Tesla Indeed, Your reached 200,000$ ")
score = +100000
else:
print("Sorry, wrong answer. You have lost and earned 0$. ")
I think you can write your program in a better way, currently you cannot easily add questions as you will have to repeat the whole code for each new question. You can store all your questions in one list and then iterate over them. I also did not need sys.exit() because of the way I organized the code. Here is the code:
questions = [
{
"question": "What is the tallest being in existence?",
"options": [
"Is it A, Dinosaur?",
"B, The one and only, Giraffe",
"C,The soul of the ocean Whale",
"or D, None"
],
"correctOption": "a",
"prize": 100_000
},
{
"question": "Which famous inventor was born in 1856?",
"options": [
"A Einstein",
"B, Tesla",
"C, Napoleon",
"D, Newton"
],
"correctOption": "b",
"prize": 100_000
}
]
isGameWon = True
score = 0
for question in questions:
print(question['question'])
input("If you want to see the choices just press enter.")
for option in question['options']:
print(option)
print("So what do you believe is the answer?")
answer = input()
if answer.lower() == question['correctOption']:
score = score + question['prize']
print("Correct! You Have Earned $" + str(score) + ".")
else:
isGameWon = False
break
if (isGameWon):
print("Congrats! You have won the game. You earned $" + str(score) + ".")
else:
print("Sorry, wrong answer. You have lost and earned $0.")
If you want to exit the program completely you need to call the exit method.
import sys
...
if answer_1 != Q1_answer:
print("Im sorry, You have lost the game.")
sys.exit()
You can use exit() to exit your program. I`d print a message telling the user that the program will be exited.
I'm stuck with a problem that asks 5 questions. If any of them has the answer no It should print ALIEN! or else Cool.
This is what I have got so far:
human = input("Are you human? ")
human = input("Are you living on planet Earth? ")
human = input("Do you live on land? ")
human = input("Have you eaten in the last year? ")
human = input("Is 2 + 2 = 4? ")
if human == "yes":
print("Cool")
elif human == "no":
print("ALIEN!")`
You could use any() to check if any of the answers to questions is 'no' and print message accordingly:
human = [input("Are you human? "), input("Are you living on planet Earth? "),
input("Do you live on land? "), input("Have you eaten in the last year? "), input("Is 2 + 2 = 4? ")]
if any(x.lower() == 'no' for x in human):
print('ALIEN!')
else:
print('Cool')
You have the variable human that is changed every time and given a new value using input() Try and make multiple variables instead of just using human.
human = input("Are you human? ")
var1 = input("Are you living on planet Earth? ")
var2 = input("Do you live on land? ")
var3 = input("Have you eaten in the last year? ")
var4 = input("Is 2 + 2 = 4? ")
if(human == "yes"):
print("Cool")
elif(human == "no"):
print("ALIEN!")
If you're not worried about storing the variables and only care if one of the questions comes up as "no" or "n":
x=["human?","on earth?", "on land?","someone who eats food?","sure that 2+2=4?"]
for i in x:
if input("Are you {}".format(i)).lower() in ['no','n']:
print("Alien!")
break
else:
print("Cool")
Just a side note: Here you can see a great case for using a for loop since there is code that is repeated many times. Personally, I would do the following to solve this problem.
Create a list of questions
Iterate through the list of questions
If any answer is no, break and print Alien.
Now for the code:
# Initialize our list
lst = ["Are you human? ", "Are you living on planet Earth? ","Do you live on
land? ","Have you eaten in the last year? ","Is 2 + 2 = 4? "]
#Create a flag for Alien
flag = False
#Iterate through the list
for question in lst:
answer = input(question)
if answer == 'no':
#Print alien
print('Alien')
#Change Flag
flag = True
#Break out of the loop
break
#Check to see if our flag was thrown during the loop
if flag == False:
print('cool')
If you want more help on solving coding challenges like this one, check out this intro to python course: https://exlskills.com/learn-en/courses/learn-python-essentials-for-data-science-intro_to_python/content
I'm asked to produce a trivia game that has 10 questions. Each question should be picked at random. Every four questions Python should ask if the user wants to play again. If the user says "yes" then it continues again, if they say "no" it ends. If the game reaches the point that there are no more questions it should apologize and end the program.
I have two issues. Right now it doesn't seem to be using my playAgain() function. It also is giving me this error, "NameError: global name 'rounds' is not defined" this also comes up for the correct variable. I'm not sure how I can define these outside the mainObject() without modifying the data that they obtain in mainObject().
What should I do?
import random, sys
question1 = "In which US state would you find the zip code 12345?"
question2 = "What never works at night and requires a gnomon to tell the time?"
question3 = "What color is a polar bear's skin?"
question4 = "What is Indiana Jones' first name?"
question5 = "Which is bigger, the state of Florida or England?"
question6 = "How many white stripes are there on the American flag?"
question7 = "How many daily tides are there?"
question8 = "Which country has the longest coastline?"
question9 = "How many of the gifts in the song 'The Twelve Days of Christmas' do not involve birds?"
question10 = "It occurs once in a minute Twice in a week and once in a year what is it?"
answer1 = "New York"
answer2 = "Sundial"
answer3 = "Black"
answer4 = "Henry"
answer5 = "Florida"
answer6 = "Six"
answer7 = "Two"
answer8 = "Canada"
answer9 = "Six"
answer10 = "E"
Questions = [question1, question2, question3,
question4, question5, question6,
question7, question8, question9, question10]
Answers = [answer1, answer2, answer3, answer4,
answer5, answer6, answer7, answer8, answer9,
answer10]
print ("Welcome to the Dynamic Duo's WJ Trivia Game!!")
print ("Press \"enter\" to play.")
input()
last = len(Questions)-1
#rounds = 0
#correct = 0
playagain = " "
def playAgain():
if (rounds == 4 or rounds == 8):
print("Do you want to play another round? (Yes or No)")
playAgain = input()
accept = "Yes"
if PlayAgain.lower() == accept.lower():
mainObject()
else:
sys.quit()
def mainObject():
correct = 0
last = len(Questions)-1
rounds = 0
playagain = "yes"
while (last>=0): #This continually checks to make sure that there is a new question
randomQuestion = random.randint(0, last)
rounds += 1
print ("Round " + str(rounds))
print (Questions[randomQuestion])
userAnswer = input()
questionAsked = (Questions[randomQuestion])
answerRequired = (Answers[randomQuestion])
isitcorrect = False
if answerRequired.lower() == userAnswer.lower():
isitcorrect = True
if isitcorrect == True:
print("Good job! You got the correct answer of " + Answers[randomQuestion])
correct += 1
print("You have " + str(correct) + " points.")
else: print("Too bad, you got it wrong. The correct answer is " + answerRequired)
Questions.remove(questionAsked)
Answers.remove(answerRequired)
last = len(Questions)-1
playAgain()
mainObject()
print("I'm sorry, there are no more trivia questions. Your total score is " + str(correct))
print("Thanks for playing!")
You need to uncomment
rounds = 0 # at the top
and insert
global rounds
in the functions. You are incrementing rounds (local) in main, but rounds in playAgain is undefined.
There are other ways to solve the problem. But this is likely the quickest, and easiest to understand.
The variable rounds is defined in the mainobject() function, and is local to that function. It is not accessible from outside of that function.
One simple fix would be to pass rounds to the playagain() function
thus
def playagain(rounds):
...
def mainobject():
....
playagain(rounds)