π Python Crash Course – Chapter 8: Functions – Exercise 8-2 Solution
Welcome to another solution from Python Crash Course by Eric Matthes.
π Exercise 8-2
Task:
Write a function called favorite_book() that accepts one
parameter, title . The function should print a message, such as
One of my
favorite books is Alice in Wonderland .
Call the function, making sure to
include a book title as an argument in the function call
✅ Solution Code:
def favorite_book(title):
print(f"One of my favorite books is {title.title()}.")
# Call the function with a book title
favorite_book("Alice in Wonderland")
favorite_book("To Kill a Mockingbird")
π§ Code Explanation:
-
Define the function with a parameter:
The function
favorite_book(title)
is defined to accept one parameter,title
. This parameter allows the function to receive a value when it is called. -
Use the parameter:
Inside the function, the parameter
title
is used to display a message about a favorite book. Thetitle()
method is applied to ensure the book title is properly formatted with capitalized words. -
Call the function with arguments:
The function is called twice with different arguments:
favorite_book("Alice in Wonderland")
: Passes the string"Alice in Wonderland"
as the argument for thetitle
parameter.favorite_book("To Kill a Mockingbird")
: Passes the string"To Kill a Mockingbird"
as the argument for thetitle
parameter.
π Output:
One of my favorite books is Alice In Wonderland.
One of my favorite books is To Kill A Mockingbird
π Related Exercises from Chapter 8:
- ➤ Exercise 8-1 | Message
- ➤ Exercise 8-2 | Favorite Book
- ➤ Exercise 8-3 | T-Shirt
- ➤ Exercise 8-4 | Large Shirts
- ➤ Exercise 8-5 | Cities
- ➤ Exercise 8-6 | City Names
- ➤ Exercise 8-7 | Album
- ➤ Exercise 8-8 | User Albums
- ➤ Exercise 8-9 | Magicians
- ➤ Exercise 8-10 | Great Magicians
- ➤ Exercise 8-11 | Unchanged Magicians
- ➤ Exercise 8-12 | Sandwiches
- ➤ Exercise 8-13 | User Profile
- ➤ Exercise 8-14 | Cars
- ➤ Exercise 8-15 | Printing Models
- ➤ Exercise 8-16 | Imports
- ➤ Exercise 8-17 | Styling Functions
π 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
πTrending Topics
π 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
π Follow Us And Stay Updated For Daily Updates
Comments
Post a Comment