Python Functions and Modules
Python Functions
What are Functions?
Functions in Python are blocks of reusable code that perform a specific task. They allow you to break down your program into smaller, manageable pieces. Functions enhance code readability, promote reusability, and make your programs more organized.
Creating a Function
To define a function, use the def
keyword followed by the function name and parentheses. You can also include parameters (inputs) inside the parentheses. Here’s a simple example:
def greet():
print("Hello, World!")
# Call the function
greet()
print("Outside function")
In the above example:
- We’ve created a function named
greet()
. - When we call
greet()
, it prints “Hello, World!”. - The control then continues outside the function, and “Outside function” is printed.
Python Modules
What are Modules?
As your program grows, it may contain many lines of code. Instead of putting everything in a single file, you can use modules to separate code into separate files based on functionality. This keeps your code organized and easier to maintain.
A module is a file that contains code to perform a specific task. It can include variables, functions, classes, and more.
Creating a Module
Let’s create a simple module named example.py
. Save the following code in a file named example.py
:
# example.py
def add(a, b):
result = a + b
return result
In this module, we’ve defined a function add()
that takes two numbers and returns their sum.
Importing Modules
To use a module in your Python program, you need to import it. You can import your own user-defined modules or Python’s standard library modules.
Importing User-Defined Modules
Suppose you’ve created the example.py
module. To import it, use the import
keyword:
import example
# Access the function using the dot operator
result = example.add(4, 5)
print("Sum:", result)
Importing Python Standard Library Modules
Python’s standard library contains over 200 modules. For example, to get the value of π (pi), you can import the math
module:
import math
# Use math.pi to get the value of pi
print("The value of pi is", math.pi)
Renaming Modules
You can also rename modules for convenience:
import math as m
# Now use m.pi instead of math.pi
print("The value of pi is", m.pi)
Importing Specific Names
If you only need specific names from a module, use the from ... import
statement:
from math import pi
# Now you can directly use pi
print("The value of pi is", pi)
Remember, importing everything with the asterisk (*
) symbol is not recommended for good programming practice.
That’s it! You’ve discovered the power of Python functions and modules. They make your code cleaner, more reusable, and easier to maintain.
Python Basics Home Page [TOC] Python Conational Statements Python Data Structures