how do i fix my problem with my tuple in python - python

i have a problem in python i have been told that is is to do with the tuple in the code the idle gives me this error after login
Traceback (most recent call last):
artist, song = choice.split()
ValueError: need more than 1 value to unpack
this is my full code
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

Issue is due to these two lines:
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`
As the format of your file https://pastebin.com/DNLSGPzd
And To fix the issue just split by ,
Updated code:
artist, song = choice.split(',')

Change artist, song = choice.split() to:
song, artist = choice.split(',')
this will fix your problem.
according to the data that you given, you should split with ,.\

Related

Python - list index out or range (unicode)

I am writing a program to encrypt / decrypt an inputted message using a key generated from a pool
The pool is created by appending unicode characters to an array
When selecting option 2 (encrypt) and reading the genkey.txt file (after generating the key with option 1), the program shows an index error as shown:
Exception has occurred: IndexError
list index out of range, line 58, in b = keyarray[a]
However, when removing the unicode script and replacing the pool with plain text (e.g [a, b, c...]) the message is encrypted without any issue.
Any way to fix this?
Code:
import random
programrun = 0
encryptedarray = []
decryptedarray = []
keyarray = []
while programrun < 1:
pool = []
for i in range(32,123): #Unicode characters
pool.append(chr(i))
print("Encryption / Decryption")
print("")
print("1. Generate Key")
print("2. Encrypt")
print("3. Decrypt")
print("4. Quit")
print("NOTE: Key must be generated before selecting Encryption / Decryption")
print("")
option = int(input("Enter the number corresponding to the option: "))
if option == 1:
a = 20
while a > 0:
b = random.randint(0,57)
c = pool[b]
keyarray.append(c)
a = a - 1
keygen = ("".join(keyarray))
print("Your generated key is:", keygen)
print("")
print("(Make sure you have generated a key before typing 'yes')")
writebool = input("Do you want to save the file to your computer? ")
if writebool == "yes":
keyfile = open("genkey.txt", "x")
keyfile.write(keygen)
keyfile.close()
wbval = 1
print("File saved to genkey.txt successfully")
print("")
quitval = 1
elif writebool == "no":
print("ok")
else:
print("Type yes or no")
elif option == 2:
encryptvalid = 0
while encryptvalid < 1:
msg = str(input("Enter the message to be encrypted: "))
genkeyf = open("genkey.txt", "r")
genkeydata = genkeyf.read()
if genkeydata == keygen:
print("File VALID")
encryptvalid = 1
for i in msg:
a = pool.index(i)
b = keyarray[a]
encryptedarray.append(b)
p = ("".join(encryptedarray))
print("")
print("Your encrypted string is: ")
print("".join(encryptedarray))
else:
print("File INVALID")
print("Please check if the genkey.txt file matches the current generated key.")
a = pool.index(i) looks up the index of a character of the message in the pool, then that index is used to lookup a value in the keyarray with b = keyarray[a].
pool is 91 bytes long, but keyarray is 20 bytes long, so many of the indexes are too high. You probably want b = keyarray[a % len(keyarray)]. This uses the modulus operator to constrain the lookup from 0-19.

How to read and write on this file?

I have to write a code that does the following:
Create a menu with three options.
Print the subjects
Search for a subject
Q) Quit
Create a main() function
Prompt the user for a file name.
Prompt the user for an option from the menu.
Open the file and load the data into a list.
Option 1 should print all the school subjects in the list, under a title
Once all the records have been processed, print a count.
Option 2 should allow the user to search for a subject in the list.
Add exception handling. (add last)
Create your own text file, with a list of 10 or more school subjects.
Submit the program module(s) and the output.
For a bonus, create a second module and import it, or add a menu item to add names to the list and save the data to a new file.
I keep getting "file not found" and was wondering if anyone could help. I want to name the read file as subjects.txt
This is the code I have written:
#Display menu and ask for user to select option
def menu():
print('Enter "1" to print subjects')
print('Enter "2" to search subjects')
print('Enter "3" to add subject')
print('Enter "q" to quit')
option = input('Enter option: ')
return option.lower()
#Reading files
def read_subjects(file_name):
file1 = open(subjects, 'r')
return file1.readlines()
#Add new subjects
def write_to_file(file_name, subject):
current_lines = []
try:
current_lines = read_subjects(file_name)
except:
pass
current_lines.append(subject + '\n')
file1 = open(file_name, 'w')
file1.writelines(current_lines)
file1.close()
#Main function
def main():
correct_file_name = False
file_name = 'subjects'
subjects = []
# while loop to ensure a user selects an existing file with catch and try
while not correct_file_name:
file_name = input('Enter file name: ')
try:
subjects = read_subjects(subject)
correct_file_name = True
except:
print('Error file not found')
# while loop to implement contious flow of options
while True:
selected_option = menu()
# quit program
if selected_option == 'q':
quit()
# display subjects
if selected_option == '1':
print('Subjects')
# Strips the newline character
count = 0
for line in subjects:
count += 1
print("{}: {}".format(count, line.strip()))
print('Total subjects: ', count)
print('==============================================')
# search for a subject
if selected_option == '2':
subject = input('Search subject: ')
print('Subjects')
count = 0
for line in subjects:
striped_line = line.strip()
if subject.lower() in striped_line.lower() or striped_line.lower() in hobby.lower():
count += 1
print("{}: {}".format(count, line.strip()))
print('Total subjects: ', count)
print('==============================================')
# bonus add new hobbies
if selected_option == '3':
subject = input('Enter new hobby: ')
write_to_file('subjects.txt', subject)
# call main function
if __name__ == '__main__':
main()

why i am getting blank list as output in python even after appending item in it?

#bll
class cms():
def __init__(self):
self.namelist = []
self.idlist = []
self.moblist = []
self.emaillist = []
self.reslist = []
def addcustomer(self):
self.idlist.append(id)
self.namelist.append(name)
self.moblist.append(mob)
self.emaillist.append(email)
return print("Customer Added")
def showcustomer(self):
print(self.idlist, self.namelist, self.moblist, self.emaillist)
#pl
while(1):
print("Enter Your Choice Enter 1 to Add, 2 to search, 3 to delete, 4 to Modify, 5 to Display All, 6 to Exit")
ch = input("Enter your choice")
conman = cms()
if ch == '1':
id = input("ENter your id")
name = input("Enter Your name")
mob = input("Enter your mobile no")
email = input("Enter your email")
conman.addcustomer()
elif ch == '2':
conman.showcustomer()
this is my code when I am entering 1 then the customer gets added,but when I call another method to print that appended item it returns blank list
Output:-
Enter your choice2
[] [] [] []
Help!! Please.
conman = cms()
Because this is inside the loop, each time through the loop, this creates a separate, new cms with its own lists of data, and makes conman be a name for the new value.
elif ch == '2':
conman.showcustomer()
This, therefore, displays information from the new conman, ignoring everything that was done in the previous iteration of the loop.

how to fix "guess the song game" python

I am trying to create this game for guessing songs however it will not allow me to have over one song even after i change the range I also would like to know how to add the code to do scores for guessing the write song.
import random
for x in range(0,1):
randNum = int(random.randint(0,1))
song = open("Songs.txt", "r")
songname = str(song.readlines()[randNum])
print(songname[0])
song.close()
artist = open("Artists.txt", "r")
artistname = artist.readlines()[randNum]
print(artistname[0])
artist.close()
y = 0
songGuess = input("What is the song called?")
while(y<=2):
if songGuess == songname:
print("Answer correct!")
break
else:
y = y + 1
songguess = input("Incorrect! Try again:")
if y == 2:
print("GAME OVER")
break
You need to change your random.randint range to random.randint(0,len(song.readlines())-1), so that you are chosing a random index from all listed songs,and do the same thing with artists.
A better approach is to choose a random element from the list using random.choice .
Your for range range(0,1) will cause your loop to run just once, update the range accordingly
You can use with keyword to automatically close the file instead of explicitly closing it.
So according to above changes, the fixed code might look like
import random
num_attempts = 10
#Run loop for num_attempts times
for x in range(0, num_attempts):
songname = ''
artistname = ''
#Use with to open file
with open('Songs.txt') as song:
#Read all songs into a list
songs = song.readlines()
#Choose a random song
songname = random.choice(songs)
print(songname)
with open('Artists.txt') as artist:
# Read all artists into a list
artists = artist.readlines()
# Choose a random artist
artistname = random.choice(artists)
print(artistname)
y = 0
#Play your game
songGuess = input("What is the song called?")
while(y<=2):
if songGuess == songname:
print("Answer correct!")
break
else:
y = y + 1
songguess = input("Incorrect! Try again:")
if y == 2:
print("GAME OVER")
break

Generating Random Combinations of Dictionary Key and Value Sets

I am creating a program to sort through a music library file. I have this one particular function, generateRandomPlaylist(musicLibDictionary), that I am stuck on.
The function needs to randomly pick a key from the dictionary and randomly assign one of the values to the key. For instance the artists in the dictionary include The Who, Adele and The Beatles. The respective albums include Tommy; 19, 21, 25; Abbey Road, Let It Be. I need the program to randomly pick one of the keys (the artists) and then randomly pick one of the key's values. The randomly generated playlist needs to have all three artists, not repeats, but different albums from the artist. The way I have it set up, the output doesn't necessarily use all three artists. Sample output should look like:
Here is your random playlist:
- 25 by Adele
- Abbey Road by The Beatles
- Tommy by The Who
Each time the function is called, the playlist should be different. Like I said, right now the function doesn't run properly, and I also get a printing error saying I cannot concatenate a list and a string, so I don't know where I am going wrong.
The code for the program is below:
# importing pickle
import pickle
import random
# declaration of functions
def displayMenu():
print("Welcome to Your Music Library")
print("Options:")
print("\t1) Display Library")
print("\t2) Display all artists")
print("\t3) Add an album")
print("\t4) Delete an album")
print("\t5) Delete an artist")
print("\t6) Search Library")
print("\t7) Generate a random playlist")
print("\t8) Make your own playlist")
print("\t9) Exit")
def displayLibrary(musicLibDictionary):
for key in musicLibDictionary:
print("Artist: " + key)
print("Albums: ")
for album in musicLibDictionary[key]:
print("\t- " + album)
def displayArtists(musicLibDictionary):
print("Displaying all artists:")
for key in musicLibDictionary:
print(" - " + key)
def addAlbum(musicLibDictionary):
artistName = input("Please enter the name of the artist you would like to add: ")
albumName = input("Please enter the name of the album you would like to add: ")
if artistName in musicLibDictionary.keys():
musicLibDictionary[artistName].append(albumName)
else:
musicLibDictionary[artistName] = [albumName]
def deleteAlbum(musicLibDictionary):
artist = input("Enter artist: ")
albumToBeDeleted = input("Enter album: ")
if artist in musicLibDictionary.keys():
if albumToBeDeleted in musicLibDictionary[artist]:
musicLibDictionary[artist].remove(albumToBeDeleted)
return True
else:
return False
else:
return False
def deleteArtist(musicLibDct):
artistToBeDeleted = input("Enter artist to delete: ")
if artistToBeDeleted in musicLibDct.keys():
del musicLibDct[artistToBeDeleted]
return True
else:
return False
def searchLibrary(musicLibDictionary):
searchTerm = input("Please enter a search term: ")
searchTerm = searchTerm.lower()
print("Artists containing" + searchTerm)
for key in musicLibDictionary.keys():
if searchTerm.lower() in key.lower():
print("\t - ", end="")
print(key)
print("Albums containing" + searchTerm)
for album in musicLibDictionary[key]:
print("\t- " + album)
for key in musicLibDictionary.keys():
for album in musicLibDictionary[key]:
if searchTerm in album.lower():
print("\t - ", end="")
print(album)
def generateRandomPlaylist(musicLibDictionary):
print("Here is your random playlist:")
for artist in musicLibDictionary.keys():
artistSelection = random.choice(list(musicLibDictionary.keys()))
albumSelection = random.choice(list(musicLibDictionary.values()))
print("\t-" + albumSelection + "by" + artistSelection)
def loadLibrary(libraryFileName):
fileIn = open(libraryFileName, "rb")
val = pickle.load(fileIn)
val = dict(val)
return val
def saveLibrary(libraryFileName, musicLibDictionary):
fileIn = open(libraryFileName, "wb")
pickle.dump(musicLibDictionary, fileIn)
def main():
musicLib = loadLibrary("musicLibrary.dat")
userChoice = ""
while (userChoice != 7):
displayMenu()
userChoice = int(input("> "))
if userChoice == 1:
displayLibrary(musicLib)
elif userChoice == 2:
displayArtists(musicLib)
elif userChoice == 3:
addAlbum(musicLib)
elif userChoice == 4:
deleteAlbum(musicLib)
elif userChoice == 5:
deleteArtist(musicLib)
elif userChoice == 6:
searchLibrary(musicLib)
elif userChoice == 7:
generateRandomPlaylist(musicLib)
elif userChoice == 8:
saveLibrary("musicLibrary.dat", musicLib)
# Call main
main()
Here's one way to do it, if I understand correctly that you want each artist exactly once in a random order and a random album from each artist:
def generateRandomPlaylist(musicLibDictionary):
print("Here is your random playlist:")
artists = list(musicLibDictionary.keys())
random.shuffle(artists) # Perform an in-place shuffle
for artistSelection in artists:
albumSelection = random.choice(list(musicLibDictionary[artistSelection]))
print("\t-" + albumSelection + "by" + artistSelection)
We know we want all the artists exactly once, but in a random order. Since the keys of the dictionary are the artists, then we can just perform a random.shuffle on the keys to get a random ordering of the artists. Then we have to look into each artist's albums (musicLibDictionary[artist]) and make a random.choice to pick out one album at random.
What your code is doing, on a line by line basis, is the following:
def generateRandomPlaylist(musicLibDictionary):
print("Here is your random playlist:")
for artist in musicLibDictionary.keys(): # For each artist
artistSelection = random.choice(list(musicLibDictionary.keys())) # Choose one artist randomly (not necessarily the one in your for loop)
albumSelection = random.choice(list(musicLibDictionary.values())) # Choose a random album list (musicLibDictionary.values() returns a list of lists, so you're just choosing a random discography (list) from a random artist)
print("\t-" + albumSelection + "by" + artistSelection) # Because this is not indented into your loop, you're likely only getting the last one chosen
The reason you were getting issues appending a string and a list (not allowed in python directly, you must cast the list to a string first) is that your albumSelection variable was a full list of the albums from a random artist, not necessarily even the artist in the artistSelection variable. Your musicLibDictionary.values() was returning something like [['Tommy'], ['19', '21', '25'], ['Abbey Road', 'Let It Be']]. random.choice picks a random value out of the list provided to it so given a list like [[1,2,3], [4,5,6]] it could pick out [1,2,3].

Categories