What are modules in Python example?

Bette 104 Published: 08/07/2024

What are modules in Python example?

I'll respond in English this time!

In Python, a module is a file that contains a collection of related functions, classes, and variables. Modules are used to organize code into logical units and make it reusable. Think of them as individual LEGO bricks that can be combined to build larger structures.

Here's an example of how you might structure a simple math module:

# mymath.py

def add(x, y):

return x + y

def subtract(x, y):

return x - y

def multiply(x, y):

return x * y

def divide(x, y):

if y == 0:

raise ValueError("Cannot divide by zero!")

return x / y

This module contains four functions: add, subtract, multiply, and divide. Each function takes two arguments, x and y, and returns the result of a mathematical operation.

To use this module in another Python script, you would import it using the import statement:

# main.py

import mymath

print(mymath.add(2, 3)) # prints: 5

print(mymath.subtract(5, 3)) # prints: 2

print(mymath.multiply(4, 5)) # prints: 20

try:

print(mymath.divide(10, 0))

except ValueError as e:

print(e) # prints: Cannot divide by zero!

As you can see, the mymath module provides a way to encapsulate related code and reuse it in other parts of your program.

Python comes with many built-in modules that you can use, such as:

math: contains mathematical functions like sin, cos, tan, etc. random: allows you to generate random numbers. time: provides functions for working with dates and times.

You can also create your own custom modules by defining a Python file and importing it into another script. This is a great way to organize your code and make it reusable!

I hope this helps illustrate the concept of modules in Python!

Python modules example w3schools

I'd be happy to provide information on Python modules and examples from W3Schools.

W3Schools is a popular online platform that provides tutorials, examples, and reference materials for web development, including HTML, CSS, JavaScript, PHP, and more. However, in this context, I will focus on Python modules and provide examples from W3Schools.

Python is a high-level programming language known for its simplicity and readability. It is often used for web development, scientific computing, data analysis, artificial intelligence, and more. The standard library of Python includes various modules that make it easy to perform tasks such as file input/output, network communication, database interactions, and more.

Here are some examples of Python modules and their uses:

os module: This module provides a way to interact with the operating system, allowing you to perform tasks such as creating files, directories, and processes.

Example:

import os
Create a new directory

os.mkdir("new_directory")

List the contents of the current directory

print(os.listdir())

Remove the directory

os.rmdir("new_directory")

requests module: This module allows you to send HTTP requests and interact with web services.

Example:

import requests
Send a GET request to fetch data from a URL

response = requests.get("https://www.example.com")

Print the status code of the response

print(response.status_code)

Parse JSON data from the response

data = response.json()

Print the extracted data

print(data)

datetime module: This module provides classes for manipulating dates and times.

Example:

from datetime import datetime
Get the current date and time

now = datetime.now()

print(now)

Format the date and time as a string

formatted_date = now.strftime("%Y-%m-%d %H:%M:%S")

print(formatted_date)

random module: This module allows you to generate random numbers.

Example:

import random
Generate a random integer between 1 and 100

random_integer = random.randint(1, 100)

print(random_integer)

Generate a list of random floating-point numbers

random_floats = [random.random() for _ in range(10)]

print(random_floats)

math module: This module provides mathematical functions such as sin(), cos(), and tan().

Example:

import math
Calculate the sine, cosine, and tangent of an angle

angle = 30

sin_angle = math.sin(math.radians(angle))

cos_angle = math.cos(math.radians(angle))

tan_angle = math.tan(math.radians(angle))

print(f"sin({angle}) = {sin_angle}")

print(f"cos({angle}) = {cos_angle}")

print(f"tan({angle}) = {tan_angle}")

These are just a few examples of the many Python modules and their uses. I hope this helps you get started with exploring the world of Python programming!