π Python Crash Course – Chapter 8: Functions – Exercise 8-6 Solution
Welcome to another solution from Python Crash Course by Eric Matthes.
π Exercise 8-6
Task:
Write a function called city_country() that takes in the name
of a city and its country . The function should return a string formatted like this:
"Santiago, Chile"
Call your function with at least three city-country pairs, and print the value
that’s returned
✅ Solution Code:
def city_country(city, country):
return f"{city.title()}, {country.title()}"
# Call the function with three city-country pairs
city1 = city_country("santiago", "chile")
city2 = city_country("paris", "france")
city3 = city_country("tokyo", "japan")
# Print the returned values
print(city1)
print(city2)
print(city3)
π§ Code Explanation:
-
Define the function:
The function
city_country(city, country)
is defined with two parameters:city
: Represents the name of the city.country
: Represents the name of the country.
-
Return a formatted string:
The function uses the
title()
method to capitalize the first letter of each word in the city and country names. It then returns a formatted string in the format"City, Country"
. -
Call the function with city-country pairs:
The function is called three times with different city-country pairs:
city_country("santiago", "chile")
: Returns"Santiago, Chile"
.city_country("paris", "france")
: Returns"Paris, France"
.city_country("tokyo", "japan")
: Returns"Tokyo, Japan"
.
-
Store and display the returned values:
The returned values from the function calls are stored in variables (
city1
,city2
,city3
) and then displayed. Each variable contains the formatted city-country string.
π Output:
Santiago, Chile
Paris, France
Tokyo, Japan
π 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