my code does not repeat when I guess the first answer wrong but then enter the correct answer

Question:

This is basically a guessing game where a file with data has random names of songs chosen from it and the player has to guess them with only the artist and first letter of each word of the song title given. However when the player guesses wrongly at first and then correct the code just stops instead of asking for a new answer and picking a new song. How can this be fixed ? Any suggestions would be appreciated. Also how can data in a file be sorted into a hierarchy and then displayed in that hierarchy ?

import random
score = 0

#player details
username = input("Please enter a username:")
password = input("Please enter a password:")


#player authentication
player_usr = input("Enter your username")
player_pass = input("Enter your password")

if player_usr == username:
  if player_pass == password:
    start = True
  else:
    print("Acces denied. Wrong details.")
    start = False
else:
  print("Acces denied. Wrong details")
  start = False


#main game loop
while start == True:
  t = True
  while t == True: 
    lines = open("music").read().splitlines()
    myline =random.choice(lines) #choosing from file 
    chosensong = myline
  
    artist = chosensong.rsplit(",", 1)[1]
    print(artist) #getting artist name

    song = chosensong.rsplit(",",1)[0]
    for word in song.split():
      print(word[0]) #getting letters of song name
    t = False
    

  target = chosensong.rsplit(",",1)[0]
  guess = None
  guesses = 0 
  answer = input("Enter guess:")
  guess = answer.lower()
    
  # points and authentcation of answer
  while guesses != 2:
    if guess == target:
      if guesses == 0:
        score = score + 3
        print("you were correct")
        break
      else:
        score = score + 1
        print("you were right")
        break
    else:
     print("please try again")
     guesses = guesses + 1
     answer = input("Enter guess:")
     guess = answer.lower()
     start = False

print(score)
Asked By: Laboratory gaming

||

Answers:

You probably won’t have a single user, so I modified your login logic to allow multiple users. This code contains a logins dictionary, where the keys are usernames, and values are passwords. When the user enters their username and password, you need to check

  1. Does logins contain the key that is the given username?
  2. Is the value at that key equal to the given password?
#player details
logins = {"admin": "admin", "lab_gaming": "abcd0123", "new_user": "password"}


while True:
    try:
        # Get auth details from user
        player_usr = input("Enter your username")
        player_pass = input("Enter your password")
        
        # Check if auth details are in the logins dict
        assert logins[player_usr] == player_pass
    except (KeyError, AssertionError): 
        # If the player_usr doesn't exist, then a KeyError is thrown
        # If the player_usr exists but the password is wrong, an AssertionError is thrown by the assert line
        print("Invalid login details")
    else: 
        # else is run if the try block completes without an error
        # If no error, auth succeeded, so break out of the while True loop
        break 

Next, let’s read the song list. This needs to be done only one time because presumably the song list won’t change every time you play the game.

# Read the file containing songs ONCE, since there's no need to read it multiple times per game
# If this is a csv file, consider using the csv module to read it
song_list = []
with open("music.txt") as f:
    for line in f:
        song_details = line.strip().lower().rsplit(",", 1)
        song_list.append(song_details)

# Now song_list is a list of lists. Each element of song_list is another list, which contains the song name and artist.

Next, we can start the game. Let’s define a variable play which will tell us whether the user wants to play another game. By default, this is true. Let’s also initialize score to zero.

play = True
score = 0

Now, you need to keep playing while the play variable is true. In each game, you randomly select a song at the start. You can do this without reading the entire file, because remember we read the file already.

I modified your code that prints the song hint slightly.

Next, we start the turns loop. Remember, the while loop can take any condition, so we’re going to loop while turns < 3. (Of course, we initialized turns = 0 before we start this loop).

Inside this loop, we can ask the user for their guess, and if the guess is correct, add to their score and break out of the inner loop. If their guess is wrong, increment turns and continue the loop. Remember, we already check turns < 3, so we don’t need yet another check here.

Now you’re finally out of the inner loop. This means the game ended due to a correct guess, or the user ran out of turns. In either case, you can ask them if they want to play another game, and set the value of play accordingly. If play is set to False, then the loop will automatically end.

while play: # No need to == True, because that's what a boolean comparison does
    # Randomly select a song/artist combo, then automatically unpack them into separate variables
    selected_song, selected_artist = random.choice(song_list) 
    
    # Print selected artist
    print(f"Artist: {selected_artist}")
    
    # Select the first character of each word in the song
    # Then join all of them with a space in between
    song_clue = " ".join(word[0] for word in selected_song.split())
    
    # Print song clue
    print(f"Song: {song_clue}")
    
    turns = 0
    while turns < 3: # This automatically stops your turn when turns >= 3
        guess = input("Enter guess: ").lower()
        if guess == selected_song:
            print("You were correct!")
            if turns == 0:
                score += 3
            else:
                score += 1
            break # This breaks the inner while loop
        else:
            print("Please try again.")
            turns += 1 
    
    # Now you're out of the inner loop, so you can ask the user if they want to play again
    play = input("Play again (y/n)? ").lower() == 'y'

print(f"Your score was {score}")    
Answered By: Pranav Hosangadi
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.