What's wrong with my Quiz Project made in Python? - python

I tried to make a Quiz Game using Python, inspired by a youtube video, I checked everything and it seems to be right, but it isn't working.
First it can't distinguish a right answer from a wrong answer, it always identifies that you picked the wrong answer, even if you hit the question.
Secondly, it does show the right answers, but it can't show your guesses, and it's followed by some other errors messages.
The code is right below:
(I made some meme questions in the quiz, hope you don't mind haha)
def new_game():
guesses = []
correct_guesses: 0
question_num = 1
for key in questions:
print("\n\n")
print(key)
for item in options[question_num-1]:
print(item)
guess = input("Enter A, B, C or D: ")
guess = guess.upper
guesses.append(guess)
question_num += 1
correct_guesses = check_answer(questions.get(key), guesses)
display_score(correct_guesses, guesses)
def check_answer(answer, guess):
if answer == guess:
print("CORRECT! NICE")
return 1
else:
print("\n\nNooo, it's wrong")
return 0
def display_score(guesses, correct_guesses):
print("---------------------")
print("RESULTS")
print("---------------------")
print("Answers: ", end="")
for i in questions:
print(questions.get(i), end=" ")
print()
print("Guesses: ", end="")
for item in guesses:
print(item, end=" ")
print()
score = int((correct_guesses/len(questions)) * 100)
print("Your score is: " + str(score) + "%")
def play_again():
response = input("Do you wanna play again?" "(yes or no?): ")
response = response.lower
if response == "yes":
return True
else:
return False
questions = {"Qual a data de nascimento de Second?": "B",
"Qual o ditador favorito de Packat?": "B",
"Qual a segunda lei da termodinâmica?": "C",
"Qual a melhor obra asiática já feita?": "D"}
options = [["A. 25/12/2004", "B. 31/03/2004", "C. 31/04/2003", "D. 21/06/2003"],
["A. Josef Stalin", "B. Nicolás Maduro", "C. Xin Jin Ping", "D. Kim Jon Un"],
["A. Ação e reação", "B. Princípio da Conservação de Energia", "C. Entropia", "D. Princípio da Incerteza"],
["A. Naruto", "B. HunterxHunter", "C. One Piece", "D. Solo Leveling"]]
new_game()
while play_again:
new_game()
print("Byeeee")
the errors messages that appear are:
RESULTS
---------------------
Answers: B B C D
Guesses: Traceback (most recent call last):
File "c:\Users\Segundinho\Documents\Programação\Python\Learning\quiz game.py", line 104, in <module>
new_game()
File "c:\Users\Segundinho\Documents\Programação\Python\Learning\quiz game.py", line 27, in new_game
display_score(correct_guesses, guesses)
File "c:\Users\Segundinho\Documents\Programação\Python\Learning\quiz game.py", line 58, in display_score
for item in guesses:
TypeError: 'int' object is not iterable
Can someone please help me out?

there are a bunch of small errors sprinkled about the code. One of the bigger things is sometimes you look like you want to call a function like upper() but end up using the function itself as a value.
Here is something that is close to your current code with these small wrinkles taken out. Hopefully it works as you expect. There are lots of enhancements you can look to in the future like the use of enumerate() and zip() but this should get you back on track:
def new_game():
guesses = []
correct_guesses = 0
question_num = 0
for key in questions:
print("\n\n")
print(key)
correct_answer = questions[key]
possible_answers = options[question_num]
for item in possible_answers:
print(item)
guess = input("Enter A, B, C or D: ")
guess = guess.upper()
guesses.append(guess)
correct_guesses += check_answer(correct_answer, guess)
question_num += 1
display_score(guesses, correct_guesses)
def check_answer(answer, guess):
if answer == guess:
print("CORRECT! NICE")
return 1
print("\n\nNooo, it's wrong")
return 0
def display_score(guesses, correct_guesses):
print("---------------------")
print("RESULTS")
print("---------------------")
print("Corrent Answers: ", end="")
for question in questions:
print(questions.get(question), end=" ")
print()
print("Your Guesses: ", end="")
for guess in guesses:
print(guess, end=" ")
print()
score = int((correct_guesses/len(questions)) * 100)
print("Your score is: " + str(score) + "%")
def play_again():
response = input("Do you wanna play again?" "(yes or no?): ")
response = response.lower()
return response == "yes"
questions = {
"Qual a data de nascimento de Second?": "B",
"Qual o ditador favorito de Packat?": "B",
"Qual a segunda lei da termodinâmica?": "C",
"Qual a melhor obra asiática já feita?": "D"
}
options = [
["A. 25/12/2004", "B. 31/03/2004", "C. 31/04/2003", "D. 21/06/2003"],
["A. Josef Stalin", "B. Nicolás Maduro", "C. Xin Jin Ping", "D. Kim Jon Un"],
["A. Ação e reação", "B. Princípio da Conservação de Energia", "C. Entropia", "D. Princípio da Incerteza"],
["A. Naruto", "B. HunterxHunter", "C. One Piece", "D. Solo Leveling"]
]
while True:
new_game()
if not play_again():
break
print("Byeeee")

Welcome to Stack-Overflow Luiz, here is a way to debug your code and understand the possible source of the error:
1) Look at the error message with attention
RESULTS
---------------------
Answers: B B C D
Guesses: Traceback (most recent call last):
File "c:\Users\Segundinho\Documents\Programação\Python\Learning\quiz game.py", line 104, in <module>
new_game()
File "c:\Users\Segundinho\Documents\Programação\Python\Learning\quiz game.py", line 27, in new_game
display_score(correct_guesses, guesses)
File "c:\Users\Segundinho\Documents\Programação\Python\Learning\quiz game.py", line 58, in display_score
for item in guesses:
TypeError: 'int' object is not iterable
Do you know what all the words in the line TypeError: 'int' object is not iterable mean? If not search each one that you do not understand on Google.
This error means that it is not possible to iterate (loop over) a number, because a number is only one thing, while you need a collection of things to loop over them.
2) Print the variables before the error
A cool trick to debug is using locals() to print all the variables with their names and values, doing it you get:
I add:
print(locals())
before the incriminated line:
for item in guesses:
Doing so I can see the output:
Guesses: {'correct_guesses': [<built-in method upper of str object at 0x7fe72522bf70>,
<built-in method upper of str object at 0x7fe72522bf70>,
<built-in method upper of str object at 0x7fe72522bf70>,
<built-in method upper of str object at 0x7fe72522bf70>],
'guesses': 0,
'i': 'Qual a melhor obra asiática já feita?',
}
So now the cause of the error is clear, guesses is a number not a list, you probably meant to iterate over correct_guesses that is a list.

Related

Last run code is having problems with starting the code because indented block

Im having problem with the last code- "intro()" its stopping me from running the code so if anyone would be able to figure out whats wrong it would be of big help
*
I believe its not working because of a typo somewhere but iam unable to locate it or fix it so i hope any of yall can spot it and help me out?
it asks me to add more detail but there isnt much more i can say :/
import time
from termcolor import colored, cprint
answer_A = ["A", "a"]
answer_B = ["B", "b"]
answer_C = ["C", "c"]
yes = ["Y", "y", "yes"]
no = ["N", "n", "no"]
phone = 1
Lady_name = 0
Lady_lastname = 0
required = ("\nUse only A, B, or C\n")
print("=========================================================")
def Intro():
print ("\n\n You are sitting at the bar like every friday... ")
time.sleep(2)
print ("\n After your wife passed away, you don't really know what to do anymore")
time.sleep(2)
print ("\n You see a lady looking at you in the cornor of your eye.")
time.sleep(2)
print("""\n A. Move over and talk to the lady .
B. Let the lady be, she probably thinks you are weird.""")
choice = input(">>> ")
if choice in answer_A:
time.sleep(1)
option_lady()
elif choice in answer_B:
print("\n You let the lady be... \n You have been sitting here a while now and the lady have been glancing over at me the whole time.")
time.sleep(3)
print ("\n You glance over at her wondering if she is watching you.")
time.sleep(2)
print ("\n You make eye contact")
time.sleep(1)
print("""\n A. Go and talk to the lady.
B. Go home for the night.""")
choice = input(">>> ")
if choice in answer_A:
option_lady()
elif choice in answer_B:
print("\n You go and home and the lady looks sad. \n\n You go to sleep and never wake up again...")
def option_lady():
print ("\n you walk over to the lady")
print("""\n A. Hey, how you doing?
B. Hey, whats your name?""")
choice = input(">>> ")
if choice in answer_A:
option_question
elif choice in answer_B:
Lady_name = 1
Lady_lastname = 1
print ("\n Hey, Whats your name? You say.")
time.sleep(1)
cprint ('\nTracey! My name is Tracey smith.', 'red')
time.sleep(1)
Lady_name = 1
Lady_lastname = 1
print("\nWhat are you gonna answer? ")
print("""\n A. How are you doing?
\nB. Can I buy you a drink?""")
choice = input (">>> ")
if choice in answer_A:
print("dsa")
elif choice in answer_B:
Intro()
'
Your code ends in elif choice in answer_B:. Any statement ending in : must have a body, some code. If you explicitly don't want to put anything there, python provides pass exactly for that reason.:
elif choice in answer_B:
pass
should fix it.

Is it possible to stop a quiz when the player answers three questions wrong

I have added a "lives" feature to my quiz. When the player answers three questions wrong, which means lives=0. The game should end but instead, it continues and goes pass zero to -1 and so on.
I have tried a while loop but I am not sure IF I have coded it correctly as it fails to work.
lives = 3
print ("lives =", lives)
print (" ")
name = input ("What is your name?")
print ("Hello",name,". Good Luck.")
while lives >= 0:
##is the player ready to start
play = input ("Would you like to start? (Type Y for yes and N for no)")
if play == "Y" or play == "y":
from time import sleep
sleep (1.0)
print("Starting in...")
sleep (1.0)
print("3")
sleep(1.0)
print("2")
sleep(1.0)
print("1")
break
##3, 2, 1 countdown added wk.4 friday
elif play == "N" or play == "n":
print ("End")
break
else:
print ("That is not an answer.\n")
## 1st Question
question1 = ("1. What is Brisbanes AFL team called?")
options1 = (" a. Brisbane Tigers \n b. Brisbane Lions \n c. Brisbane Broncos \n d. Brisbane Magpies")
print (question1)
print (options1)
answer = input (">")
if answer == "B" or answer == "b":
print ("Correct!")
else:
print("Incorrect.")
print ("lives =", lives - 1)
lives-=1
## 2nd Question
question2 = ("2. What sport did Greg Inglis play")
options2 = (" a. rugby league \n b. rugby union \n c. AFL \n d. Soccer")
print (question2)
print (options2)
answer = input (">")
if answer == "A" or answer == "a":
print ("Correct!")
else:
print("Incorrect.")
print ("lives =", lives - 1)
lives-=1
## 3rd Question
question3 = ("3. Where were the 2018 Commonwealth Games held?")
options3 = (" a. Sunshine Coast \n b. Melbourne \n c. Brsbane\n d. Gold coast")
print (question3)
print (options3)
answer = input (">")
if answer == "D" or answer == "d":
print ("Correct!")
else:
print("Incorrect.")
print ("lives =", lives - 1)
lives-=1
The game should stop but instead continues saying the player is on negative lives. I would appreciate any help and thank you in advance for taking the time to help me with my problem. If you have any other pieces of advice that can better my quiz than feel free to comment.
if you want to game start again if lives = 0 then you need to include all your quiestions into while loop as well. And also include lives var into while loop so it will be set each time code enters loops, like:
lives = 3
print ("lives =", lives)
print (" ")
name = input ("What is your name?")
print ("Hello",name,". Good Luck.")
while lives >= 0:
lives = 3
##is the player ready to start
play = input ("Would you like to start? (Type Y for yes and N for no)")
if play == "Y" or play == "y":
print ('playing')
##3, 2, 1 countdown added wk.4 friday
elif play == "N" or play == "n":
print ("End")
break
else:
print ("That is not an answer.\n")
## 1st Question
question1 = ("1. What is Brisbanes AFL team called?")
options1 = (" a. Brisbane Tigers \n b. Brisbane Lions \n c. Brisbane Broncos \n d. Brisbane Magpies")
print (question1)
print (options1)
answer = input (">")
if answer == "B" or answer == "b":
print ("Correct!")
else:
print("Incorrect.")
print ("lives =", lives - 1)
lives-=1
## 2nd Question
question2 = ("2. What sport did Greg Inglis play")
options2 = (" a. rugby league \n b. rugby union \n c. AFL \n d. Soccer")
print (question2)
print (options2)
answer = input (">")
if answer == "A" or answer == "a":
print ("Correct!")
else:
print("Incorrect.")
print ("lives =", lives - 1)
lives-=1
## 3rd Question
question3 = ("3. Where were the 2018 Commonwealth Games held?")
options3 = (" a. Sunshine Coast \n b. Melbourne \n c. Brsbane\n d. Gold coast")
print (question3)
print (options3)
answer = input (">")
if answer == "D" or answer == "d":
print ("Correct!")
else:
print("Incorrect.")
print ("lives =", lives - 1)
lives-=1
lives = 3
print ("lives =", lives)
print (" ")
name = input ("What is your name?")
print ("Hello",name,". Good Luck.")
##is the player ready to start
play = input ("Would you like to start? (Type Y for yes and N for no)")
if play == "Y" or play == "y":
from time import sleep
sleep (1.0)
print("Starting in...")
sleep (1.0)
print("3")
sleep(1.0)
print("2")
sleep(1.0)
print("1")
##3, 2, 1 countdown added wk.4 friday
elif play == "N" or play == "n":
print ("End")
else:
print ("That is not an answer.\n")
while lives >= 0: # <----
## 1st Question
question1 = ("1. What is Brisbanes AFL team called?")
options1 = (" a. Brisbane Tigers \n b. Brisbane Lions \n c. Brisbane Broncos \n d. Brisbane Magpies")
print (question1)
print (options1)
answer = input (">")
if answer == "B" or answer == "b":
print ("Correct!")
else:
lives -= 1 # <----
print("Incorrect.")
print ("lives =", lives) # <----
if lives == 0: #<---
break
## 2nd Question
question2 = ("2. What sport did Greg Inglis play")
options2 = (" a. rugby league \n b. rugby union \n c. AFL \n d. Soccer")
print (question2)
print (options2)
answer = input (">")
if answer == "A" or answer == "a":
print ("Correct!")
else:
lives -= 1 # <----
print("Incorrect.")
print ("lives =", lives) # <----
if lives == 0: #<---
break
## 3rd Question
question3 = ("3. Where were the 2018 Commonwealth Games held?")
options3 = (" a. Sunshine Coast \n b. Melbourne \n c. Brsbane\n d. Gold coast")
print (question3)
print (options3)
answer = input (">")
if answer == "D" or answer == "d":
print ("Correct!")
else:
lives -= 1 # <----
print("Incorrect.")
print ("lives =", lives) # <----
if lives == 0: #<---
break

User input comparison isn't working

When the program goes to level one, and the game begins, I input the correct answer, but it does not work. The answer to the first quote is "death". The if else statement is supposed to acquire the answer of the user, and, if it is correct, display a message and move on to the next level. However, it does not. It displays another message telling me I lost.
I don't understand what is going on, especially since the if else statement picks up whether or not the user wants to view the rules.
Just to be safe, I am going to write one last clarification in a more straightforward form.
When I input the correct answer on level one, and I know for a fact it is the correct answer, it does not display the congrats_message, but it displays the loss_message.
welcome_message = "Hello! Welcome to Quote Game by Chandler Morell!"
version = "0.0.1"
congrats_message = "Congratulations! You passed level one!"
loss_message = "Sorry. You did not succeed. One life has been lost."
win_game_message = "Congratulations! You won the game!"
lost_game_message = "You made it to the end, but you did not win. Give it another go!"
lives = 3
def game_won():
print("")
print(win_game_message)
def game_lost():
print("")
print(lost_game_message)
def update_lives():
global lives
lives = lives - 1
if lives is 0:
print("You have ran out of lives. Game over.")
game_lost()
exit(0)
def view_rules():
rules = ["1. Do not look up quotes online.", "2. You have three lives.",
"3. You will have three words to choose from.", "4. Type the WORD not the NUMBER"]
print("")
for i in rules:
print(i)
def ask_view_rules():
rules_answer = input("Would you like to view the rules? (y/n): ")
if rules_answer is "y":
view_rules()
else:
print("")
print("Okay, let's begin!")
def level_one():
print("Lives: ", lives)
print("We will start with an easy quote. Fill in the blank.")
print("")
choices = ["1. death", "2. torture", "3. nothing"]
for i in choices:
print(i)
print("")
choice = input("Give me liberty or give me _____! - Patrick Henry ")
if choice is "death":
print("")
print(congrats_message)
print("")
level_two()
else:
print("")
print(loss_message)
print("")
update_lives()
level_two()
def level_two():
print("-----------------------")
print("")
print("Lives: ", lives)
print("Welcome to level two!")
print("")
choices = ["1. stupidity", "2. wisdom", "3. nobody"]
for i in choices:
print(i)
print("")
choice = input("Knowledge speaks, but ______ listens. - Jimi Hendrix ")
if choice is "wisdom":
print("")
print(congrats_message)
print("")
level_three()
else:
print("")
print(loss_message)
print("")
update_lives()
level_three()
def level_three():
print("-----------------------")
print("")
print("Lives: ", lives)
print("")
print("Wow. I am impressed!")
print("")
print(welcome_message)
print("Version: " + version)
ask_view_rules()
print("")
print("We will now begin the game!")
print("")
level_one()
As cricket_007 pointed out you need to use == instead of is in your code. This is because is returns True if both variables point to the same object whereas == returns True if the value of both variables are equal. I would also suggest that you use a line break in your code \n as opposed to using print(“”).

Python Hangman game and replacing multiple occurrences of letters

This is my first year programming with Python.
I am trying to create a hangman game.
So my questions: how do I check for
If the person is guessing a letter that has already been guessed and where to include it.
Check they are inputting a valid letter not multiple letters or a number.
What happens if it's a word such as 'Good' and they guess an 'o' at the moment my code breaks if this is the case. Also where on Earth would this be included in the code?
Here is my code
import random
import math
import time
import sys
def hangman():
if guess == 5:
print " ----------|\n /\n|\n|\n|\n|\n|\n|\n______________"
print
print "Strike one, the tigers are getting lonely!"
time.sleep(.5)
print "You have guessed the letters- ", guessedLetters
print " ".join(blanks)
print
elif guess == 4:
print " ----------|\n / O\n|\n|\n|\n|\n|\n|\n______________"
print
print "Strike two, pressure getting to you?"
time.sleep(.5)
print "You have guessed the letters- ", guessedLetters
print " ".join(blanks)
print
elif guess == 3:
print " ----------|\n / O\n| \_|_/ \n|\n|\n|\n|\n|\n______________"
print
print "Strike three, are you even trying?"
time.sleep(.5)
print "You have guessed the letters- ", guessedLetters
print " ".join(blanks)
print
elif guess == 2:
print " ----------|\n / O\n| \_|_/ \n| |\n|\n|\n|\n|\n______________"
print
print "Strike four, might aswell giveup, your already half way to your doom. Oh wait, you can't give up."
time.sleep(.5)
print "You have guessed the letters- ", guessedLetters
print " ".join(blanks)
print
elif guess == 1:
print " ----------|\n / O\n| \_|_/ \n| |\n| / \\ \n|\n|\n|\n______________"
print
print "One more shot and your done for, though I knew this would happen from the start"
time.sleep(.5)
print "You have guessed the letters- ", guessedLetters
print " ".join(blanks)
print
elif guess == 0:
print " ----------|\n / O\n| \_|_/ \n| |\n| / \\ \n| GAME OVER!\n|\n|\n______________"
print "haha, its funny cause you lost."
print "p.s the word was", choice
print
words = ["BAD","RUGBY","JUXTAPOSED","TOUGH","HYDROPNEUMATICS"]
choice = random.choice(words)
lenWord = len(choice)
guess = 6
guessedLetters = []
blanks = []
loading = ".........."
print "Loading",
for char in loading:
time.sleep(.5)
sys.stdout.write(char)
sys.stdout.flush()
time.sleep(.5)
print "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"
print "Great I'm glad to see you have finally woken."
time.sleep(1)
raw_input("Did you have a nice journey? ")
time.sleep(2)
print """
Oh wait, I don't care.
I have brought you to this island simply for my amusment. I also get paid to do this.
"""
time.sleep(2)
print"""
Don't worry this isn't all for nothing.
I'm sure the tigers will enjoy your company.
"""
time.sleep(2)
print"""
Hold on, let us make things interesting.
"""
time.sleep(2)
print "I will let you live if you complete an impossible game!"
time.sleep(2)
print "A game know as hangman!"
time.sleep(2)
print "HAHAHAHAHAH, I am so evil, you will never escape!"
time.sleep(2)
print "Enjoy your stay :)"
time.sleep(1)
print
print "Alright lets begin! If you wish to guess the word type an '!' and you will be prompted"
time.sleep(.5)
print
for s in choice:
missing = choice.replace(choice, "_")
blanks.append("_")
print missing,
print
time.sleep(.5)
while guess > 0:
letterGuess = raw_input("Please enter a letter: ")
letterGuess = letterGuess.upper()
if letterGuess == "!":
print "If you guess the FULL word correcly then you win, if incorrect you die. Simple."
fullWordGuess = raw_input("What is the FULL Word? ")
fullWordGuess = fullWordGuess.upper()
if fullWordGuess == choice:
print "You must have hacked this game"
time.sleep(.5)
print "Looks like you beat an impossible game! \nGood Job \nI'll show myself out."
break
else:
print "You lost, I won, you're dead :) Have a nice day!"
print "P.S The word was ", choice
break
else:
print
if letterGuess in choice:
location = choice.find(letterGuess)
blanks.insert(location, letterGuess)
del blanks[location+1]
print " ".join(blanks)
guessedLetters.append(letterGuess)
print
print "You have guessed the letters- ", guessedLetters
if "_" not in blanks:
print "Looks like you beat an impossible game! \nGood Job \nI'll show myself out."
break
else:
continue
else:
guessedLetters.append(letterGuess)
guess -= 1
hangman()
I did not really follow your code since there seems to be something wrong with your indentation, and the many print's confused me a little, but here is how I would suggest soving your Questions:
1.1. Create a list of guessed characters:
guessed_chars = []
if(guess in guessed_chars):
guessed_chars.append(guess)
#do whatever you want to do with the guess.
else:
print("You already guessed that.")
#do what ever you want to do if you already guessed that.
1.2 Lets say the word the player has to ges is word = "snake". To get the indices (since a string is just a list of charcters in python, only that it is immutable) where the guessed letter is in the word you could then use something like:
reveal = "_"*len(word)
temp = ""
for i, j in enumerate(word):
if j == guess:
temp += guess
else:
temp += reveal[i]
reveal = temp
print(reveal)
Maybe not fancy but it should work:
if (guess not in [a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z]):
with my suggestion for 1.2 you would just have to check if(word==reveal): no problem with duplicate charcters.
Since I am just a hobbyist there would probably be a more professional way though.
Next time maybe splitting up your question and first looking them up individually would be better, since I am pretty sure that at least parts of your questions have been asked before.

How to give user taking a quiz 2 chances to get the answer correct in python?

How to give user taking a quiz 2 chances to get the answer correct in python?
The easiest way to do this is with a for loop, with a break if they get it right, and maybe an else if they never got it right. For example:
for tries in range(2):
print("\n", "QUESTION 3:", "\n", "Which level of government is responsible for Tourism?")
print(" a) Municipal", "\n", "b) Fedral", "\n", "c) Provincial", "\n", "d) All", "\n", "e) Legislative")
answer3 = input("Make your choice: ")
if answer3 == "d" or answer3 == "D" :
print("Correct!")
break
else:
print("False!")
else:
print("Out of chances!")
If you don't want to re-print the question each time, just move the print calls before the for.
The linked tutorial section (and the following few three sections) explain this all in more detail.
def nTries(isCorrect, n = 2):
answer = input("Make your choice: ")
if isCorrect(answer):
print("Correct")
elif n == 1:
print("Out of tries, and incorrect")
else:
print("Incorrect")
nTries(isCorrect, n - 1)
Set this up like this
print("\n", "QUESTION 3:", "\n", "Which level of government is responsible for Tourism?")
print(" a) Municipal", "\n", "b) Fedral", "\n", "c) Provincial", "\n", "d) All", "\n", "e) Legislative")
nTries(lambda d: d.lower() == 'd')

Categories