将字符串与从`.readlines()`返回的字符串进行比较总是得到FAL

2024-10-03 19:30:56 发布

您现在位置:Python中文网/ 问答频道 /正文

似乎现在我的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!")

如果“guess”变量等于songname变量,那么它应该显示"Correct! You have earned three points, and now have a total of:",score, "points!"消息,尽管现在它总是显示Song is Incorrect消息。你知道吗

文件中存储的歌曲有:

Africa
Redding
Follow
Fleekes

Tags: oftheyouifishavenowpoints
2条回答

readlines不会从每行的末尾去掉换行符。如果您print(repr(songname)),您将看到它的末尾有一个\n。您可以通过自己调用strip来解决这个问题:

songname = lines[line_number].strip()

也许把答案也转换成小写。你知道吗

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

相关问题 更多 >