samedi 30 janvier 2021

stand-alone If statement in function being iterated twice

I'm currently writing a function for a music quiz, the quiz involves the user guessing the song name from the artist and the first letter of each word in the name. after 2 attempts, the users username and score are appended to a text file and the users score is outputted - the code in question is:

if x == attempts:
            print("You scored:  ", score)
            g.write(username)
            g.write(str(score))
            g.write(',')
            print(leaderboard)

The problem arises when i compile and run the code, as this if statement is executed 2 times before the program is finished, an example being:

You scored:   6
['kaylem3', 'kaylem3', 'b6', 'b6', 'c3', 'c3', 'e6', 'e6', '']
You scored:   6
['kaylem3', 'kaylem3', 'b6', 'b6', 'c3', 'c3', 'e6', 'e6', '']

I've tried changing it to a while loop and I've tried changing it to an elif branch but nothing seems to fix this minor issue.

the function in it's entirety at the moment is:

def userguess(song, attempts):
    global x
    while x < attempts:
        print(song.firstletters, song.artist)
        guess = str(input("Enter the songs name: "))
        if guess == song.name:
            global score
            score += 3
            x += 1
            print("You're correct")
            choose_song()
        elif guess != song.name:
            x += 1
            print("You're wrong")
            choose_song()
    while not x < attempts:
        print("You scored:  ", score)
        g.write(username)
        g.write(str(score))
        g.write(',')
        print(leaderboard)
        break

Thanks for any help!

Aucun commentaire:

Enregistrer un commentaire