Introduction to functions and modules
Functions allow you to:
- Break big problems into smaller, manageable pieces
- Reuse code without copying and pasting
- Test parts of your program independently and debug it more easily
Modules allow you to:
- Keep your code organized and manageable
- Reuse code across different projects
- Share code with others
What is a function?
A function is a named block of code that performs a specific task. Functions help you organize your code, avoid repetition, and make your programs easier to read and maintain (you can fix a mistake once and it will fix it wherever the function is invoked).
Example:
Defining and calling functions
- Use the
defkeyword to define a function - Give your function a name (by convention use lowercase and underscores)
- Use parentheses
()for parameters (input variables) - End the definition with a colon
: - Indent the code inside the function
Example:
Parameters and arguments
# Declare function add, which takes in two parameters, a and b
def add(a, b):
return a + b
result = add(3, 5) # When calling the function, the parameters now have values
print(result) # Output: 8
- Parameters are variables listed in the function definition (
a,babove). - Arguments are the actual values you pass when calling the function (
3,5above).
Return values
- Use
returnto send a value back from the function. - If you don’t use
return, the function returnsNoneby default.
Example:
def square(x):
return x * x
print(square(4)) # Output: 16
This gives the output:
16
But this:
def square(x):
x * x
print(square(4)) # Output: None
gives the output:
None
What is a module?
A module is a file containing Python code (functions, variables, classes) that you can use in other programs. Modules help you organize large projects by splitting code into multiple files.
Modules allow you to:
- Keep your code organized and manageable
- Reuse code across different projects
- Share code with others
Example:
Suppose you have a file called calculator.py:
# calculator.py
def square(x):
return x * x
This file can be accessed by another python file as the calculator module.
import calculator
print(calculator.square(4)) # Output: 16
This alls the square(x) function declared in calculator.py using the full reference preceded by calculator: calculator.square().
Importing modules
There are three ways to import a module and its functions:
- Use
import module_nameto bring in a module. Then to call a function, you usemodule_name.function_name() - Use
import module_name as aliasto give a module a different name (often something shorter or more understandable). Then to call the function, you usealias.function_name() - Use
from module_name import function_nameto import specific functions. Then to call the function, you simply usefunction_name() - Use
from module_name import function_name as aliasto import specific functions and give them a different name
For example, to use the square(x) function declared in calculator.py, you can either use:
import calculator
print(calculator.square(4)) # Output: 16
or with an alias:
import calculator as calc
print(calc.square(4)) # Output: 16
or with the specific function imported, so you can simply use square()
from calculator import square
print(square(4)) # Output: 16
or with a specific function alias
from calculator import square as sq
print(sq(4)) # Output: 16
Using third-party libraries
A library is a collection of modules written by others that you can use in your projects. Importing a library uses the same syntax as importing a module.
For example, this code imports a third-party library called tkinter, a library for building graphical user interfaces (GUIs)
Example:
# Both use the same import syntax
import calculator # Import a single module (one file)
import tkinter # Import a library (many files/modules)
window = tk.Tk()
window.title("My App")
window.mainloop()
A library is essentially a folder containing multiple modules:
tkinter/ # Library (folder)
├── __init__.py # Makes it a package
├── dialog.py # Module within the library
├── font.py # Another module
└── messagebox.py # Another module
As well as importing the whole library (as above), you can also import specific modules from it:
from tkinter import messagebox
