Sitemap
Aditya Kumar

Aditya Kumar

BTech | Security Software Engineer & Researcher | Cloud Security | Python, AWS, MERN, ReactJS | Mail: adii.utsav@gmail.com

Python — Part 3

12 min readFeb 7, 2026
Press enter or click to view image in full size

Dictionary methods in Python:

Example: update()

Example: clear()

Press enter or click to view image in full size

Example: pop()

Example: popitem() -> removes the last key-value pair.

Example: del to delete a key-value or complete dictionary. Here we are deleting the dictionary.

Press enter or click to view image in full size

Example: using del to delete the key.

Press enter or click to view image in full size

for Loop with else in Python:

Example: a basic example of for loop with else.

Example: another example.

Example:

Press enter or click to view image in full size

Example: using for … if … else. Clearly, else will execute only when the for loop completed successfully.

Press enter or click to view image in full size

Exception Handling in Python:

What is an Exception?

An exception is an error that occurs while the program is running, which stops the normal flow of execution.

Example:

x = 10 / 0 # ZeroDivisionError

Output:

ZeroDivisionError: division by zero

Why Exception Handling?

Without handling exceptions:

· The program crashes

· Remaining code does not execute

With exception handling:

· Program continues gracefully

· Errors are managed properly

Basic try–except: Use try to write risky code and except to handle errors.

try:

x = 10 / 0

except:

print(“An error occurred”)

Example:

Example: code to print the multiplication table.

Example: what if we give string as the input in the above example? The program will show an error.

Press enter or click to view image in full size

Example: using try…except to handle the error.

Press enter or click to view image in full size

Example: we can omit the “exception as e”

Press enter or click to view image in full size

Example: catching specific exceptions

Press enter or click to view image in full size

Example: we can add multiple “except”.

Press enter or click to view image in full size

Summary:

· try block contains code that may cause an error

· except block handles the error if it occurs

· Program does not crash when exception is handled

· Always catch specific exceptions, not generic ones

· Multiple except blocks can handle different errors

· else runs only if no exception occurs

· finally runs whether an exception occurs or not

· Use Exception as e to get error details

· raise is used to create custom errors

· Keep try blocks short and focused

Finally Keyword in Python:

What is finally?

The finally block is used with try–except and always executes, whether:

· an exception occurs

· no exception occurs

· an exception is handled or not

Basic Syntax

try:

# risky code

except:

# error handling

finally:

# cleanup code (always runs)

Example: a basic example.

Press enter or click to view image in full size

Example: finally is always executed even if try or except executed.

Press enter or click to view image in full size

Why Use finally?

· To close files

· To release resources

· To disconnect databases

· To ensure cleanup code always runs

Important Points

· finally executes even if return is used

· finally executes even if an exception is not handled

· Only skipped if the program forcibly terminates

· finally is used to run cleanup code that must execute no matter what happens in try or except.

Raising custom errors in Python:

What Is a Custom Error?

A custom error (custom exception) is a user-defined error that you create to represent specific problems in your program.

Why Raise Custom Errors?

· To make errors more meaningful

· To improve code readability

· To handle application-specific rules

· To separate logic errors from system errors

Using raise (Basics)

You can raise a built-in exception manually.

age = -5

if age < 0:

raise ValueError(“Age cannot be negative”)

Example: a basic example.

Press enter or click to view image in full size

Example: Handling Custom Exceptions with try–except

Press enter or click to view image in full size

Summary:

· Custom errors are user-defined exceptions created for specific problems

· They are created by inheriting from Exception

· Use raise to trigger a custom error

· Custom errors make code clearer and more meaningful

· They must be defined before use

· Use try–except to handle custom errors gracefully

· Unhandled custom errors show a traceback (expected behavior)

· Name custom errors clearly (e.g., InvalidAgeError)

Short hand if else statements:

What Is Shorthand if–else?

A shorthand if–else (also called ternary operator) allows you to write an if–else condition in one line.

Basic Syntax

value_if_true if condition else value_if_false

Example: a basic example.

Press enter or click to view image in full size

Example: multiple conditions

Press enter or click to view image in full size

Enumerate Function in Python:

What is enumerate()?

enumerate() is a built-in Python function used to loop over an iterable while keeping track of the index. Instead of manually counting indexes, enumerate() does it automatically.

Basic Syntax

enumerate(iterable, start=0)

· iterable → list, tuple, string, etc.

· start → starting index (default is 0)

Example: old way

Example: a basic example printing the index number and the text at that index.

Example: enumerating with custom start index

Example: enumerate with the string.

Press enter or click to view image in full size

Example:

Press enter or click to view image in full size

Summary:

· enumerate() is a built-in Python function

· It returns index and value while looping

· Used with lists, tuples, strings, and other iterables

· Default starting index is 0

· start parameter can change the starting index

· Makes code cleaner than manual indexing

· Returns pairs as (index, item) tuples

· Commonly used in for loops

Virtual Environment in Python:

What Is a Virtual Environment?

A virtual environment (venv) is an isolated Python environment where you can install packages without affecting the global Python installation.

Why Use a Virtual Environment?

· Avoids package version conflicts

· Keeps projects independent

· Makes projects portable

· Prevents breaking system Python

Example Problem (Without venv)

· Project A needs Django 2.2

· Project B needs Django 4.x

· Installing one breaks the other

Creating a Virtual Environment:

Step 1: Open Terminal / Command Prompt

python -m venv myenv

myenv = environment name

Press enter or click to view image in full size

To activate:

Press enter or click to view image in full size

Deactivating the Virtual Environment

Press enter or click to view image in full size

Installing the module named ‘requests’:

Press enter or click to view image in full size

Checking installed packages:

Press enter or click to view image in full size

Sharing a Virtual Environment (requirements.txt)

Press enter or click to view image in full size

Deleting a Virtual Environment: Just delete the folder:

Get Aditya Kumar’s stories in your inbox

Join Medium for free to get updates from this writer.

Myenv/

Summary:

· A virtual environment is an isolated Python workspace

· It prevents dependency and version conflicts

· Each project should have its own virtual environment

· Created using python -m venv env_name

· Must be activated before installing packages

· Packages installed inside venv do not affect global Python

· Deactivate using deactivate

· Use requirements.txt to share dependencies

· Virtual environment folders should not be committed to Git

How import works in Python:

What Is import in Python?

import is used to load code from another module (file) so you can use its functions, variables, or classes.

Example: importing a module.

Example: importing specific items

Example: Import Everything (Not Recommended)

Example: importing with alias

Example: using ‘dir’ to know the function inside the module.

Press enter or click to view image in full size

Example: importing your own file(modules)

A.py:

B.py:

How Python Finds a Module (Import Search Path)

Python searches in this order:

1. Current directory

2. Built-in modules

3. Installed packages

4. Paths in sys.path

if __name__ == “__main__” in Python:

What Is __name__?

· __name__ is a special built-in variable in Python

· It tells how the Python file is being executed

Key Values of __name__:

Why Use if __name__ == “__main__”?

· To control code execution

· Code inside this block runs only when file is executed directly

· Prevents code from running when file is imported

Let’s us first understand the issue without it:

Aditya.py:

Press enter or click to view image in full size

Main2.py:

Press enter or click to view image in full size

Clearly, when main2.py was run, it printed the output twice, once because of “Aditya.welcome()” and one because “welcome()” was called in Aditya.py.

What if we commend out “Aditya.welcome()”? Only once it will print.

But, is this the solution? No, it means that every function inside the Aditya.py will get executed if main2.py was run.

Solution:

Real-World Use Case

· Python scripts often contain functions, classes, and test code

· Use if __name__ == “__main__” to run test/demo code only when needed

os Module in Python:

What Is the os Module?

· os is a built-in Python module for interacting with the operating system

· Lets you perform tasks like:

o File and directory management

o Environment variables

o Process management

Importing the module:

Example: Creating a folder using the os module.

Press enter or click to view image in full size

Example: code to check if a folder exists in our folder or not.

Press enter or click to view image in full size

Example: to rename

Press enter or click to view image in full size

Example: to print the list of the folders in a specific folder.

Press enter or click to view image in full size

Example: Current Working Directory

Example: Creating and Removing Directories

Press enter or click to view image in full size

Local vs Global Variables in Python:

What is a Variable?

A variable is a name that stores a value in memory.

x = 10

What is Scope?

Scope defines where a variable can be accessed in your program.

Python mainly uses:

· Local scope

· Global scope

Local Variables: A local variable is created inside a function and can be used only within that function.

def my_function():

x = 10 # local variable

print(x)

my_function()

Global Variables: A global variable is created outside all functions and can be accessed anywhere in the program.

x = 20 # global variable

def my_function():

print(x)

my_function()

print(x)

Example: local variable.

Example: global variable.

Example: local variable get preference over the global variable if there name be same.

Example: using ‘global’ keyword

Why Avoid Too Many Global Variables?

Using many global variables can:

· Make code hard to debug

· Cause unexpected changes

· Reduce readability

File IO in Python:

What is File I/O?

File I/O means:

· Input → Reading data from a file

· Output → Writing data to a file

Files allow data to be stored permanently, unlike variables (temporary).

Types of Files

Python mainly works with:

1. Text files → .txt, .csv, .log

2. Binary files → .jpg, .pdf, .exe

Example: opening the file.

Press enter or click to view image in full size

Example: reading the content of myfile.txt

Press enter or click to view image in full size

Common File Modes

Example: if we open a file which doesn’t exists in ‘w’ mode, then that file automatically get created.

Press enter or click to view image in full size

Example: writing in the file.

Example: appending in the file.

Example: the number of times we run the code, the number of times it get appended.

Example: Using with Statement (Best Practice): Automatically closes the file.

Press enter or click to view image in full size

read(), readlines() and other methods:

Before reading, a file must be opened in read mode (r).

read()

· Reads entire file content as one single string

· Can also read a specific number of characters

Example: basic reading of the file.

Press enter or click to view image in full size

Example: reading the first ten characters.

Press enter or click to view image in full size

readline()

· Reads one line at a time

· Cursor moves to the next line automatically

Example: basic use of readline()

readlines()

· Reads all lines at once

· Returns a list of strings

Example: a basic example of readlines()

Press enter or click to view image in full size

Example: File Cursor Methods: tell() — Returns current cursor position.

Press enter or click to view image in full size

Example: seek() -> Moves cursor to a specific position.

Press enter or click to view image in full size

Comparison Table

Summary:

· read() → Reads the entire file (or given number of characters) and returns a single string.

· readline() → Reads one line at a time and returns it as a string.

· readlines() → Reads all lines at once and returns them as a list of strings.

· File iteration (for line in file) → Reads the file line-by-line efficiently using minimal memory.

· tell() → Returns the current position of the file cursor.

· seek(pos) → Moves the file cursor to the specified position.

· write() → Writes a string to the file and returns the number of characters written.

· writelines() → Writes a list of strings to the file without adding newlines automatically.

· close() → Closes the file and frees system resources.

· with open() → Automatically opens and closes the file safely (best practice).

Contact Me:
📧 Email: adii.utsav@gmail.com
🔗 LinkedIn: https://www.linkedin.com/in/aditya-kumar-3241b6286/
💻 GitHub: https://github.com/Rememberful

--

--

Aditya Kumar
Aditya Kumar

BTech | Security Software Engineer & Researcher | Cloud Security | Python, AWS, MERN, ReactJS | Mail: adii.utsav@gmail.com