Python Tutorial Part 4: Functions and Modules

In this article, we'll explore functions and modules in Python.

Functions

A function is a block of reusable code that performs a specific task. You can define your own functions in Python using the def keyword.

Example:

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

greet("Alice")
greet("Bob")

In this example, we define a function named greet that takes a parameter name and prints a personalized greeting message. We then call this function with different names.

Modules

A module is a file containing Python code that can be imported and used in other Python programs. Python comes with a standard library that includes many useful modules.

Example:

# Import the math module
import math



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

In this example, we import the math module and use its sqrt function to calculate the square root of a number.

Conclusion

Now you understand how to define and use functions as well as import modules in Python. In the next article, we'll cover object-oriented programming (OOP) concepts.

Previous Post Next Post