Skip to content

Archive

Python

119 articles
Python Updated 02 Sep 2025 2 min read

Understanding Conditional Expressions in Python

Python does not use the condition ? a : b syntax found in languages such as C or JavaScript. Instead, it provides a conditional expression that reads naturally from left to right. Basic Syntax value_if_true if condition else value_if_false For example:

Python Updated 02 Sep 2025 2 min read

Understanding `@staticmethod` vs `@classmethod` in Python

Python provides @staticmethod and @classmethod for methods that do not operate on one specific instance. They look similar at first, but they receive different context and solve different problems. @staticmethod A static method receives no implicit self or cls argument: class Temperature: @staticmethod def celsius_to_fahrenheit(value): return value * 9 / 5 + 32 print(Temperature.celsius_to_fahrenheit(20)) Use a static method when a function logically belongs in the class namespace but does not need instance or class state.

Python Updated 02 Sep 2025 2 min read

Understanding `__str__` vs `__repr__` in Python

Python provides __str__() and __repr__() so classes can control how their instances appear as text. They serve related but different audiences. __str__: Human-Friendly Output str(obj) and usually print(obj) use __str__(): class Person: def __init__(self, name, age): self.name = name self.age = age def __str__(self): return f"{self.name}, age {self.age}" person = Person("Alice", 30) print(person) Output:

Python Updated 02 Sep 2025 2 min read

Understanding `__init__.py` in Python

The __init__.py file is commonly used to define a regular Python package and control what happens when that package is imported. It can be empty, expose a package-level API, define metadata, or run lightweight initialization code. 1. A Basic Package Consider this structure: my_package/ ├── __init__.py ├── module1.py └── module2.py With __init__.py present, my_package is a regular package and its modules can be imported normally:

Python Updated 02 Sep 2025 2 min read

Merging Multiple Dictionaries in Python

Combining dictionaries is common when assembling configuration, request data, defaults, or results from multiple sources. Python provides several approaches, and the right one depends on the Python version and whether you want to mutate an existing dictionary. 1. Dictionary Union with | (Python 3.9+) Modern Python supports the dictionary union operator: dict1 = {"a": 1, "b": 2} dict2 = {"b": 3, "c": 4} dict3 = {"d": 5} merged = dict1 | dict2 | dict3 print(merged) Output:

Python Updated 02 Sep 2025 2 min read

How to Use a Global Variable Inside a Python Function

Python variables follow scope rules that determine where a name can be read or assigned. A module-level variable can be read inside a function, but assigning to that same name requires special handling. Reading a Global Variable A function can read a module-level variable without the global keyword: app_name = "Nalar" def print_app_name(): print(app_name) print_app_name() Because the function does not assign to app_name, Python resolves the name from the enclosing module scope.

Python Updated 02 Sep 2025 2 min read

How to List Files in a Directory with Python

Listing files in a directory is a common Python task for automation, data processing, uploads, and filesystem utilities. The standard library provides several good approaches. 1. os.listdir() os.listdir() returns names for both files and subdirectories, so filter the results when you need only regular files: import os def list_files(directory): try: entries = os.listdir(directory) return [ name for name in entries if os.path.isfile(os.path.join(directory, name)) ] except FileNotFoundError: return [] 2. os.scandir() os.scandir() returns DirEntry objects that can expose file-type information efficiently:

Python Updated 02 Sep 2025 2 min read

How to Flatten a List of Lists in Python

Python lists can contain other lists, which is useful for representing grouped or nested data. When you need a single sequence instead, you can flatten the nested structure in several ways. 1. Flatten One Level with a List Comprehension For a list where every top-level item is another list: nested_list = [[1, 2, 3], [4, 5], [6, 7, 8]] flat_list = [item for sublist in nested_list for item in sublist] print(flat_list) Output:

Python Updated 02 Sep 2025 1 min read

How to Check for a Specific Key in a Python Dictionary

Python dictionaries store key-value pairs and provide efficient key lookup. Before reading an optional key, you may want to check whether it exists. 1. Use in The recommended approach is the membership operator: my_dict = {"name": "Alice", "age": 30, "city": "New York"} if "name" in my_dict: print("The key exists.") else: print("The key does not exist.") This checks keys directly and clearly expresses the intent.

Python Updated 02 Sep 2025 2 min read

Check Whether a Key Exists in a Python Dictionary

Python dictionaries provide fast key-based lookup, and checking whether a key exists is a common operation. Use the in Operator The clearest and most idiomatic solution is: my_dict = {"name": "Alice", "age": 30, "city": "New York"} if "name" in my_dict: print("The key 'name' exists.") else: print("The key 'name' does not exist.") Membership tests on a dictionary check keys by default.

Python Updated 02 Sep 2025 2 min read

Catching Multiple Exceptions in Python

Python lets one except clause handle several exception types when they should receive the same response. This keeps error handling concise without hiding unrelated failures. Catch Several Exception Types Place the exception classes in a tuple: try: value = int(user_input) result = 100 / value except (ValueError, ZeroDivisionError) as exc: print(f"Invalid input: {exc}") ValueError handles non-numeric input, while ZeroDivisionError handles zero.

Data Science Updated 02 Sep 2025 2 min read

Working with Pandas: A Beginner Guide

Pandas is a widely used Python library for tabular data manipulation and analysis. This guide covers a few everyday DataFrame operations: renaming columns, adding and updating rows, deleting data, sorting, and filtering. Install Pandas python -m pip install pandas Create a DataFrame import pandas as pd df = pd.DataFrame( { "Name": [ "Braund, Mr. Owen Harris", "Allen, Mr. William Henry", "Bonnell, Miss. Elizabeth", ], "Age": [22, 35, 58], "Sex": ["male", "male", "female"], } ) Rename a Column df = df.rename(columns={"Sex": "Gender"}) Returning a new DataFrame instead of relying on inplace=True often makes transformation pipelines easier to reason about.

Data Science Updated 02 Sep 2025 2 min read

Working with CSV Files in Pandas

CSV (Comma-Separated Values) is a common format for storing and exchanging tabular data. Pandas makes it straightforward to export a DataFrame to CSV and load CSV data back into a DataFrame. Install Pandas If Pandas is not installed yet: python -m pip install pandas Using python -m pip helps ensure that pip belongs to the Python interpreter you intend to use.

Python Updated 02 Sep 2025 2 min read

Understanding Tuples in Python: A Practical Guide

A tuple is an ordered Python collection whose item references cannot be reassigned after creation. Tuples are useful for fixed groups of related values, function return values, dictionary keys when their contents are hashable, and lightweight records. Create Tuples coordinates = (10, 20) colors = ("red", "green", "blue") The comma is what creates a tuple, not the parentheses alone. A one-item tuple therefore needs a trailing comma:

Python Updated 02 Sep 2025 3 min read

Sets in Python: A Practical Beginner Guide

A Python set is a mutable collection of unique, hashable elements. Sets are especially useful for membership tests, deduplication, and mathematical set operations such as union and intersection. Create a Set Use braces for a non-empty set: numbers = {1, 2, 3, 4, 5} Duplicates are removed automatically:

Python Updated 02 Sep 2025 2 min read

Python Lists: From Basics to Nested Lists

Python lists are mutable ordered collections and one of the most commonly used data structures in the language. They work well for sequences that need to grow, shrink, reorder, or contain arbitrary Python objects. Create Lists empty_list = [] numbers = [1, 2, 3, 4, 5] mixed = [1, "Hello", 3.14, True] A list can contain values of different types, although homogeneous lists are often easier to process predictably.

Python Updated 02 Sep 2025 2 min read

Python Dictionaries: A Comprehensive Guide

Python dictionaries are mutable mappings that associate unique keys with values. They are a natural fit for configuration, structured records, caches, lookup tables, and JSON-like application data. Create a Dictionary Use a literal: person = { "name": "Alice", "age": 30, "city": "New York", } Or use dict():

Python Updated 02 Sep 2025 2 min read

Extract Text from PDFs in Python with PyMuPDF

Extracting text from PDF files is useful for search, indexing, analysis, migration, and accessibility workflows. PyMuPDF provides a fast Python API for reading PDF pages and extracting their text. Install PyMuPDF python -m pip install pymupdf Current PyMuPDF versions support the pymupdf import name. Older examples often use import fitz, which is still seen in existing codebases.

Python Updated 02 Sep 2025 2 min read

Common Types of Functions in Python

Python functions range from ordinary def functions to lambdas, generators, methods, and asynchronous functions. Understanding the differences helps you choose the clearest abstraction for each task. 1. Built-in Functions Python includes many functions that are available without imports: print("Hello, world!") print(len([1, 2, 3])) print(sum([1, 2, 3])) Other examples include type(), range(), enumerate(), zip(), min(), and max().

Python Updated 02 Sep 2025 2 min read

Arrays in Python: Lists, `array`, and NumPy

Python has several ways to represent sequence data. The right choice depends on whether you need flexible general-purpose containers, compact typed storage, or high-performance numerical operations. 1. Lists: The Default General-Purpose Sequence Python lists are flexible and can contain objects of different types: numbers = [1, 2, 3, 4, 5] mixed = [1, "Python", 3.14, True] print(numbers[0]) numbers[1] = 10 numbers.append(6) For most application code, a list is the correct default.

Python Updated 02 Sep 2025 2 min read

Using `venv` in Python

A Python virtual environment isolates a project’s installed packages from the system Python environment and from other projects. This helps prevent dependency conflicts and makes development environments easier to reproduce. Create a Virtual Environment From the project directory: python3 -m venv .venv .venv is a common directory name because many editors recognize it automatically. You can use another name if your project has a different convention.

Python Updated 02 Sep 2025 2 min read

Finding Text in a String with a Custom Python Function

Python already provides several ways to search strings, but sometimes you want more than a yes/no result. For example, a search interface may need to return a snippet containing the matching keyword plus some surrounding context. A Context-Aware Search Function def find_text(text, keyword, context=100): index = text.find(keyword) if index == -1: return None start = max(index - context, 0) end = min(len(text), index + len(keyword) + context) return text[start:end] The function:

Python Updated 02 Sep 2025 2 min read

Processing API Data with `requests` and Lambdas in Python

Python’s requests library makes HTTP calls straightforward, while small lambda functions can be useful as transformation or sorting keys. This article shows how to combine them without turning simple data processing into hard-to-read one-liners. Install requests python -m pip install requests Fetch JSON from an API import requests response = requests.get( "https://jsonplaceholder.typicode.com/posts", timeout=10, ) response.raise_for_status() data = response.json() Two details matter here: