如何解决python中元组的问题

2024-06-26 17:52:49 发布

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

我在python中遇到了一个问题,有人告诉我这与代码中的元组有关,idle在登录后给了我这个错误

回溯(最近一次呼叫):

artist, song = choice.split()

ValueError:需要多个值才能解包

这是我的全部代码

import random
import time

x = 0
print("welcome to music game please login below")

AuthUsers = {"drew":"pw","masif":"pw","ishy":"pw"}
#authentication
PWLoop = True

while PWLoop:
    userName = input("what is your username?")
#asking for password
    password = (input("what is the password?"))

    if userName in AuthUsers:
        if AuthUsers.get(userName) == password:
            print("you are allowed to play")
            PWLoop = False
        else:
            print("invalid password")
    else:
        print("invalid username")


#GAME

#SETTING SCORE VARIBLE
score = 0

#READING SONGS

read = open("SONGS.txt", "r")
songs = read.readline()
songlist = []

for i in range(len(songs)):
    songlist.append(songs[i].strip())



while x == 0:
    #RANDOMLY CHOSING A SONG

    choice = random.choice(songlist)
    artist, song = choice.split()


#SPLITTING INTO FIRST WORDS

songs = song.split()
letters = [word[0] for word in songs]


#LOOp

for x in range(0,2):
    print(artist, "".join(letters))
    guess= str(input(Fore.RED + "guess the song"))
    if guess == song:
        if x == 0:
            score = score + 2
            break
        if x == 1:
            score = score + 1
            break


#printing score

Tags: inforifsongartistusernamepasswordsplit
2条回答

artist, song = choice.split()更改为:

song, artist = choice.split(',')

这会解决你的问题。 根据你给出的数据,你应该用,分割

问题在于这两条线:

choice = random.choice(songlist)
# choice will be single item from songlist chosen randomly.
artist, song = choice.split() # trying to unpack list of 2 item
# choice.split() -> it will split that item by space
# So choice must be a string with exact one `space`
# i.e every entry in songlist must be string with exact one `space`

作为文件的格式https://pastebin.com/DNLSGPzd

为了解决这个问题,

更新代码:

artist, song = choice.split(',')

相关问题 更多 >