Python coding
53 subscribers
24 files
11 links
​A technical hub dedicated to Python programming, web development, and software engineering. Learn core syntax, build full-stack projects, and master backend development.
Download Telegram
Python coding
πŸš€ Python Tip #48: The decimal.Decimal Class Floating-point numbers are not always exact. This can lead to small rounding errors, especially in financial and scientific calculations. Python's Decimal class from the decimal module provides precise decimal…
🐍 Python Tip #49: The datetime Module

Working with dates and times is a common task in Python.

The datetime module allows you to create, manipulate, and format dates and times with ease.

---

Importing datetime

from datetime import datetime

---

Getting the Current Date and Time

from datetime import datetime

now = datetime.now()

print(now)

Output:

2026-07-08 14:30:15.123456

(The output will depend on the current date and time.)

---

Getting Individual Components

from datetime import datetime

now = datetime.now()

print(now.year)
print(now.month)
print(now.day)
print(now.hour)
print(now.minute)
print(now.second)

Example Output:

2026
7
8
14
30
15

---

Formatting Dates

Use the strftime() method to display dates in different formats.

from datetime import datetime

now = datetime.now()

print(now.strftime("%d/%m/%Y"))
print(now.strftime("%B %d, %Y"))
print(now.strftime("%I:%M %p"))

Example Output:

08/07/2026
July 08, 2026
02:30 PM

---

Creating a Specific Date

from datetime import datetime

birthday = datetime(2009, 11, 4)

print(birthday)

Output:

2009-11-04 00:00:00

---

Why use datetime?

βœ“ Work with dates and times easily
βœ“ Format dates in different styles
βœ“ Extract year, month, day, and time components
βœ“ Commonly used in web development, automation, logging, and scheduling

---

Challenge:

Create a datetime object for:

January 1, 2030

Then print it in the following format:

01 January 2030

using the strftime() method.
Python coding
🐍 Python Tip #49: The datetime Module Working with dates and times is a common task in Python. The datetime module allows you to create, manipulate, and format dates and times with ease. --- Importing datetime from datetime import datetime --- Getting…
πŸš€ Python Tip #50: The datetime.timedelta Class

The timedelta class from Python's datetime module represents a duration or difference between two dates or times.

It makes it easy to perform date and time arithmetic.

---

Importing timedelta

from datetime import datetime, timedelta

---

Adding Days

from datetime import datetime, timedelta

today = datetime.now()

future = today + timedelta(days=7)

print(future)

Output:

2026-07-15 14:30:15.123456

(The output depends on the current date and time.)

---

Subtracting Days

from datetime import datetime, timedelta

today = datetime.now()

past = today - timedelta(days=30)

print(past)

This returns the date 30 days before today.

---

Adding Hours and Minutes

from datetime import datetime, timedelta

now = datetime.now()

later = now + timedelta(hours=2, minutes=30)

print(later)

This calculates the date and time 2 hours and 30 minutes from now.

---

Finding the Difference Between Dates

from datetime import datetime

date1 = datetime(2026, 7, 1)
date2 = datetime(2026, 7, 15)

difference = date2 - date1

print(difference)
print(difference.days)

Output:

14 days, 0:00:00
14

The result is a timedelta object representing the time difference.

---

Why use timedelta?

βœ“ Easily add or subtract dates and times
βœ“ Calculate the difference between two dates
βœ“ Supports days, hours, minutes, seconds, and weeks
βœ“ Commonly used in scheduling, reminders, logging, and automation

---

Challenge:

Create a program that:

1. Gets today's date.
2. Calculates the date 100 days from today.
3. Prints both dates.
4. Displays the number of days between them.
Python coding
πŸš€ Python Tip #50: The datetime.timedelta Class The timedelta class from Python's datetime module represents a duration or difference between two dates or times. It makes it easy to perform date and time arithmetic. --- Importing timedelta from datetime…
πŸ’‘ Python Tip #51: The uuid Module

The uuid module generates Universally Unique Identifiers (UUIDs).

UUIDs are commonly used to create unique IDs for users, orders, files, API keys, and database records.

---

Importing uuid

import uuid

---

Generating a Random UUID

import uuid

unique_id = uuid.uuid4()

print(unique_id)

Example Output:

550e8400-e29b-41d4-a716-446655440000

Your output will be different every time because each UUID is randomly generated.

---

Converting a UUID to a String

import uuid

unique_id = uuid.uuid4()

print(str(unique_id))

Output:

550e8400-e29b-41d4-a716-446655440000

This is useful when storing UUIDs in databases or sending them through APIs.

---

Generating Multiple UUIDs

import uuid

for _ in range(3):
print(uuid.uuid4())

Example Output:

9b1deb4d-3b7d-4f47-bc2b-4e7f5f36c91e
b87d6b11-5c61-4e2a-a93e-91b7ef9d82a3
7db3d59f-0ec4-4b5e-8f5f-cd28bca1e75f

Each generated UUID is unique.

---

Using UUIDs as Dictionary Keys

import uuid

users = {}

user_id = uuid.uuid4()

users[user_id] = "Yehya"

print(users)

Output:

{
UUID('550e8400-e29b-41d4-a716-446655440000'): 'Yehya'
}

---

Why use uuid?

βœ“ Generates globally unique identifiers
βœ“ Prevents ID collisions
βœ“ No need for auto-incrementing numbers
βœ“ Commonly used in web development, databases, distributed systems, and REST APIs

---

Challenge:

Create a program that:

1. Generates 5 random UUIDs.
2. Stores them in a list.
3. Prints each UUID on a separate line.
4. Verifies that all generated UUIDs are unique.
Python coding
πŸ’‘ Python Tip #51: The uuid Module The uuid module generates Universally Unique Identifiers (UUIDs). UUIDs are commonly used to create unique IDs for users, orders, files, API keys, and database records. --- Importing uuid import uuid --- Generating a…
πŸš€ Python Tip #52: The enum.Enum Class

The Enum class from Python's enum module allows you to create a set of named constant values.

Enums make your code more readable, safer, and easier to maintain.

---

Importing Enum

from enum import Enum

---

Creating an Enum

from enum import Enum

class Status(Enum):
PENDING = 1
RUNNING = 2
COMPLETED = 3

print(Status.PENDING)

Output:

Status.PENDING

---

Accessing the Name and Value

from enum import Enum

class Status(Enum):
PENDING = 1
RUNNING = 2
COMPLETED = 3

print(Status.RUNNING.name)
print(Status.RUNNING.value)

Output:

RUNNING
2

---

Comparing Enum Members

from enum import Enum

class Color(Enum):
RED = 1
GREEN = 2
BLUE = 3

if Color.RED == Color.RED:
print("They are equal.")

Output:

They are equal.

Enums should be compared with other enum members, not with integers.

---

Looping Through an Enum

from enum import Enum

class Day(Enum):
MONDAY = 1
TUESDAY = 2
WEDNESDAY = 3

for day in Day:
print(day.name, day.value)

Output:

MONDAY 1
TUESDAY 2
WEDNESDAY 3

---

Why use Enum?

βœ“ Makes code more readable
βœ“ Replaces "magic numbers" with meaningful names
βœ“ Prevents invalid constant values
βœ“ Commonly used for application states, user roles, HTTP status codes, and configuration options

---

Challenge:

Create an enum named:

TrafficLight

with the following members:

RED = 1
YELLOW = 2
GREEN = 3

Then:

1. Print the name and value of GREEN.
2. Loop through all members and print their names and values.
Python coding
πŸš€ Python Tip #52: The enum.Enum Class The Enum class from Python's enum module allows you to create a set of named constant values. Enums make your code more readable, safer, and easier to maintain. --- Importing Enum from enum import Enum --- Creating…
🐍 Python Tip #53: The secrets Module

The secrets module is designed for generating cryptographically secure random numbers, tokens, and passwords.

Unlike the random module, secrets should be used for security-related tasks.

---

Importing secrets

import secrets

---

Generating a Secure Random Number

import secrets

number = secrets.randbelow(100)

print(number)

Output:

42

The output will be a secure random integer between 0 and 99.

---

Choosing a Random Item

import secrets

colors = ["Red", "Green", "Blue", "Black"]

choice = secrets.choice(colors)

print(choice)

Output:

Green

A random item is selected securely.

---

Generating a Secure Token

import secrets

token = secrets.token_hex(16)

print(token)

Example Output:

9f8d7c2b1a4e5f6d8c9b0a1d2e3f4a5b

This creates a secure hexadecimal token with 16 random bytes.

---

Generating a Strong Password

import secrets
import string

characters = string.ascii_letters + string.digits + string.punctuation

password = "".join(
secrets.choice(characters)
for _ in range(12)
)

print(password)

Example Output:

A#7mP!2xQ9@k

A different password will be generated each time.

---

Why use secrets?

βœ“ Generates cryptographically secure random values
βœ“ More secure than the random module for sensitive data
βœ“ Ideal for passwords, API keys, authentication tokens, and session IDs
βœ“ Recommended for security-related applications

---

Challenge:

Create a program that:

1. Generates a secure password with 16 characters.
2. The password should contain:
- Uppercase letters
- Lowercase letters
- Numbers
- Special characters
3. Print the generated password.
Python coding
🐍 Python Tip #53: The secrets Module The secrets module is designed for generating cryptographically secure random numbers, tokens, and passwords. Unlike the random module, secrets should be used for security-related tasks. --- Importing secrets import…
πŸš€ Python Tip #54: The dataclasses Module

The dataclasses module helps you create classes that mainly store data without writing repetitive boilerplate code.

It automatically generates methods such as __init__(), __repr__(), and __eq__().

---

Importing dataclass

from dataclasses import dataclass

---

Creating a Data Class

from dataclasses import dataclass

@dataclass
class Student:
name: str
age: int
grade: str

student = Student("Ali", 18, "A")

print(student)

Output:

Student(name='Ali', age=18, grade='A')

Notice that Python automatically created the constructor and the string representation.

---

Accessing Attributes

from dataclasses import dataclass

@dataclass
class Student:
name: str
age: int

student = Student("Yehya", 16)

print(student.name)
print(student.age)

Output:

Yehya
16

---

Comparing Objects

Data classes automatically support equality comparison.

from dataclasses import dataclass

@dataclass
class Book:
title: str
pages: int

book1 = Book("Python", 300)
book2 = Book("Python", 300)

print(book1 == book2)

Output:

True

---

Using Default Values

from dataclasses import dataclass

@dataclass
class User:
name: str
country: str = "Ethiopia"

user = User("Yehya")

print(user)

Output:

User(name='Yehya', country='Ethiopia')

If no country is provided, "Ethiopia" is used by default.

---

Why use dataclasses?

βœ“ Eliminates repetitive boilerplate code
βœ“ Automatically generates constructors and other useful methods
βœ“ Improves code readability and maintainability
βœ“ Commonly used in APIs, configuration objects, and data models

---

Challenge:

Create a data class named:

Car

with the following fields:

brand
model
year

Then:

1. Create two identical Car objects.
2. Print one of them.
3. Check whether the two objects are equal.
Python coding
πŸš€ Python Tip #54: The dataclasses Module The dataclasses module helps you create classes that mainly store data without writing repetitive boilerplate code. It automatically generates methods such as __init__(), __repr__(), and __eq__(). --- Importing…
πŸ’‘ Python Tip #55: The pathlib Module

The pathlib module provides an object-oriented way to work with files and directories.

It is the modern replacement for using os.path in Python.

---

Importing Path

from pathlib import Path

---

Creating a Path Object

from pathlib import Path

file = Path("example.txt")

print(file)

Output:

example.txt

---

Checking if a File Exists

from pathlib import Path

file = Path("example.txt")

print(file.exists())

Output:

True

or

```python
False

depending on whether the file exists.

---

Getting File Information

python
from pathlib import Path

file = Path("report.pdf")

print(file.name)
print(file.stem)
print(file.suffix)

Output:

python
report.pdf
report
.pdf

- `name` returns the full filename.
- `stem` returns the filename without the extension.
- `suffix` returns the file extension.

---

Creating a Directory

python
from pathlib import Path

folder = Path("Projects")

folder.mkdir(exist_ok=True)

print("Folder created.")

The `exist_ok=True` argument prevents an error if the folder already exists.

---

Listing Files in a Directory

python
from pathlib import Path

folder = Path(".")

for file in folder.iterdir():
print(file)

This prints every file and folder in the current directory.

---

Why use `pathlib`?

βœ“ Modern and easy-to-read syntax
βœ“ Works across Windows, macOS, and Linux
βœ“ Simplifies file and directory operations
βœ“ Commonly used in automation, scripting, web development, and data science

---

Challenge:

Create a program that:

1. Creates a folder named:

python
PythonProjects

2. Creates a `Path` object for a file named:

python
notes.txt
`

inside that folder.

3. Print:

- The full path
- The file name
- The file extension
Python coding
πŸ’‘ Python Tip #55: The pathlib Module The pathlib module provides an object-oriented way to work with files and directories. It is the modern replacement for using os.path in Python. --- Importing Path from pathlib import Path --- Creating a Path Object…
πŸš€ Python Tip #56: The logging Module

The logging module provides a flexible way to record messages while your program is running.

Unlike print(), logging allows you to categorize messages by importance and save them to files.

---

Importing logging

import logging

---

Basic Logging

import logging

logging.basicConfig(level=logging.INFO)

logging.info("Program started.")

Output:

INFO:root:Program started.

---

Logging Levels

Python provides several logging levels.

import logging

logging.basicConfig(level=logging.DEBUG)

logging.debug("Debug message")
logging.info("Information message")
logging.warning("Warning message")
logging.error("Error message")
logging.critical("Critical error")

Output:

DEBUG:root:Debug message
INFO:root:Information message
WARNING:root:Warning message
ERROR:root:Error message
CRITICAL:root:Critical error

---

Logging to a File

Instead of displaying messages in the terminal, you can save them to a file.

import logging

logging.basicConfig(
filename="app.log",
level=logging.INFO
)

logging.info("Application started.")
logging.warning("Low disk space.")

A file named app.log will be created containing the log messages.

---

Formatting Log Messages

import logging

logging.basicConfig(
level=logging.INFO,
format="%(asctime)s - %(levelname)s - %(message)s"
)

logging.info("User logged in.")

Example Output:

2026-07-22 10:15:30 - INFO - User logged in.

---

Why use logging?

βœ“ Better than using print() for debugging
βœ“ Supports different log levels
βœ“ Can save logs to files automatically
βœ“ Essential for professional applications, APIs, and server programs

---

Challenge:

Create a program that:

1. Configures logging to save messages to a file named:

program.log

2. Logs the following messages:

INFO: Program started
WARNING: Low memory
ERROR: File not found

3. Open the log file and verify that all three messages were saved.
Python coding
πŸš€ Python Tip #56: The logging Module The logging module provides a flexible way to record messages while your program is running. Unlike print(), logging allows you to categorize messages by importance and save them to files. --- Importing logging import…
🐍 Python Tip #57: The argparse Module

The argparse module allows your Python programs to accept command-line arguments.

It is commonly used to build professional command-line applications and automation scripts.

---

Importing argparse

import argparse

---

Basic Example

import argparse

parser = argparse.ArgumentParser()

parser.add_argument("name")

args = parser.parse_args()

print(f"Hello, {args.name}!")

Running the program:

python app.py Yehya

Output:

Hello, Yehya!

---

Adding Optional Arguments

Optional arguments start with --.

import argparse

parser = argparse.ArgumentParser()

parser.add_argument("--age", type=int)

args = parser.parse_args()

print(args.age)

Run:

```bash
python app.py --age 16

Output:

python
16

---

Providing Default Values

python
import argparse

parser = argparse.ArgumentParser()

parser.add_argument("--country", default="Ethiopia")

args = parser.parse_args()

print(args.country)

Run:

bash
python app.py

Output:

python
Ethiopia

---

Displaying Help

`argparse` automatically generates a help message.

python
import argparse

parser = argparse.ArgumentParser(
description="Simple Calculator"
)

parser.add_argument("--num", type=int)

parser.parse_args()

Run:

bash
python app.py --help

Example Output:

text
usage: app.py [-h] [--num NUM]

Simple Calculator

options:
-h, --help Show this help message and exit
--num NUM Enter a number

---

Why use `argparse`?

βœ“ Makes command-line programs easy to use
βœ“ Automatically validates user input
βœ“ Generates built-in help messages
βœ“ Widely used in automation, DevOps, and professional Python tools

---

Challenge:

Create a program that accepts the following command-line arguments:

text
--name
--age
--country

Then print the information in this format:

text
Name: Yehya
Age: 16
Country: Ethiopia
`

If `--country` is not provided, use `"Unknown"` as the default value.
Python coding
🐍 Python Tip #57: The argparse Module The argparse module allows your Python programs to accept command-line arguments. It is commonly used to build professional command-line applications and automation scripts. --- Importing argparse import argparse…
πŸš€ Python Tip #58: The tempfile Module

The tempfile module allows you to create temporary files and directories that are automatically cleaned up when no longer needed.

It is useful for testing, data processing, and handling temporary data.

---

Importing tempfile

import tempfile

---

Creating a Temporary File

import tempfile

with tempfile.TemporaryFile() as file:
file.write(b"Hello, Python!")
file.seek(0)

print(file.read())

Output:

b'Hello, Python!'

The file is automatically deleted after the with block ends.

---

Creating a Temporary Directory

import tempfile

with tempfile.TemporaryDirectory() as folder:
print(folder)

Example Output:

C:\Users\User\AppData\Local\Temp\tmpabc123

The directory is automatically removed when you're done.

---

Creating a Named Temporary File

import tempfile

with tempfile.NamedTemporaryFile(mode="w+", delete=True) as file:
file.write("Temporary data")
file.seek(0)

print(file.read())

Output:

Temporary data

Unlike TemporaryFile(), a NamedTemporaryFile has a visible filename while it exists.

---

Getting the File Name

import tempfile

with tempfile.NamedTemporaryFile() as file:
print(file.name)

Example Output:

C:\Users\User\AppData\Local\Temp\tmpx9z4ab.tmp

The exact path depends on your operating system.

---

Why use tempfile?

βœ“ Automatically cleans up temporary files and folders
βœ“ Prevents clutter on your system
βœ“ Securely creates temporary storage
βœ“ Commonly used in testing, file processing, and automation

---

Challenge:

Create a program that:

1. Creates a temporary file.
2. Writes the text:

Learning Python is fun!

3. Reads the contents back and prints them.
4. Lets Python automatically delete the file when the program finishes.
Python coding
πŸš€ Python Tip #58: The tempfile Module The tempfile module allows you to create temporary files and directories that are automatically cleaned up when no longer needed. It is useful for testing, data processing, and handling temporary data. --- Importing…
πŸ’‘ Python Tip #59: The shutil Module

The shutil module provides high-level file and directory operations.

It makes it easy to copy, move, rename, and delete files and folders.

---

Importing shutil

import shutil

---

Copying a File

import shutil

shutil.copy("source.txt", "backup.txt")

print("File copied successfully.")

This creates a copy of source.txt named backup.txt.

---

Moving or Renaming a File

import shutil

shutil.move("old_file.txt", "new_file.txt")

print("File moved or renamed.")

If the destination is in another folder, the file is moved. If it's in the same folder with a different name, it is renamed.

---

Copying an Entire Directory

import shutil

shutil.copytree("Project", "Project_Backup")

print("Directory copied.")

This copies the entire Project folder, including all its files and subfolders.

---

Deleting a Directory

import shutil

shutil.rmtree("Old_Project")

print("Directory deleted.")

Warning: rmtree() permanently deletes the directory and everything inside it.

---

Getting Disk Usage

import shutil

usage = shutil.disk_usage(".")

print(f"Total: {usage.total} bytes")
print(f"Used: {usage.used} bytes")
print(f"Free: {usage.free} bytes")

Example Output:

Total: 512110190592 bytes
Used: 301245964288 bytes
Free: 210864226304 bytes

---

Why use shutil?

βœ“ Copy, move, and rename files easily
βœ“ Copy or remove entire directories
βœ“ Check disk usage information
βœ“ Commonly used in backup tools, automation scripts, and file management applications

---

Challenge:

Create a program that:

1. Creates a copy of a file named:

notes.txt

2. Rename the copied file to:

notes_backup.txt

3. Print a success message after each operation.
Python coding
πŸ’‘ Python Tip #59: The shutil Module The shutil module provides high-level file and directory operations. It makes it easy to copy, move, rename, and delete files and folders. --- Importing shutil import shutil --- Copying a File import shutil shut…
πŸš€ Python Tip #60: The contextlib Module

The contextlib module provides utilities for working with context managers.

It helps you manage resources such as files, database connections, and locks safely and cleanly.

---

Importing contextmanager

from contextlib import contextmanager

---

Creating a Custom Context Manager

from contextlib import contextmanager

@contextmanager
def my_context():
print("Entering context...")
yield
print("Exiting context...")

with my_context():
print("Inside the block")

Output:

Entering context...
Inside the block
Exiting context...

The code before yield runs when entering the block, and the code after yield runs when exiting it.

---

Managing Resources

from contextlib import contextmanager

@contextmanager
def open_file(filename):
file = open(filename, "w")
try:
yield file
finally:
file.close()

with open_file("example.txt") as f:
f.write("Hello, Python!")

The file is automatically closed after leaving the with block.

---

Ignoring Exceptions

Use suppress() to ignore specific exceptions.

from contextlib import suppress

with suppress(FileNotFoundError):
open("missing_file.txt")

If the file doesn't exist, the program continues without raising an error.

---

Redirecting Output

You can temporarily redirect printed output.

from contextlib import redirect_stdout

with open("output.txt", "w") as file:
with redirect_stdout(file):
print("Hello, Python!")

The text is written to output.txt instead of appearing in the terminal.

---

Why use contextlib?

βœ“ Create custom context managers easily
βœ“ Automatically manage resources
βœ“ Simplify exception handling
βœ“ Commonly used in file handling, testing, logging, and resource management

---

Challenge:

Create a custom context manager that:

1. Prints:

Starting task...

before entering the with block.

2. Prints:

Task completed.

after leaving the with block.

3. Inside the with block, print:

Learning Python Context Managers!
Python coding pinned Β«Introduction to Programming with Python --- What is Python? Python is a popular programming language created by Guido van Rossum in 1991. It is known for: - Simplicity - Readability - Flexibility - Powerful libraries Python is beginner-friendly while…»