-1

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?

  • Does this answer your question? [Python - TypeError: 'int' object is not iterable](https://stackoverflow.com/questions/19523563/python-typeerror-int-object-is-not-iterable) – takendarkk Jan 26 '23 at 18:05
  • 3
    Compare `display_score(correct_guesses, guesses)` with `def display_score(guesses, correct_guesses):` – interjay Jan 26 '23 at 18:06
  • 3
    Hello luiz, you should try to make a more general question. Try to base your question on the error message such as "what does: 'TypeError: 'int' object is not iterable' means?" The objective of stack overflow is to make general questions that may be useful to someone else later. I'll help you on this one tho... :) – Florian Fasmeyer Jan 26 '23 at 18:06
  • Reading in your error log: " line 58," is where your error starts. As stated by @interjay, you intverted the inputs to your function, giving (correct_guessts, guesses) instead of (guesses, correct_guesses) You should find articles about how to read the python console. It will save you a lot of time in the long run and turn ou into a coding god. – Florian Fasmeyer Jan 26 '23 at 18:10
  • 2
    @FlorianFasmeyer aaah sorry! I got it, thank you. Thanks for the help!!! I'll try to search for it – luiz_second Jan 26 '23 at 18:12
  • but why does it always respond that you picked the wrong choice? – luiz_second Jan 26 '23 at 18:14
  • For that last question, you will have to cut your program into small pieces and try them separately. One question per question thread. ;) – Florian Fasmeyer Jan 26 '23 at 18:16
  • `guess = guess.upper` sets `guess` to be a function not the result of a function. – JonSG Jan 26 '23 at 18:18

2 Answers2

1

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.

Caridorc
  • 6,222
  • 2
  • 31
  • 46
  • I believe `guess = guess.upper` is the root of it. Thus a list of guesses is a list of the method `str.upper` as you see in your output. – JonSG Jan 26 '23 at 18:20
  • i'm legit having headaches trying to understand and fix this problem hahahaha, but thanks for all the help and tips guys!! You're awesome – luiz_second Jan 26 '23 at 18:32
  • @luiz_second Do not worry learning to program is hard for everyone ahahahah, another tip, as JonSG said, be very careful to always put parenthesis after calling a function in Python `"hello".upper()` is the uppercase version of `"hello"`, while `"hello".upper` is a function object – Caridorc Jan 26 '23 at 18:35
  • @luiz_second Did you manage to fix it in the end? – Caridorc Jan 28 '23 at 11:58
  • 1
    @Caridorc yeah! Jon fixed it for me haha, but I analized what I've done wrong step by step. One of my biggest fails was to forget to put the parantheses in the end of a function to call it, but now I'm paying more attention to it. Thanks for all the help, i'm still learning – luiz_second Jan 29 '23 at 00:35
1

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")
JonSG
  • 10,542
  • 2
  • 25
  • 36
  • 1
    OMG you made it!!! Thank you so much man, love you. I'll compare all of the two codes to find all my errors, I really appreciate your help, thank you! – luiz_second Jan 26 '23 at 18:55