Exercise 8-8 Solution Python Crash Course Chapter 8 : Functions

 

📘 Python Crash Course – Chapter 8: Functions – Exercise 8-8 Solution

Welcome to another solution from Python Crash Course by Eric Matthes.


📝 Exercise 8-8

Task:
Start with your program from Exercise 8-7 . Write a while loop that allows users to enter an album’s artist and title . Once you have that information, call make_album() with the user’s input and print the dictionary that’s created .
Be sure to include a quit value in the while loop

✅ Solution Code:


def make_album(artist, title):
    album = {
        'artist': artist,
        'title': title
    }
    

while True:
    print("\nEnter the artist and title of the album (or 'q' to quit):")
    artist = input("Artist: ")
    if artist.lower() == 'q':
        break
    title = input("Title: ")
    if title.lower() == 'q':
        break

    album = {artist : title}
    print(f"Album created: {album}")

🧠 Code Explanation:

  1. Define the function:

    The function make_album(artist, title) is defined to create a dictionary representing an album. The dictionary contains two keys:

    • 'artist': Stores the name of the artist.
    • 'title': Stores the title of the album.
  2. Start an infinite loop:

    A while True loop is used to continuously prompt the user for input until they choose to quit.

  3. Prompt for artist and title:

    The user is asked to enter the artist's name and the album's title. If the user enters 'q' (case-insensitive) for either input, the loop is exited using the break statement.

  4. Create the album dictionary:

    For each valid input, a dictionary is created with the artist as the key and the title as the value. This dictionary represents the album.

  5. Display the album:

    The created album dictionary is displayed to confirm that the input has been processed correctly.

  6. Quit condition:

    The loop continues to prompt the user for new albums until they enter 'q' for either the artist or the title, at which point the program terminates.

🔍 Output:


Enter the artist and title of the album (or 'q' to quit):
Artist: Artist-1
Title: title-1
Album created: {'Artist-1': 'title-1'}

Enter the artist and title of the album (or 'q' to quit):
Artist: artist-2
Title: title-2
Album created: {'artist-2': 'title-2'}

Enter the artist and title of the album (or 'q' to quit):
Artist: q

📚 Related Exercises from Chapter 8:


🔗 Connect With Us:

“In the world of code, Python is the language of simplicity, where logic meets creativity, and every line brings us closer to our goals.”
— Only Python

📌 Tags: #Python #PythonCrashCourse #CodingForBeginners #LearnPython #PythonProjects #PythonTips

Previous Post Next Post

Contact Form