我怎样才能使python读取一个文件,而任务是让某人从这个文件中命名10首歌曲,而不必重复一首歌曲

2024-04-26 03:49:35 发布

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

在python中,我试图让python读取一个文本文件(这个文本文件有一个歌曲列表,所有歌曲都在不同的行上),运行代码的人需要命名其中的10首歌曲。我已经设法做到了这一点,但它允许你把所有10猜测相同的答案。有人能帮忙吗,所以你不能说同样的答案

import random
score = 0
print("Welcome to my quiz. The task is to name 10 of Juice Wrld's songs. You get two wrong answers, and if you pass that margin you lose. Good luck!")
    
def login(): #defines the function
    file = open("musicpass.txt", "r")
    password = file.read()
    userguess = input("Enter password for access: ")
    if password == userguess:
        print("Access Granted!")
        game(song)
        ransong()
    else:
        print("Access Denied!")
        login()

def ransong():
    with open("musicsongs.txt", "r") as file:
        content= file.read()
        words = content.splitlines()
  
    # print random string
    #print(random.choice(words))
    return words


def game(song):
    songlist = song
    guess=0
    score=0
    while guess != 2:
        if score == 10:
            print("Well done, you win!")
            break
            
        usguess1 = input("Enter your choice here: ")
        if usguess1 in songlist:
            print("Correct!")
            score = score + 1                                             
        else:
            print("Incorrect, one more guess allowed")
            guess = guess + 1
    else:
        print("Your score is:",score)
        print("Incorrect, no more guesses left.")



def main():
    login()
song=ransong()
main()

1条回答
网友
1楼 · 发布于 2024-04-26 03:49:35

在他们猜对之后,您可以像这样从列表中删除歌曲:

if usguess1 in songlist:
    songlist.remove(usguess1)
    print("Correct!")
    score = score + 1      

或者建立一个猜测列表并对照它进行检查,如果您想对重复项做一些不同的操作

guesses=[]
if usguess1 in songlist:
    if usguess1 in guesses:
        print("Already Guessed!")
    else:
        print("Correct!")
        score = score + 1  

相关问题 更多 >