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

 

πŸ“˜ 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:

  1. 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".
  2. Use the parameters:

    Inside the function, the parameters city and country are used to display a sentence indicating which country the city is located in. If no value is provided for the country parameter when the function is called, the default value "Iceland" is used.

  3. 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.
  4. Call the function with a different country:

    The function is called with both the city and country 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:


πŸ”— 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