Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Joel Crouse
4,727 PointsFunction/While Loop Issue
Below I've written a script just for fun but have run into a bit of a snag. This is basically the app we made in Python Basics but instead I've made a music player. My problem is that I have a function that generates a random song from the "songs" list and returns the song. What I want to happen is that, inside the while loop, when the user enters "skip" a random song is generated. That isn't what is happening and that's my problem here. Instead of generating a new song when the user enters "skip", the same song is printed each time.
Problem:
random_number = (randint(0, len(songs) - 1))
def random_song():
return songs[random_number]
if user_input.lower() == "skip":
new_song = random_song()
print(new_song)
session.append(new_song)
continue
How can I make it so a new song is generated each time the user enters "skip"?
Complete code:
from random import randint
songs = [
"Radioactive - Image Dragons",
"Nico And The Niners - Twenty One Pilots",
"Breezeblocks - alt-J",
"Apeshit - The Carters",
"High Hopes - Panic! at the Disco",
"R.I.P. SCREW - Travis Scott",
"Emotionless - Drake",
"All The Stars (with SZA) - Kendrick Lamar",
"DDU-DU DDU-DU - BLACKPINK",
]
playlist = []
random_number = (randint(0, len(songs) - 1))
def random_song():
return songs[random_number]
def add_to_playlist(song):
playlist.append(song)
print("\n".join(playlist))
while True:
session = []
user_input = input("> ")
if user_input.lower() == "skip":
new_song = random_song()
print(new_song)
session.append(new_song)
continue
elif user_input.lower() == "add":
add_to_playlist(new_song)
elif user_input.lower() == "session" or user_input.lower() == "quit"
print(session)
else:
pass
2 Answers
Steven Parker
243,656 PointsI agree with Dave. Right now, you only generate one random number and use the same one over and over. Moving the assignment into the function should give you a (potentially) different one each time. Since it's random, it will still sometimes be the same one.
Joel Crouse
4,727 PointsIndeed it worked. Thanks Dave and Steven for your answers!
Dave StSomeWhere
19,870 PointsDave StSomeWhere
19,870 PointsI think your issue is that the random number line
random_number = (randint(0, len(songs) - 1))is only executed once and should be inside the
random_song()function to get a new random number each time it is called.Does that work?