how to fix "guess the song game" python - 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

Related

Can't end program with break. Break is used inside defined function and function is later used inside while loop. What can I do?

I need a help with a certain situation.
We have the following code:
import random
Genre = ["Power metal", "Melodic death metal", "Progressive metal", "Rock"]
Power_metal = ["Helloween", "Dragonforce", "Hammerfall"]
Melodic_death_metal = ["Kalmah", "Insomnium", "Ensiferum", "Wintersun"]
Progressive_metal = ["Dream theater", "Symphony X"]
Rock = ["Bon Jovi", "Nirvana"]
a = ["Pumpkins united", "Halloween"]
Helloween = set(a)
Music = input("\nSelect a music genre from available: %s:" % (Genre))
def bands(Music):
while True:
if Music == "Melodic death metal":
return (Melodic_death_metal)
elif Music == "Power metal":
return (Power_metal)
elif Music == "Progressive metal":
return (Progressive_metal)
elif Music == "Rock":
return (Rock)
else:
Music = input("\nYou entered the wrong name. Please, enter again: %s:" % (Genre))
Band = input("\nReffering to chosen genre, I have bands such as: %s. Choose a specific band and I'll suggest a random song:\n" % bands(Music))
def fate(Band):
while True:
if Band == "Helloween":
if len(Helloween) != 0:
print("Suggested song: ", Helloween.pop())
break
elif len(Helloween) == 0:
print("I don't have more songs to propose. Enjoy your music")
break
fate(Band)
while True:
next = input("\nWould you like me to suggest one more song from the band of your choice ? Answer yes or no:\n")
if next == "no":
print("Enjoy your music")
break
elif next == "yes":
fate(Band)
The problem is: when we get to the point where the program has no more songs to offer, it should print: "I don't have more songs to propose. Enjoy your music"and break. But instead of this, it goes all the way to the last loop and doesn't end until I type in the console no.
Can I make somehow the statement inside loop to end program even if I type in console yes?
Cause it will keep printing:
I don't have more songs to propose. Enjoy your music.
Would you like me to suggest one more song from the band of your choice ? Answer yes or no:
Thanks for the help.

how do i fix my problem with my tuple in 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 ,.\

What way could I add score with different values to my code?

I need to add score to my code and I don't know how. I've tried different ways of previous code I had but they would not work in this program. Any suggestions on what I could do?
I need to make the score so that if the user guesses right on the first try they get 3 points and if they get it on the second they get 1 but if they get it wrong they get none. Here is my code :
def choose_song(artist, songs, song_choosen):
idx = 0
guess_correct = False
song = ''
while idx < 2:
guess = input('The artist is {} and the song is {}... Enter your guess {}: '.format(artist, song_choosen[:3], idx+1))
#Iterate through all songs to check if the guess is right, if it is, break out of for loop
for song in songs:
if guess.lower().strip() == song.lower().strip():
guess_correct = True
song = guess
break
#If the user guessed correctly, we are done else try again
if guess_correct:
break
else:
idx+= 1
#Show the final output accordingly
if guess_correct:
print('You guessed correctly. The song is indeed {} '.format(song))
else:
print('You guessed wrong. The song is {} '.format(song_choosen))
choose_song('Eminem', ['Rap God', 'skip'], 'Rap God')
choose_song('Marshmello', ['Project Dreams', 'skip'], 'Project Dreams')
choose_song('Unlike Pluto', ['Late Bloomer', 'skip'], 'Late Bloomer')
Any help will be appreciated.
Add:
Line 4: score = 0
Line 13 score = [3,1,0][idx]
Line 23 Change print() command
Comments on what happens in the follwing new code:
idx = 0
guess_correct = False
song = ''
score = 0 #Add Variable for score and set it = 0
while idx < 2:
guess = input('The artist is {} and the song is {}... Enter your guess {}: '.format(artist, song_choosen[:3], idx+1))
#Iterate through all songs to check if the guess is right, if it is, break out of for loop
for song in songs:
if guess.lower().strip() == song.lower().strip():
guess_correct = True
song = guess
score = [3,1,0][idx] # Depending on your index (number of tries) give 3, 1 or 0 points
break
#If the user guessed correctly, we are done else try again
if guess_correct:
break
else:
idx+= 1
#Show the final output accordingly
if guess_correct:
print('You guessed correctly. The song is indeed {}. You got {} Points '.format(song, score)) # Print points
else:
print('You guessed wrong. The song is {}. You got no points '.format(song_choosen))
choose_song('Eminem', ['Rap God', 'skip'], 'Rap God')
choose_song('Marshmello', ['Project Dreams', 'skip'], 'Project Dreams')
choose_song('Unlike Pluto', ['Late Bloomer', 'skip'], 'Late Bloomer')

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].

If statement does not detect string or doesn't take action

I wanted to make a bot that plays Rock, Paper, Scissors with the player.
But every time I try to run the script, and type in Stein (German for rock),
the if statement doesn't detect it or doesn't take any action.
Here's my code so far:
import random
import time
print("Anfangs Buchstaben immer groß schreiben!")
time.sleep(2)
outcomes2 = ("Stein")
Runde = 0
while True:
Player = input("Deine Wahl: ")
for i in range(1):
outcomes = print(random.choice(outcomes2))
if outcomes == Player:
print("draw")
Runde + 1
continue
Issue 1
>>> outcomes2 = ("Stein")
>>> print(random.choice(outcomes2))
n
You're iterating over a string and selecting a character at random.
I'm assuming you want:
>>> outcomes2 = ("Stein", )
>>> print(random.choice(outcomes2))
Stein
Now, by specifying the ,, you're iterating over a tuple of strings (tuple of size 1). You'll end up getting "Stein" only unless you add more strings, like
outcomes2 = ("Stein", "Name2", "Name3", ...)
Issue 2
You want outcomes = random.choice(outcomes2). Do not assign the value to the print statement, because print returns None.
Putting it together...
outcomes2 = ("Stein", )
Runde = 0
while True:
Player = input("Deine Wahl: ")
outcomes = random.choice(outcomes2)
if outcomes == Player:
print("draw")
Runde + 1
continue
`import time
import random
comp_score=0
play_score=0
outcome=('rock','paper','scissor')
while True:
player = raw_input("Enter any?");
out=random.choice(outcome)
print "COMP->"+out
if out==player:
print "draw"
elif out=="rock"and player=="scissor":
comp_score+=1;
elif out=="scissor" and player=="rock":
play_score+=1;
elif out=="rock" and player=="paper":
play_score+=1;
elif out=='paper' and player=='rock':
comp_score+=1;
elif out=="scissor" and player=="paper":
play_score+=1;
elif out=='paper' and player=="scissor":
comp_score+=1;
elif player=="quit":
break;
print "GAME over"
print "PLayer score: ",play_score
print "Comp score ",comp_score`

Categories