Lesson 7: Functions and Modules | Coding Class Series
Introduction
Welcome to Lesson 7!
In this lesson, we will learn about functions and modules in Python. Functions allow you to reuse code, while modules help you organize your programs efficiently.
1. Functions
A function is a block of code that performs a specific task and can be reused multiple times.
Syntax:
def greet(name):
print(f"Hello, {name}!")
greet("Alice") # Output: Hello, Alice!
Key Points:
- Functions start with the
defkeyword. - Arguments can be passed inside parentheses.
returnkeyword is used to give back a result.
Example with Return:
def add(a, b):
return a + b
result = add(5, 3)
print(result) # Output: 8
2. Modules
A module is a file containing Python definitions and functions.
You can import modules to use their functions in your program.
Importing a module:
import math
print(math.sqrt(16)) # Output: 4.0
From module import specific function:
from math import pow
print(pow(2, 3)) # Output: 8.0
Creating your own module:
- Create a file
my_module.py:
def welcome():
print("Welcome to my module!")
- Import in another file:
import my_module
my_module.welcome() # Output: Welcome to my module!
3. Advantages of Functions and Modules
- Reusability: Write once, use multiple times.
- Organization: Keeps code clean and structured.
- Efficiency: Saves time and reduces errors.
- Scalability: Easier to maintain and expand large programs.
Practice Exercises
- Create a function
multiply(a, b)that returns the product of two numbers. - Write a function that takes a list of numbers and returns the largest number.
- Create a module
math_utils.pywith a functionsquare(n)that returns the square of a number. Import it and test. - Use the
randommodule to generate 5 random numbers between 1 and 50.
No comments:
Post a Comment