Сравнение строки со строкой, возвращенной из `.readlines ()` всегда дает False - PullRequest
0 голосов
/ 09 января 2019

Кажется, что сейчас мои операторы if не регистрируют, что другая переменная равна одной заявленной. Я даже распечатал сохраненную переменную, которая предполагает проверку, и сохраненная догадка и переменная должны быть равны друг другу.

Я попытался сделать это с учетом регистра, и без. Я попытался отобразить переменную, чтобы затем точно ввести ее, и она просто не будет работать.

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!")

Если переменная "предположения" равна переменной songname, то она должна отображать сообщение "Correct! You have earned three points, and now have a total of:",score, "points!", хотя сейчас она всегда отображает сообщение Song is Incorrect.

Песни, хранящиеся в файле:

Africa
Redding
Follow
Fleekes

Ответы [ 2 ]

0 голосов
/ 09 января 2019

Возможно, преобразовав также ответ в нижний регистр.

if guess.lower() == answer.lower():
0 голосов
/ 09 января 2019

readlines не удаляет символы новой строки с конца каждой строки. Если вы print(repr(songname)), вы увидите, что у него есть \n в конце. Вы можете это исправить, позвонив strip самостоятельно:

songname = lines[line_number].strip()
...