π Python Crash Course – Chapter 8: Functions – Exercise 8-5 Solution
Welcome to another solution from Python Crash Course by Eric Matthes.
π Exercise 8-5
Task:
Write a function called describe_city() that accepts the name of
a city and its country . The function should print a simple sentence, such as
Reykjavik is in Iceland .
Give the parameter for the country a default value .
Call your function for three different cities, at least one of which is not in the
default country
✅ Solution Code:
def describe_city(city, country="Iceland"):
print(f"{city.title()} is in {country.title()}.")
# Call the function with different cities and countries
describe_city("Reykjavik") # Default country
describe_city("Paris", "France") # Different country
π§ Code Explanation:
-
Define the function with a default parameter:
The function
describe_city(city, country="Iceland")
is defined with two parameters:city
: Represents the name of the city.country="Iceland"
: The default value for the country is set to "Iceland".
-
Use the parameters:
Inside the function, the parameters
city
andcountry
are used to display a sentence indicating which country the city is located in. If no value is provided for thecountry
parameter when the function is called, the default value "Iceland" is used. -
Call the function with the default country:
The function is called with only the
city
parameter:describe_city("Reykjavik")
: Uses the default country "Iceland" and displays the sentence accordingly.
-
Call the function with a different country:
The function is called with both the
city
andcountry
parameters:describe_city("Paris", "France")
: Overrides the default country with "France" and displays the sentence accordingly.
π Output:
Reykjavik is in Iceland.
Paris is in France.
π 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