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

“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