Search code examples
pythonpython-3.xstringreadlines

Comparing a string with the one returned from `.readlines()` always gives False


It seems that right now my if-statements don't register that another variable is equal to one stated. I have even printed the variable stored that the guess is to check-against, and both the guess and variable stored should be equal to each other.

I have tried making it case-sensitive, and without. I have tried displaying the variable to then type it out exactly and it just won't work.

import random
from random import randint

loop = 0
score = 0


f = open("songs.txt", "r")
line_number = randint(0,3)
lines = f.readlines()
songname = lines[line_number]

firstletters = songname.split()
letters = [firstletters[0] for firstletters in firstletters]
print(" ".join(letters))

f.close()

f = open("artists.txt", "r")
lines = f.readlines()
artistname = lines[line_number]

print("The first letter of each word in the title of the song is: " + "".join(letters))
print("The artist of the above song is: " + artistname)

print(songname)

answer = songname

guess = input("What is your guess? ")

if guess.lower()==answer:
  score = score + 3
  print("Correct! You have earned three points, and now have a total of:",score, "points!")

else:
  print("Incorrect! You have one more chance to guess it correctly!")
  guesstwo = input("What is your second guess? ")

  if guesstwo.lower()==answer:
    score = score + 1
    print("Correct! You have earned one point, and now have a total of:",score, "points!")

  else:
    print("Incorrect! Unfortunately you have guessed incorrectly twice- therefore the game has now ended. You had a total of:",score,"points!")

If the "guess" variable equals the songname variable, then it should display the "Correct! You have earned three points, and now have a total of:",score, "points!" message, although right now it always displays the Song is Incorrect message.

The songs stored in the file are:

Africa
Redding
Follow
Fleekes

Solution

  • Maybe by converting also answer to lowercases.

    if guess.lower() == answer.lower():