Functions are reusable blocks of code that perform specific tasks, while modules are collections of functions and variables that can be imported and used in your code.
Functions are defined using the def
keyword in Python. They allow us to organize our code into logical blocks and perform specific tasks. Here's the basic syntax for defining a function:
def function_name(parameter1, parameter2, ...):
# code block
# perform some operations
return result
Let's see an example:
# Example of a function
def greet(name):
message = "Hello, " + name + "!"
return message
# Calling the function
print(greet("Alice"))
In this example, we defined a function called greet
that takes a name
parameter. Inside the function, we create a message by concatenating the name
parameter with a greeting. The return
statement is used to return the result from the function. We then call the function greet("Alice")
and print the returned message.
Functions can accept parameters, which are values passed into the function when it is called. Parameters allow us to provide inputs to functions and make them more flexible. Functions can also return values using the return
statement.
# Example of a function with parameters and return value
def add_numbers(a, b):
result = a + b
return result
# Calling the function
sum = add_numbers(3, 5)
print(sum) # Output: 8
In this example, the function add_numbers
takes two parameters, a
and b
, and returns their sum. We call the function with the arguments 3
and 5
, and the returned result is assigned to the variable sum
.
Modules are files containing Python code that can be used in other programs. Python provides a rich set of built-in modules that offer additional functionality beyond what is available in the standard Python library. We can import modules using the import
statement.
# Example of importing and using a module
import math
radius = 5
area = math.pi * math.pow(radius, 2)
print(area) # Output: 78.53981633974483
In this example, we import the math
module, which provides various mathematical functions and constants. We use the math.pi
constant and the math.pow()
function to calculate the area of a circle with a given radius.
You can also import specific functions or variables from a module:
# Example of importing specific functions from a module
from math import sqrt, pow
result = pow(2, 3)
print(result) # Output: 8.0
result = sqrt(25)
print(result) # Output: 5.0
In this case, we import only the sqrt
and pow
functions from the math
module, allowing us to use them directly without referencing the module name.