Beginner’s Guide to Python – Prerequisite for Mastering Machine Learning
About Lesson

Functions and modules are essential concepts in Python that allow you to organize and reuse code more effectively.

Functions

A function is a block of reusable code that performs a specific task. Functions can take input parameters and return a result. Here’s an example of a simple function:

python
def greet(name):
print("Hello, " + name + "!")

This function takes a parameter name and prints a greeting message.

You can call this function and pass an argument like this:

python
greet("Alice")

This will print “Hello, Alice!”.

Modules

A module is a file containing Python code. It can define functions, classes, and variables that can be reused in other Python files. You can create your own modules or use built-in modules provided by Python.

To use a module in your Python program, you need to import it using the import statement. Here’s an example:

python
import math

# Calculate the square root of a number
result = math.sqrt(25)

print(result)

This will print 5.0, which is the square root of 25.

Understanding how to define and use functions and modules is essential for writing modular and reusable Python code. In the next chapter, we’ll explore data structures such as lists, tuples, and dictionaries.

Join the conversation