Ways to simplify my code - Multichoice quiz - python

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()

Related

I came across what is most likely is an indentation error, but I can't figure it out [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 23 days ago.
Improve this question
I'm programming a text adventure game in python, and while fixing some syntax. I got what I think is an indentation error, but I can't seem to be able to fix it. My expected results were for the opening part in the game to run, me enter the main game, and be able to test the inventory system. now my question may be silly, but I'm just starting in python. the specific error is:
File "main.py", line 56
else:
^
SyntaxError: invalid syntax
and my code is:
import random
room = random.randrange(100,400)
door = 0
closets = 0
invintorySlots = 0
# Menu
print(" --------DOORS--------")
answer = input(" < Press enter to continue >")
#intro
print("You enter the hotel, its storming outside")
print("The receptionist, a girl with black hair and brown eyes says hi to you.")
print("Her: Your reserved room is number",room)
print(" ")
answer = input("(A): Thanks! (B): Your cute (C): ...")
if answer == "a":
print("You: Thanks!")
print("Her: No problem!")
elif answer == "b":
print("You: Your cute.")
print("Her: Im not really into dating right now.. Thank you though!")
elif answer == "c":
print("Her: Not much of a talker eh?")
print("You walk to your room")
print("You enter but its not your room. its another room, with another door.")
#main game
door += 1
print("You enter door",door)
if closets > 0:
if random.randrange(1,2) == 2:
print("The lights flicker")
answer = input("(A): Hide in the closet (B): go to the next door (C): look around")
if answer == "a":
print("You hide in a closet")
elif answer == "b":
door += 1
print("You enter door",door)
elif answer == "c":
print("You look around")
if random.randrange(1,10) == 1:
print("You found a lighter!")
#Each item has a number ID
if invintorySlots == 0:
invintorySlots = 1
print("You got a lighter")
else:
print("Would you like to replace your current item with this one?")
answer = input("(A): yes (B): no
if answer == "a":
print("You swapped your item for a lighter")
else:
print("You kept your lighter")
else:
answer = input("(A): Go to the next door (B): say your name (C): ...")
answer = input("(A): yes
Should be
answer = input("(A): yes (B): no")
And your if else should not be tabbed over after.
You have an extra else statement at the end which will never be reached.
Your code should look like this:
import random
room = random.randrange(100,400)
door = 0
closets = 0
invintorySlots = 0
# Menu
print(" --------DOORS--------")
answer = input(" < Press enter to continue >")
#intro
print("You enter the hotel, its storming outside")
print("The receptionist, a girl with black hair and brown eyes says hi to you.")
print("Her: Your reserved room is number",room)
print(" ")
answer = input("(A): Thanks! (B): Your cute (C): ...")
if answer == "a":
print("You: Thanks!")
print("Her: No problem!")
elif answer == "b":
print("You: Your cute.")
print("Her: Im not really into dating right now.. Thank you though!")
elif answer == "c":
print("Her: Not much of a talker eh?")
print("You walk to your room")
print("You enter but its not your room. its another room, with another door.")
#main game
door += 1
print("You enter door",door)
if closets > 0:
if random.randrange(1,2) == 2:
print("The lights flicker")
answer = input("(A): Hide in the closet (B): go to the next door (C): look around")
if answer == "a":
print("You hide in a closet")
elif answer == "b":
door += 1
print("You enter door",door)
elif answer == "c":
print("You look around")
if random.randrange(1,10) == 1:
print("You found a lighter!")
#Each item has a number ID
if invintorySlots == 0:
invintorySlots = 1
print("You got a lighter")
else:
print("Would you like to replace your current item with this one?")
answer = input("(A): yes (B): no")
if answer == "a":
print("You swapped your item for a lighter")
else:
print("You kept your lighter")

Why is my Python code ignoring my if-statement and not quitting when I add the answer "no"?

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

Looping back to a specific line in Python

I am writing a program (for no specific purpose), where I take orders from users, which run the program. At some point, I ask them if they are happy with their decision. They have the option to "say" Yes or No. If their answer is no, I need the program to loop back to a specific point in the code. How can I do that?
Here's the code:
import datetime
import calendar
import time
import colorsys
import math
# Definitions
date = time.strftime("%A")
MenuItems = {0:["Beef steak (0.5 kg) with french fries or basmati rice and mushroom sauce.","Patata con pollo (potato slices with chicken and cooked cream) with cooked vegetables.","Moussaka with green beans, carrots and broccoli \033[92m(vegeterian)\033[37m."],
1:["Beef stroganoff with noodles.","Risotto with pork meat and cooked vegatables.","Gratinated cottage cheese pancakes \033[92m(vegeterian)\033[37m."],
2:["Spaghetti carbonara.","Noodle soup with cut up parsley.","Gnocchi with tomato sauce and sauteed vegetables \033[92m(vegeterian)\033[37m."],
3:["Fried hake with cooked potatoes.","Pizza Palermo (tomato sauce, cheese, ham, pancetta and mushrooms.","Pizza Margherita (tomato sauce, cheese, olives) \033[92m(vegeterian)\033[37m."],
4:["Warm salad with octopus.","Chicken filet with paears in spicy sauce.","Gratinated cheese tortellini with spinach, sour cream and an egg \033[92m(vegeterian)\033[37m."],
5:["Black angus burger with cheddar.","Macaroni with beef filet and tomatoes.","Spaghetti with vegetable sauce \033[92m(vegeterian)\033[37m."]}
DrinkItems = {0:["Soft beverages","Carbonated beverages","Alcoholic beverages","Hot beverages"],
1:["Cedevita (0,5l)","Ice Tea (0,5l)","Water (0,5l) \033[92m(FREE)\033[37m","Apple juice (0,25l)","Orange juice (0,25l)","Strawberry juice (0,25l)","Peach juice (0,25l)","Lemonade (0,5l)","Water with taste (0,5l)"],
2:["Coca Cola (0,25l)","Coca Cola Zero (0,25l)","Coca Cola Zero Lemon (0,25l)","Cockta (0,25l)","Fanta (0,25l)","Schweppes Bitter Lemon (0,25l)","Schweppes Tonic Water (0,25l)","Schweppes Tangerine (0,25l)","Radenska (0,25l)","Sprite (0,25l)","Red Bull (0,25l)"],
3:["Laško beer (0,33l)","Union beer (0,33l)","Malt (0,33l)","Non-alcoholic beer (0,33l)","Corona Extra (0,33l)","Guiness Extra Stout (0,33l)","Sparkling wine (0,10l)","White wine (0,10l)","Red wine (0,10l)","Blueberry Schnapps (0,03l)","Grappa (0,03l)","Stock (0,3l)","Jägermeister (0,03l)","Liquer (0,03l)","Rum (0,03l)","Tequila (0,03l)","Vodka (0,03l)","Gin (0,03l)","Whiskey (0,03l)","Cognac (0,03l)"],
4:["Coffee","Coffee with milk","Cocoa","Hot Chocolate","Irish Coffee","Tea (green, black, herbal, chamomile)"]}
MenuPrices= {0:[6.00, 4.50, 4.50],
1:[5.00, 4.50, 4.00],
2:[5.00, 4.00, 4.50],
3:[4.50, 4.50, 4.50],
4:[4.50, 5.00, 4.00],
5:[5.00, 5.00, 4.00]}
# Introduction of the Bartender
print ("Hello! Welcome to the e-Canteen!")
print ("")
time.sleep(1)
print ("Today is \033[1m" + (date) + "\033[0m.")
time.sleep(1)
# Menus available for current day
todayWeekday = datetime.datetime.today().weekday()
if todayWeekday < 6:
print ("We are serving:")
for x in MenuItems[todayWeekday]:
print(str(MenuItems[todayWeekday].index(x)+1)+".", x)
time.sleep(0.5)
# Canteen is closed on Sunday
else:
print ("Sorry, we're closed.")
exit()
# Ordering the menus
print ("")
time.sleep(1)
menu = int(input("Please choose a menu item by typing in a number from 1 to 3: "))-1
print ("")
if menu < int(3):
print("Great choice! You have selected: "+MenuItems[todayWeekday][menu])
print("The meal price is: {:,.2f}€".format(MenuPrices[todayWeekday][menu]))
# Person chooses higher menu item than 3
else:
print("Sorry, we do not have more than 3 menu items per day. Please choose a menu item from 1 to 3.")
time.sleep (1)
while menu >= 3:
menu = int(input("Please choose a menu by typing in a number from 1 to 3: "))-1
# Person chooses a menu item from 1 to 3
if menu < 3:
print("Great choice! You have selected: "+MenuItems[todayWeekday][menu])
print("The meal price is: {:,.2f}€".format(MenuPrices[todayWeekday][menu]))
# Any additional orders
# Choosing beverage category
print ("------------------------------------------------------------")
print ("")
time.sleep(2)
category = DrinkItems[0]
print("Please choose a type of beverage you would like to order:")
time.sleep(1)
for x in DrinkItems[0]:
print(str(DrinkItems[0].index(x)+1)+".", x)
print("")
time.sleep(0.5)
# Choosing beverage
category = int(input("Enter your number here: "))
print("")
print("You chose \033[1m" +DrinkItems[0][category-1] +"\033[0m. Here is a list:")
for x in DrinkItems[category]:
print(str(DrinkItems[category].index(x)+1)+".", x)
print("")
time.sleep(0.5)
drink = int(input("Please choose a beverage by entering the number in front of your desired beverage: "))-1
# User deciding if she/he is happy with her/his decision
decision = input("\nYou chose " +DrinkItems[category][drink] +". Are you happy with your decision? ").lower()
if decision == 'yes':
additional = input("Great! Would you like to order anything else? ").lower()
if additional == "yes":
what = input("What else would you like to order (menu, drink or both)? ").lower()
if what == "menu":
print("I understand. The program will return you to the menus.")
elif what == "drink":
print("I understand. The program will return you to the drinks.")
elif what == "both":
print("I understand. The program will return you back to the menus (no orders until now will be lost).")
elif additional == "no":
print("Awesome! The program will now summ up your price. Please wait a moment...")
time.sleep(2)
elif decision == "no":
change = input("I'm sorry to hear that. What else would you like to change (menu, drink or both)? ").lower()
if change == "menu":
print("I understand. The program will return you to the menus.")
elif change == "drink":
print("I understand. The program will return you to the drinks.")
elif change == "both":
print("I understand. The program will return you back to the menus.")
# Any additional beverages
# Billing
print(sum(DrinkItems[category][drink]))
# End
I am new relatively new to the coding scene.
Thank you in advance for any answers.
You can wrap your code inside a while loop:
while True:
// your code
// at some point in the code:
happiness = input("Are you happy?")
if happiness == "yes":
break
To go to a specific point in the code, you will have to use this pattern (or something similar) several times.
You can use break statement to stop the(infinite)loop while continue is used to skip something that is what you're looking for here.
So, your code needs to be like this
# User deciding if she/he is happy with her/his decision
while True:
decision = input("\nYou chose "+". Are you happy with your decision? ").lower()
if decision == 'yes':
additional = input("Great! Would you like to order anything else? ").lower()
if additional == "yes":
what = input("What else would you like to order (menu, drink or both)? ").lower()
if what == "menu":
print("I understand. The program will return you to the menus.")
elif what == "drink":
print("I understand. The program will return you to the drinks.")
elif what == "both":
print("I understand. The program will return you back to the menus (no orders until now will be lost).")
break
elif additional == "no":
print("Awesome! The program will now summ up your price. Please wait a moment...")
time.sleep(2)
break
elif decision == "no":
continue

simple python text adventure game errors [closed]

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
I got this sample rpg text adventure game online and im trying to understand the codes so that i can use it as a reference to develop my own text adventure game in the future. However, i am currently facing the error "gold is not defined at line 121 and i suspect is cause by indentation error. Although this is the error im facing so far, i believed that are more mistakes in the codes which i am glad for anyone to point it out.Thanks!
# gold = int(100)
inventory = ["sword", "armor", "potion"]
print("Welcome hero")
name = input("What is your name: ")
print("Hello", name,)
# role playing program
#
# spend 30 points on strenght, health, wisdom, dexterity
# player can spend and take points from any attribute
classic = {"Warrior",
"Archer",
"Mage",
"Healer"}
print("Choose your race from", classic,)
classicChoice = input("What class do you choose: ")
print("You are now a", classicChoice,)
# library contains attribute and points
attributes = {"strenght": int("0"),
"health": "0",
"wisdom": "0",
"dexterity": "0"}
pool = int(30)
choice = None
print("The Making of a Hero !!!")
print(attributes)
print("\nYou have", pool, "points to spend.")
while choice != "0":
# list of choices
print(
"""
Options:
0 - End
1 - Add points to an attribute
2 - remove points from an attribute
3 - Show attributes
"""
)
choice = input("Choose option: ")
if choice == "0":
print("\nYour hero stats are:")
print(attributes)
elif choice == "1":
print("\nADD POINTS TO AN ATTRIBUTE")
print("You have", pool, "points to spend.")
print(
"""
Choose an attribute:
strenght
health
wisdom
dexterity
"""
)
at_choice = input("Your choice: ")
if at_choice.lower() in attributes:
points = int(input("How many points do you want to assign: "))
if points <= pool:
pool -= points
result = int(attributes[at_choice]) + points
attributes[at_choice] = result
print("\nPoints have been added.")
else:
print("\nYou do not have that many points to spend")
else:
print("\nThat attribute does not exist.")
elif choice == "2":
print("\nREMOVE POINTS FROM AN ATTRIBUTE")
print("You have", pool, "points to spend.")
print(
"""
Choose an attribute:
strenght
health
wisdom
dexterity
"""
)
at_choice = input("Your choice: ")
if at_choice.lower() in attributes:
points = int(input("How many points do you want to remove: "))
if points <= int(attributes[at_choice]):
pool += points
result = int(attributes[at_choice]) - points
attributes[at_choice] = result
print("\nPoints have been removed.")
else:
print("\nThere are not that many points in that attribute")
else:
print("\nThat attribute does not exist.")
elif choice == "3":
print("\n", attributes)
print("Pool: ", pool)
else:
print(choice, "is not a valid option.")
While True:
print("Here is your inventory: ", inventory)
print("What do you wish to do?")
print("please input shop, tavern, forest.")
choice = input("Go to the shop, go to the tavern, go to the forest: ")
crossbow = int(50)
spell = int(35)
potion = int(35)
if choice == "shop":
print("Welcome to the shop!")
print("You have", gold,"gold")
buy = input("What would you like to buy? A crossbow, a spell or a potion: ")
if buy == "crossbow":
print("this costs 50 gold")
answer = input("Do you want it: ")
if answer == "yes":
print("Thank you for coming!")
inventory.append("crossbow")
gold = gold - crossbow
print("Your inventory is now:")
print(inventory)
print("Your gold store now is: ", gold)
if answer == "no":
print("Thank you for coming!")
if buy == "spell":
print("this costs 35 gold")
answear2 = input("Do you want it: ")
if answear2 == "yes":
print("Thank you for coming!")
inventory.append("spell")
gold = gold - spell
print("Your inventory is now:")
print(inventory)
if answear2 == "no":
print("Thank you for coming!")
if buy == "potion":
print("this costs 35 gold")
answear3 = input("Do you want it: ")
if answear3 == "yes":
print("Thank you for coming!")
inventory.append("spell")
gold = gold - potion
print("Your inventory is now:")
print(inventory)
if answear3 == "no":
print("Thank you for coming!")
choice = input("Go to the shop, go to the tavern, go to the forest: ")
while choice != "shop" or "tavern" or "forest":
print("Not acepted")
print("What do you wish to do?")
print("please input shop, tavern, forest.")
choice = input("Go to the shop, go to the tavern, go to the forest: ")
if choice == "teavern":
print("You enter the tavern and see a couple of drunken warriors singing, a landlord behind the bar and a dodgy figure sitting at the back of the tavern.")
tavernChoice = input("Would you like to talk to the 'drunken warriors', to the 'inn keeper', approach the 'dodgy figure' or 'exit'")
if tavernChoice == "drunken warriors":
print("You approach the warriors to greet them.")
print("They notice you as you get close and become weary of your presence.")
print("As you arrive at their table one of the warriors throughs a mug of ale at you.")
if dexterity >= 5:
print("You quickly dodge the mug and leave the warriors alone")
else:
print("You are caught off guard and take the mug to the face compleatly soaking you.")
print("The dodgy figure leaves the tavern")
From a quick glance at it. #gold = int(100) is commented out on line 1.
This causes a issue because it doesn't know what gold is. it isn't defined. remove the # before it.

My music quiz just stops [closed]

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.

Categories