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

 

πŸ“˜ Python Crash Course – Chapter 8: Functions – Exercise 8-16 Solution

Welcome to another solution from Python Crash Course by Eric Matthes.


πŸ“ Exercise 8-16

Task:
Using a program you wrote that has one function in it, store that function in a separate file . Import the function into your main program file, and call the function using each of these approaches:
- import module_name
- from module_name import function_name
- from module_name import function_name as fn
- import module_name as mn
- from module_name import *

✅ Solution Code:

helper_8_15.py


# this help to solve the exercise 8.15 and 8.16

def your_name(first, last):
    full_name = f"{first} {last}"
    return f'Your name is :{full_name}'

exercise_8_16.py


# Importing the function from the helper file
import helper_8_15
print(helper_8_15.your_name("John", "Doe"))

# Importing the function using different approaches
from helper_8_15 import your_name
print(your_name("Jane", "Smith"))


from helper_8_15 import your_name as fn
print(fn("Alice", "Johnson"))

import helper_8_15 as mn
print(mn.your_name("Bob", "Brown"))

from helper_8_15 import *
print(your_name("Charlie", "Davis"))

🧠 Code Explanation:

  1. Import the entire module:

    The statement import helper_8_15 imports the entire module. Functions from the module are accessed using dot notation, such as helper_8_15.your_name().

  2. Import a specific function:

    The statement from helper_8_15 import your_name imports only the your_name function from the module. The function can then be called directly without using dot notation.

  3. Import a function with an alias:

    The statement from helper_8_15 import your_name as fn imports the your_name function and assigns it an alias fn. The function can then be called using the alias, such as fn().

  4. Import the module with an alias:

    The statement import helper_8_15 as mn imports the entire module and assigns it an alias mn. Functions from the module are accessed using the alias, such as mn.your_name().

  5. Import all functions from the module:

    The statement from helper_8_15 import * imports all functions from the module. Functions can then be called directly without using dot notation or aliases.

πŸ” Output:


Your name is :John Doe
Your name is :Jane Smith
Your name is :Alice Johnson
Your name is :Bob Brown
Your name is :Charlie Davis

πŸ“š Related Exercises from Chapter 8:


“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