我在python中遇到一个问题,有人告诉我这是与代码中的元组有关,idle在登录后给了我这个错误
回溯(最近通话最近一次):
artist, song = choice.split()
ValueError:需要超过1个值才能解包
这是我的完整代码
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
答案 0 :(得分:1)
问题归因于以下两行:
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(',')
答案 1 :(得分:0)
将artist, song = choice.split()
更改为:
song, artist = choice.split(',')
这将解决您的问题。
根据您提供的数据,应使用,
进行拆分。\