Cross_Column

Monday, 19 January 2026

Object Oriented Programming (OOP) in Python




Object Oriented Programming (OOP) in Python

Object Oriented Programming (OOP) is a programming approach that organizes code into objects and classes. Python fully supports OOP, making programs more modular, reusable, scalable, and easy to maintain.


Why Use OOP in Python?

  • Better code organization
  • Reusability of code
  • Easy maintenance and updates
  • Real-world problem modeling
  • Widely used in automation frameworks and applications

Basic OOP Concepts in Python

Python OOP is based on four main principles:

  1. Class
  2. Object
  3. Encapsulation
  4. Inheritance
  5. Polymorphism
  6. Abstraction

1. Class in Python

A class is a blueprint or template used to create objects. It defines variables (attributes) and functions (methods).


class Car:
    brand = "Toyota"

    def start(self):
        print("Car started")

Here:

  • Car is a class
  • brand is a class variable
  • start() is a method


2. Object in Python

An object is an instance of a class. It represents a real-world entity created using a class.


my_car = Car()
my_car.start()
print(my_car.brand)

Output:


Car started
Toyota


3. The __init__() Constructor

The __init__() method is a special constructor that runs automatically when an object is created.


class Employee:
    def __init__(self, name, salary):
        self.name = name
        self.salary = salary

    def show_details(self):
        print(self.name, self.salary)


emp1 = Employee("Chandan", 50000)
emp1.show_details()


4. Encapsulation

Encapsulation means hiding internal data and allowing access through methods only.


class Account:
    def __init__(self, balance):
        self.__balance = balance   # private variable

    def get_balance(self):
        return self.__balance

Note: Variables starting with __ are private.


5. Inheritance

Inheritance allows a class to reuse properties and methods of another class.


class Animal:
    def speak(self):
        print("Animal speaks")

class Dog(Animal):
    def bark(self):
        print("Dog barks")


dog = Dog()
dog.speak()
dog.bark()


6. Polymorphism

Polymorphism means same method name but different behavior.


class Bird:
    def fly(self):
        print("Bird can fly")

class Penguin(Bird):
    def fly(self):
        print("Penguin cannot fly")


b = Bird()
p = Penguin()

b.fly()
p.fly()


7. Abstraction

Abstraction hides implementation details and shows only essential features. Python uses abstract classes for abstraction.


from abc import ABC, abstractmethod

class Vehicle(ABC):

    @abstractmethod
    def start(self):
        pass


Real-World Example (Automation Testing)


class Browser:
    def open(self):
        print("Opening browser")

class Chrome(Browser):
    def open(self):
        print("Opening Chrome Browser")

This approach is widely used in Selenium and Robot Framework projects.


Advantages of OOP in Python

  • Code reusability
  • Easy debugging
  • Improved security
  • Better scalability

OOP Interview Questions

  • What is OOP?
  • Difference between class and object
  • Explain encapsulation with example
  • What is method overriding?
  • Explain inheritance in Python

Conclusion

Object Oriented Programming in Python helps developers write clean, reusable, and scalable code. Understanding OOP is mandatory for Python developers, automation testers, and framework designers.

👉 Continue learning Python with practical examples on https://www.way2testing.com

Sunday, 18 January 2026

Python String Handling




Hello Friends,

String Handling in Python

A string in Python is a sequence of characters enclosed within single quotes (' '), double quotes (" "), or triple quotes (''' ''' or """ """). Strings are used to store and manipulate text data.


Creating Strings

name = "Python"
message = 'Welcome to Python'
paragraph = """Python is easy
and powerful"""

Accessing Characters in a String

Strings are indexed starting from 0.

text = "Python"

print(text[0])
print(text[3])

Output:

P
h

String Slicing

Slicing is used to extract a portion of a string.

text = "Python Programming"

print(text[0:6])
print(text[7:])
print(text[:6])
print(text[-11:])

Output:

Python
Programming
Python
Programming

String Immutability

Strings are immutable, meaning they cannot be changed after creation.

text = "Python"
text[0] = "J"   # Error

Correct Way:

text = "Python"
text = "J" + text[1:]
print(text)

Common String Methods

Changing Case

text = "Python Programming"

print(text.upper())
print(text.lower())
print(text.title())

Removing Whitespaces

text = "  Python  "

print(text.strip())
print(text.lstrip())
print(text.rstrip())

Searching in Strings

text = "Python Programming"

print(text.find("Python"))
print(text.count("o"))

Replacing Text

text = "I like Java"
text = text.replace("Java", "Python")
print(text)

Checking String Content

text = "Python123"

print(text.isalpha())
print(text.isdigit())
print(text.isalnum())

Splitting and Joining Strings

Split

text = "Python,Java,C++"
languages = text.split(",")
print(languages)

Join

languages = ["Python", "Java", "C++"]
text = " | ".join(languages)
print(text)

String Formatting

Using f-strings (Recommended)

name = "Chandan"
age = 36

print(f"My name is {name} and I am {age} years old")

Using format()

print("My name is {} and I am {} years old".format(name, age))

Iterating Over a String

text = "Python"

for char in text:
    print(char)

String Comparison

a = "python"
b = "Python"

print(a == b)
print(a.lower() == b.lower())

Real-Life Examples

Example 1: Validate Email

email = "test@gmail.com"

if "@" in email and "." in email:
    print("Valid Email")
else:
    print("Invalid Email")

Example 2: Count Words

text = "Python is easy to learn"
words = text.split()
print(len(words))

Common Mistakes

  • Trying to modify a string directly
  • Forgetting string methods return new strings
  • Incorrect indexing

Summary

  • Strings store text data
  • Strings are immutable
  • Python provides many built-in string methods
  • f-strings are the best way for formatting

Python Collections – Lists, Tuples, Sets, Dictionaries




Hello Friends,

Python Collections: Lists, Tuples, Sets, and Dictionaries

Python provides built-in collection data types that allow storing multiple values in a single variable. The most commonly used collections are List, Tuple, Set, and Dictionary.


1. Python List

A list is an ordered, mutable (changeable) collection that allows duplicate values.

Syntax

list_name = [item1, item2, item3]

Example

fruits = ["apple", "banana", "mango"]
print(fruits)

Accessing List Items

print(fruits[0])

Modifying List

fruits[1] = "orange"
print(fruits)

Common List Methods

fruits.append("grapes")
fruits.remove("apple")
fruits.sort()
print(fruits)

Real-Life Example

marks = [65, 72, 80]
total = sum(marks)
print(total)

2. Python Tuple

A tuple is an ordered, immutable (cannot be changed) collection.

Syntax

tuple_name = (item1, item2, item3)

Example

colors = ("red", "green", "blue")
print(colors)

Accessing Tuple Items

print(colors[1])

Why Use Tuple?

  • Data safety (cannot be modified)
  • Faster than lists

Real-Life Example

coordinates = (10.5, 20.3)
print(coordinates)

3. Python Set

A set is an unordered collection that does not allow duplicate values.

Syntax

set_name = {item1, item2, item3}

Example

numbers = {1, 2, 3, 3, 4}
print(numbers)

Adding and Removing Elements

numbers.add(5)
numbers.remove(2)
print(numbers)

Set Operations

a = {1, 2, 3}
b = {3, 4, 5}

print(a.union(b))
print(a.intersection(b))

Real-Life Example

emails = {"a@gmail.com", "b@gmail.com", "a@gmail.com"}
print(emails)

4. Python Dictionary

A dictionary stores data in key-value pairs.

Syntax

dict_name = {key1: value1, key2: value2}

Example

student = {"name": "Amit", "age": 21, "course": "Python"}
print(student)

Accessing Dictionary Values

print(student["name"])

Modifying Dictionary

student["age"] = 22
student["city"] = "Delhi"
print(student)

Loop Through Dictionary

for key, value in student.items():
    print(key, ":", value)

Real-Life Example

employee = {
  "id": 101,
  "name": "Ravi",
  "designation": "Tester",
  "salary": 50000
}
print(employee)

Difference Between List, Tuple, Set, Dictionary

Feature List Tuple Set Dictionary
Ordered Yes Yes No Yes
Mutable Yes No Yes Yes
Duplicates Yes Yes No Keys: No

Common Mistakes

  • Using index on set
  • Trying to modify tuple
  • Duplicate keys in dictionary

Summary

  • Lists are flexible and commonly used
  • Tuples are immutable and safe
  • Sets remove duplicates
  • Dictionaries store structured data
===============================================================================

How to Store Ordered and Unique Data in Python

Sometimes we need a data structure that:

  • Maintains insertion order
  • Does not allow duplicate values

Python does not provide a built-in data type that fully satisfies both conditions. However, there are effective ways to achieve this.


Option 1: Using List with Manual Duplicate Check (Most Common)

A list maintains order but allows duplicates. We can manually prevent duplicates.

items = []

data = ["apple", "banana", "apple", "mango"]

for item in data:
    if item not in items:
        items.append(item)

print(items)

Output:

['apple', 'banana', 'mango']

Explanation:
The list preserves order and avoids duplicates by checking before inserting.


Option 2: Using OrderedDict (Best Practice)

OrderedDict from the collections module preserves insertion order and removes duplicates.

from collections import OrderedDict

data = ["apple", "banana", "apple", "mango"]

result = list(OrderedDict.fromkeys(data))
print(result)

Output:

['apple', 'banana', 'mango']

Why This Is Best:

  • Preserves order
  • Automatically removes duplicates
  • Clean and readable

Option 3: Using dict (Python 3.7+)

Since Python 3.7, dictionaries preserve insertion order.

data = ["apple", "banana", "apple", "mango"]

result = list(dict.fromkeys(data))
print(result)

Output:

['apple', 'banana', 'mango']

Note:
This is the most commonly used modern Python approach.


Why Not Use Set?

data = ["apple", "banana", "apple", "mango"]
print(set(data))

Output (order not guaranteed):

{'banana', 'apple', 'mango'}

Sets remove duplicates but do NOT preserve order.


Comparison Table

Approach Ordered No Duplicates Recommended
List + Check Yes Yes Good
OrderedDict Yes Yes Best
dict.fromkeys() Yes Yes Best (Modern)
Set No Yes No

Real-Life Example

Removing duplicate email IDs while keeping order:

emails = [
  "a@gmail.com",
  "b@gmail.com",
  "a@gmail.com",
  "c@gmail.com"
]

unique_emails = list(dict.fromkeys(emails))
print(unique_emails)

Summary

  • No direct built-in ordered set in Python
  • Use dict.fromkeys() for best results
  • Use OrderedDict for clarity
  • Do not use set when order matters

Python Functions




Hello Friends,

Python Functions

A function in Python is a reusable block of code that performs a specific task. Functions help reduce code duplication, improve readability, and make programs easier to maintain.


Why Use Functions?

  • Reuse code multiple times
  • Make programs modular
  • Improve readability and maintenance
  • Reduce errors

Syntax of a Function

def function_name(parameters):
    statements
    return value
  • def – keyword to define a function
  • function_name – name of the function
  • parameters – inputs to the function
  • return – sends result back to caller

Example 1: Simple Function

def greet():
    print("Welcome to Python Functions")

greet()

Output:

Welcome to Python Functions

Explanation:
The function greet() prints a message when called.


Example 2: Function with Parameters

def greet_user(name):
    print("Hello", name)

greet_user("Chandan")

Output:

Hello Chandan

Explanation:
The function accepts a parameter name and prints a personalized message.


Example 3: Function with Return Value

def add(a, b):
    return a + b

result = add(10, 20)
print(result)

Output:

30

Explanation:
The function returns the sum of two numbers.


Example 4: Default Arguments

Default arguments are used when no value is passed.

def greet(name="Guest"):
    print("Hello", name)

greet()
greet("Amit")

Output:

Hello Guest
Hello Amit

Example 5: Keyword Arguments

def student_info(name, age):
    print("Name:", name)
    print("Age:", age)

student_info(age=25, name="Rahul")

Example 6: Arbitrary Arguments (*args)

*args allows passing multiple values.

def total_marks(*marks):
    total = 0
    for m in marks:
        total += m
    return total

print(total_marks(70, 80, 90))

Example 7: Arbitrary Keyword Arguments (**kwargs)

**kwargs allows passing key-value pairs.

def employee_details(**details):
    for key, value in details.items():
        print(key, ":", value)

employee_details(name="Ravi", role="Tester", salary=50000)

Example 8: Function Inside a Function

def outer_function():
    def inner_function():
        print("Inner Function Executed")
    inner_function()

outer_function()

Example 9: Lambda Function

Lambda functions are small anonymous functions.

square = lambda x: x * x
print(square(5))

Output:

25

Real-Life Example

Checking pass or fail:

def check_result(marks):
    if marks >= 40:
        return "Pass"
    else:
        return "Fail"

print(check_result(55))

Common Mistakes

  • Forgetting to call the function
  • Incorrect indentation
  • Using return incorrectly
  • Mismatch in parameters and arguments

Summary

  • Functions help reuse code
  • Functions can take parameters and return values
  • Supports default, keyword, *args, **kwargs
  • Lambda functions are short functions

Python Operators, Conditional Statements (if, else, elif), Loops (for & while)




Hello Friends,

Python Operators

Arithmetic Operators

a = 10
b = 5

print(a + b)
print(a - b)
print(a * b)
print(a / b)

Comparison Operators

print(a > b)
print(a == b)
================================================================================

Conditional Statements in Python

Conditional statements control the flow of execution.

Example

marks = 75

if marks >= 60:
    print("First Division")
elif marks >= 40:
    print("Second Division")
else:
    print("Fail")
==================================================================================

Loops in Python

For Loop

for i in range(1, 6):
    print(i)


Python for Loop

The for loop in Python is used to iterate (loop) over a sequence such as a list, tuple, string, or range of numbers. It executes a block of code repeatedly for each item in the sequence.


Syntax of for Loop

for variable in sequence:
    statements
  • variable – takes value of each element in the sequence
  • sequence – list, tuple, string, or range
  • statements – code executed for each iteration

Example 1: for Loop with range()

The range() function generates a sequence of numbers.

for i in range(1, 6):
    print(i)

Output:

1
2
3
4
5

Explanation:
The loop runs 5 times. The variable i takes values from 1 to 5.


Example 2: for Loop with List

fruits = ["apple", "banana", "mango"]

for fruit in fruits:
    print(fruit)

Output:

apple
banana
mango

Explanation:
Each element of the list is assigned to the variable fruit one by one.


Example 3: for Loop with String

name = "Python"

for char in name:
    print(char)

Output:

P
y
t
h
o
n

Explanation:
Strings are sequences of characters. The loop iterates over each character.


Example 4: for Loop with range(start, stop, step)

for i in range(0, 11, 2):
    print(i)

Output:

0
2
4
6
8
10

Explanation:
The loop starts at 0, ends at 10, and increments by 2.


Example 5: Nested for Loop

A nested for loop means one loop inside another.

for i in range(1, 4):
    for j in range(1, 4):
        print(i, j)

Output:

1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3

Example 6: for Loop with break

The break statement stops the loop immediately.

for i in range(1, 10):
    if i == 5:
        break
    print(i)

Output:

1
2
3
4

Example 7: for Loop with continue

The continue statement skips the current iteration.

for i in range(1, 6):
    if i == 3:
        continue
    print(i)

Output:

1
2
4
5

Example 8: for Loop with else

The else block executes when the loop finishes normally.

for i in range(1, 4):
    print(i)
else:
    print("Loop completed successfully")

Output:

1
2
3
Loop completed successfully

Real-Life Example

Printing student marks:

marks = [65, 72, 80, 90]

for mark in marks:
    print("Student scored:", mark)

Common Mistakes

  • Missing colon : after for statement
  • Incorrect indentation
  • Using wrong variable name inside loop

Summary

  • for loop is used to iterate over sequences
  • range() is commonly used with for loops
  • Supports break, continue, and else
  • Very useful in automation and data processing

====================================================================

While Loop

i = 1
while i <= 5:
    print(i)
    i += 1
=====================================================================
What is "is" in Python? | is vs == Explained

What is is in Python?

In Python, is is an identity operator used to check whether two variables refer to the same object in memory. Unlike the == operator, which compares values, is compares object identity.


Definition of is Operator

The is operator returns True if both variables point to the same memory location, otherwise it returns False.

Syntax:

x is y

Difference Between is and ==

is ==
Checks memory identity Checks value equality
Compares object reference Compares data/content
Used for singletons Used for value comparison
x is y x == y

Example 1: Using is with Integers

x = 10
y = 10

print(x == y)   # True
print(x is y)   # True

Python caches small integers (usually from -5 to 256). So both x and y refer to the same memory object.


Example 2: When == is True but is is False

x = 1000
y = 1000

print(x == y)   # True
print(x is y)   # False

Here, the values are equal, but Python creates separate objects in memory.


Example 3: is with Lists

a = [1, 2, 3]
b = [1, 2, 3]

print(a == b)   # True
print(a is b)   # False

Lists are mutable objects, so Python does not reuse memory for them.


Example 4: Using is with None

The most common and recommended use of is is checking against None.

x = None

if x is None:
    print("x is None")

❌ Bad Practice:

if x == None:
    pass

✔ Best Practice:

if x is None:
    pass

Using id() to Understand is

The id() function returns the memory address of an object.

x = 10
y = 10

print(id(x))
print(id(y))

If both IDs are same, is will return True.


When Should You Use is?

  • To compare with None
  • To check singleton objects
  • To verify object identity

When NOT to Use is?

  • For string comparison
  • For numeric value comparison
  • For list or dictionary value comparison

Interview Questions on is Operator

  • What is the difference between is and ==?
  • Why should we use is with None?
  • Does is compare values?
  • What does id() return?

Summary

  • is checks object identity, not value
  • == checks value equality
  • is compares memory references
  • Use is mainly with None

✅ Understanding is helps avoid logical bugs and improves Python coding best practices.


Related Topics: == vs is, id() function, Mutable vs Immutable Objects, Python Operators

Python Syntax & Indentation, Python Variables and Data Types




Hello Friends,

Python Syntax and Indentation

Python uses indentation instead of brackets to define code blocks.

Correct Example

if 10 > 5:
    print("10 is greater than 5")

Incorrect Example

if 10 > 5:
print("Error")
=======================================================================

Variables and Data Types

Variables store data values in Python.

Common Data Types

  • int
  • float
  • string
  • boolean

Example

age = 30
name = "Chandan"
price = 99.50
is_active = True

print(age)
print(name)
print(price)
print(is_active)


type() in Python – Complete Guide with Examples

type() in Python – Complete Guide with Examples

The type() function in Python is a built-in function used to determine the data type of a variable, object, or value. It plays an important role in debugging, type checking, dynamic programming, and object-oriented programming.


🔹 Syntax of type()


type(object)
type(name, bases, dict)

Explanation:

  • Single argument: Returns the type/class of the object
  • Three arguments: Dynamically creates a class (advanced usage)

🔹 Basic Example


x = 10
y = 3.14
z = "Python"
a = [1, 2, 3]
b = {"name": "Chandan", "role": "Tester"}

print(type(x))
print(type(y))
print(type(z))
print(type(a))
print(type(b))

Output:


<class 'int'>
<class 'float'>
<class 'str'>
<class 'list'>
<class 'dict'>

🔹 type() with User Input


user_input = input("Enter something: ")
print(type(user_input))

Output:


<class 'str'>

👉 Note: input() always returns a string, so conversion is required:


num = int(input("Enter number: "))
print(type(num))

🔹 type() with Custom Class


class Employee:
    pass

emp = Employee()
print(type(emp))

Output:


<class '__main__.Employee'>

🔹 Dynamic Class Creation using type()


Person = type("Person", (), {
    "name": "Chandan",
    "age": 25,
    "greet": lambda self: f"Hello, my name is {self.name}"
})

p = Person()
print(p.name)
print(p.greet())

Output:


Chandan
Hello, my name is Chandan

🔹 type() vs isinstance()

type() isinstance()
Checks exact type Checks inheritance also
Not inheritance-friendly Inheritance-friendly
Less flexible More flexible

Example:


class Animal:
    pass

class Dog(Animal):
    pass

d = Dog()

print(type(d) == Animal)        # False
print(isinstance(d, Animal))    # True

🔹 Real-world Use Cases

  • ✔ Debugging variable types
  • ✔ Data validation
  • ✔ Dynamic behavior control
  • ✔ Framework development
  • ✔ API response validation
  • ✔ Serialization & deserialization

🔹 Common Mistakes

  • ❌ Using type() instead of isinstance() for inheritance checks
  • ❌ Assuming input() returns numbers
  • ❌ Hardcoding type checks instead of polymorphism

🔹 Best Practices

  • ✅ Prefer isinstance() for type checking
  • ✅ Use type() for debugging/logging
  • ✅ Avoid tight coupling with specific types
  • ✅ Use duck typing where possible

🔹 Interview Questions

  • What is the use of type() in Python?
  • Difference between type() and isinstance()?
  • Can type() create classes dynamically?
  • Is type a class in Python?
  • Explain metaclasses in Python

🔹 Conclusion

The type() function is a powerful built-in feature of Python that helps in identifying object types, creating dynamic classes, debugging applications, and building flexible systems. While it is useful, Python developers should prefer isinstance() for most type-checking scenarios to support inheritance and polymorphism.

Understanding type() gives you deeper insight into Python’s object model and dynamic nature.


Related Topics: isinstance(), id(), __class__, metaclasses, duck typing, reflection

Python Introduction And Python Installation & Setup




Hello Friends,

Introduction to Python

Python is a high-level, interpreted, and general-purpose programming language. It is easy to learn and widely used in automation, web development, data science, and testing.

Why Learn Python?

  • Easy to read and write
  • Large community support
  • Used in Automation, AI, ML, Web Development

Example

print("Hello, World!")

Output:

Hello, World!


Python Installation and Setup

Steps to Install Python

  1. Download Python from official website
  2. Install Python
  3. Add Python to system PATH

Verify Installation

python --version

Example

print("Python Installed Successfully")

Few More

Encapsulation in Python

Encapsulation in Python: A Complete Guide with Examples and Diagrams Encapsul...

Popular Posts