173k views
5 votes
write code to read a list of song durations and song names from input. for each line of input, set the duration and name of currsong. then add currsong to myplaylist. input first receives a song duration, then the name of that song (which you can assume is only one word long). input example: 424 time 383 money -1

User Sidarcy
by
8.7k points

2 Answers

4 votes

Final answer:

To read a list of song durations and names from input and add them to a playlist in Python, you can use a loop to process each line of input. Split each line into the duration and name of the song, and then create a dictionary with these values. Finally, add the dictionary to a list representing the playlist.

Step-by-step explanation:

Python code to read a list of song durations and names

To solve this problem, you can use a loop to read the input lines. For each line, you can split it into duration and name using the split() method. Then, create a dictionary with 'duration' and 'name' as keys and the extracted values as their respective values. Finally, add the dictionary to a list to represent the playlist.

myplaylist = []

while True:
line = input()
if line == '':
break
duration, name = line.split()
currsong = {'duration': int(duration), 'name': name}
myplaylist.append(currsong)
User Dtracers
by
8.2k points
6 votes

Below is a simple Python code snippet that reads song durations and names from input, creates a Song object for each entry, and adds it to the myplaylist list.

The input is assumed to be in the format of alternating lines of duration and name:

class Song:

def __init__(self, duration, name):

self.duration = duration

self.name = name

# Function to read song durations and names from input

def read_songs():

myplaylist = []

while True:

duration_input = input("Enter song duration (or -1 to stop): ")

duration = int(duration_input)

if duration == -1:

break

name = input("Enter song name: ")

currsong = Song(duration, name)

myplaylist.append(currsong)

return myplaylist

# Example usage

myplaylist = read_songs()

# Print the playlist

print("My Playlist:")

for song in myplaylist:

print(f"{song.name}: {song.duration} seconds")

User Rick Sanchez
by
9.1k points

No related questions found