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

 

📘 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:

  1. 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.
  2. 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".

  3. 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".
  4. 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:


🔗 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