Master's Python With Elight Python Series Documentation
Python is one of the most popular programming languages in the world today. It was created by Guido van Rossum and first released in 1991. Python is known for its simple and easy-to-read syntax, which makes it a great choice for both beginners and professionals.
Python is widely used because it is:
Python is extremely flexible. Some common areas include:
Here’s the famous “Hello, World!” program in Python:
print("Hello, World!")
When you run this code, Python will display:
Hello, World!
python --version or python3 --version to confirm installation.Python is a high-level, beginner-friendly, interpreted language created in 1991. It is easy to read, supports many applications (from web apps to AI), and has a huge global community. If you are new to coding, Python is one of the best languages to start with.
Welcome to Python.Before you can start writing and running Python programs, you need to set up Python on your computer. This topic explains how to install Python, check if it’s working, and run your first program.
sudo apt-get install python3
After installation, check if Python is working properly:
python --version
or
python3 --version
If Python is installed, you’ll see something like:
Python 3.12.6
Open your terminal (Command Prompt, PowerShell, or shell) and type:
python
This opens the Python Interactive Shell, where you can run Python commands directly.
Type this command:
print("Hello, World!")
You should see:
Hello, World!
Instead of typing code in the interactive shell, you can write code in a file with the extension
.py.
print("Welcome to Python programming!")
first_program.py.python first_program.py
If you don’t want to install Python immediately, you can use online interpreters such as:
These let you write and run Python code directly in your browser.
python --version..py file.Python Setup Successful!The syntax of Python is what makes it one of the easiest programming languages to learn. Unlike other languages that use symbols and complex rules, Python uses simple and clean code that almost looks like normal English sentences.
indentation (spaces or tabs) to
define code blocks. Other languages like C, C++ or Java use curly braces { }, but in Python
indentation is mandatory.name and Name are different.
;)
at the end of each line. Each line is treated as a complete statement.# symbol. Comments are ignored by
the Python interpreter.# This is a comment
print("Hello, World!") # This line prints text
In this example:
Indentation is one of the most important parts of Python syntax. It tells the interpreter which block of code belongs together.
if 5 > 2:
print("Five is greater than two!")
If you forget to indent or use the wrong indentation, Python will throw an error. For example:
if 5 > 2:
print("Five is greater than two!") # ❌ This will cause an error
You can write a statement across multiple lines using a backslash (\).
x = 10 + 20 + 30 + \
40 + 50
print(x)
Identifiers are the names you give to variables, functions, classes, etc. They must start with a letter or underscore and cannot contain special characters or spaces.
Python’s syntax is designed to be clean, simple, and easy to read. It helps beginners focus on problem-solving instead of worrying about complex grammar rules. Understanding indentation, case sensitivity, and basic rules of Python syntax is the first step toward writing error-free code.
Comments in Python are lines of text that are ignored by the Python interpreter. They are used to explain the code, make it more readable, and leave helpful notes for yourself or other developers. Good commenting practices make your code easier to understand and maintain.
In Python, single-line comments start with the # symbol.
Everything written after # on that line is treated as a comment.
# This is a single-line comment
print("Hello, World!") # This prints a message
Python does not have a special syntax for multi-line comments like some other languages.
Instead, you can use multiple # symbols or triple quotes (''' ... ''' or
""" ... """)
to write multi-line comments.
# This is line one of a comment
# This is line two of the comment
# This is line three of the comment
"""
This is a multi-line comment.
It can span across multiple lines.
Useful for long explanations or documentation.
"""
print("Python comments example")
# increase x by 1 if the code already shows
x = x + 1.
Comments are not executed by Python, but they play a huge role in making your code professional and easy to understand. As a beginner, try to develop the habit of writing clear and meaningful comments in your programs.
In Python, variables are used to store data that can be used and modified later in your program. Think of a variable as a container that holds information like numbers, text, or more complex data types.
To create a variable in Python, you simply assign a value using the = operator:
name = "Ashish"
age = 20
height = 5.9
Here:
name stores a string.age stores an integer.height stores a float (decimal number)._).age and Age are different.
if, for, while) as variable
names.You can assign values to multiple variables in a single line:
x, y, z = 5, 10, 15
print(x, y, z) # Output: 5 10 15
Or assign the same value to multiple variables:
a = b = c = 100
print(a, b, c) # Output: 100 100 100
Variables in Python are dynamic, meaning their value can change at any time:
score = 50
print(score) # Output: 50
score = 75
print(score) # Output: 75
global_var = 100 # Global variable
def my_function():
local_var = 50 # Local variable
print(local_var)
my_function() # Output: 50
print(global_var) # Output: 100
Variables are the foundation of any Python program. They allow you to store and manipulate data easily. Understanding how to create, name, and use variables correctly is essential for writing efficient and readable Python code.
In Python, data types define the kind of value a variable holds. Each variable in Python has a data type that determines what operations can be performed on it. Understanding data types is essential for writing correct and efficient code.
"Hello" or 'Python'
[1, 2, 3, "Python"]
(1, 2, 3)
{1, 2, 3}{"name": "Ashish", "age": 20}
NoneYou can check the data type of a variable using the type() function:
x = 10
y = "Python"
z = 3.14
print(type(x)) # Output: <class 'int'>
print(type(y)) # Output: <class 'str'>
print(type(z)) # Output: <class 'float'>
Python allows you to convert one data type to another using type conversion functions:
x = 10 # int
y = float(x) # convert to float
z = str(x) # convert to string
print(y) # Output: 10.0
print(z) # Output: '10'
Understanding Python data types is crucial for programming because it helps you choose the right type of variable for the data you want to store and manipulate. Using data types correctly improves your code's reliability, performance, and readability.
In Python, numbers are used to store numeric values. Python supports several types of numbers, and understanding them is essential for performing calculations and mathematical operations in your programs.
10, -5, 10003.14, -0.5, 2.02 + 3j
Assign numbers to variables like this:
int_num = 10
float_num = 3.14
complex_num = 2 + 3j
print(int_num)
print(float_num)
print(complex_num)
Python allows you to perform arithmetic operations easily:
5 + 3 = 810 - 4 = 62 * 5 = 1010 / 2 = 5.07 // 2 = 37 % 2 = 12 ** 3 = 8Convert numbers between types using built-in functions:
x = 10 # int
y = float(x) # convert to float
z = complex(x) # convert to complex
print(type(y)) # <class 'float'>
print(type(z)) # <class 'complex'>
Python has useful built-in functions for numbers:
abs(x) - Returns absolute value of xround(x, n) - Rounds x to n decimal placespow(x, y) - Returns x raised to the power ymin(x, y, ...) - Returns the smallest numbermax(x, y, ...) - Returns the largest numberNumbers are fundamental in Python programming. By understanding the different types of numbers and how to perform operations on them, you can easily handle calculations, mathematical problems, and even complex scientific tasks in your Python programs.
In Python, casting means converting a variable from one data type to another. Python is dynamically typed, which means the type is decided automatically when you assign a value. However, you may want to convert data into a specific type for calculations or formatting.
int() — Convert to IntegerConverts a number or a numeric string into an integer. Decimals are truncated, not rounded.
x = int(1) # 1
y = int(2.9) # 2
z = int("10") # 10
print(x, y, z) # Output: 1 2 10
float() — Convert to Floating PointConverts a number or numeric string into a floating-point (decimal) number.
a = float(1) # 1.0
b = float(2.5) # 2.5
c = float("3.14") # 3.14
print(a, b, c) # Output: 1.0 2.5 3.14
str() — Convert to StringConverts numbers and other values into text.
p = str(10) # "10"
q = str(3.14) # "3.14"
r = str(True) # "True"
print(p, q, r) # Output: 10 3.14 True
# Example 1: Math with input
age = input("Enter your age: ") # input is string
age_num = int(age)
print(age_num + 5)
# Example 2: String concatenation
price = 99
print("The price is " + str(price))
int() removes the decimal part (does not round).float() can handle decimal values and numeric strings.str() is used when combining numbers with text.int("abc")) cause ValueError.int(2.9) and round(2.9)?"15.75" into both float and int. What happens?int("3.5") raise an error while float("3.5") works?
In Python, a string is a sequence of characters enclosed in either single quotes
(' ') or double quotes (" ").
Strings are one of the most commonly used data types in Python.
# Single or double quotes
a = "Hello"
b = 'World'
print(a, b) # Output: Hello World
Use triple quotes (''' or """) for strings that span multiple lines.
text = """This is
a multiline
string."""
print(text)
Strings are arrays of characters, and indexing starts at 0.
word = "Python"
print(word[0]) # P
print(word[5]) # n
You can extract a portion of a string using slicing.
word = "Python"
print(word[0:4]) # Pyth
print(word[2:]) # thon
print(word[:3]) # Pyt
txt = "Hello World"
print(len(txt)) # 11
Python has many built-in string methods:
upper() → Converts to uppercaselower() → Converts to lowercasestrip() → Removes whitespacereplace() → Replaces a substringsplit() → Splits string into a listtxt = " Hello World "
print(txt.upper()) # HELLO WORLD
print(txt.lower()) # hello world
print(txt.strip()) # "Hello World"
print(txt.replace("World", "Python")) # Hello Python
print(txt.split()) # ['Hello', 'World']
a = "Hello"
b = "World"
print(a + " " + b) # Hello World
You can insert variables into strings using f-strings or format().
name = "Alice"
age = 25
print(f"My name is {name}, and I am {age} years old.")
print("My name is {}, and I am {} years old.".format(name, age))
Use the backslash (\) to escape special characters.
txt = "We are \"Python\" developers"
print(txt) # We are "Python" developers
"Programming".
"World" with "Python" in "Hello World".
In Python, a boolean represents one of two values: True or
False.
Booleans are often used in conditional statements, loops, and logical operations.
print(True) # True
print(False) # False
print(type(True)) # <class 'bool'>
A boolean expression evaluates to either True or False.
x = 10
y = 5
print(x > y) # True
print(x == y) # False
print(x < y) # False
is_raining = True
if is_raining:
print("Take an umbrella")
else:
print("Enjoy the sunshine")
The bool() function can convert values to a boolean:
print(bool(1)) # True
print(bool(0)) # False
print(bool("Hello")) # True
print(bool("")) # False
The following are considered False in Python:
0"" (empty string)[] (empty list)() (empty tuple){} (empty dictionary)NoneFalsea = True
b = False
print(a and b) # False
print(a or b) # True
print(not a) # False
if statement to check if a string is empty or not.0, "Python", and [] into booleans using
bool().
5 > 2 and 3 < 1?In Python, operators are special symbols that perform operations on variables and values. Operators are the building blocks of programming because they help us perform calculations, compare values, and make decisions.
Used for mathematical calculations:
x = 10
y = 3
print(x + y) # Addition → 13
print(x - y) # Subtraction → 7
print(x * y) # Multiplication → 30
print(x / y) # Division → 3.33
print(x % y) # Modulus → 1 (remainder)
print(x ** y) # Exponentiation → 1000
print(x // y) # Floor division → 3
Used to compare two values. Returns True or False.
a = 5
b = 10
print(a == b) # False
print(a != b) # True
print(a > b) # False
print(a < b) # True
print(a >= b) # False
print(a <= b) # True
Used to assign values to variables.
x = 5
x += 3 # x = x + 3 → 8
x -= 2 # x = x - 2 → 6
x *= 4 # x = x * 4 → 24
x /= 6 # x = x / 6 → 4.0
x %= 3 # x = x % 3 → 1
Used to combine conditional statements.
a = True
b = False
print(a and b) # False
print(a or b) # True
print(not a) # False
Check if two objects are the same in memory.
x = ["apple", "banana"]
y = ["apple", "banana"]
z = x
print(x is z) # True (same object)
print(x is y) # False (different objects with same values)
print(x == y) # True (values are equal)
Check if a value is present in a sequence.
fruits = ["apple", "banana", "cherry"]
print("apple" in fruits) # True
print("mango" not in fruits) # True
Used to compare binary numbers.
a = 6 # 110 in binary
b = 3 # 011 in binary
print(a & b) # AND → 2 (010)
print(a | b) # OR → 7 (111)
print(a ^ b) # XOR → 5 (101)
print(~a) # NOT → -7
print(a << 1) # Left shift → 12
print(a >> 1) # Right shift → 3
**).
"python" exists in the list
["java", "python", "c++"].
5 and
7.
In Python, a list is an ordered collection of items. Lists are one of the most versatile data types and allow you to store multiple values in a single variable. You can store numbers, strings, or even other lists inside a list.
You can create lists using square brackets []:
fruits = ["apple", "banana", "cherry"]
numbers = [1, 2, 3, 4, 5]
mixed = [1, "apple", 3.14, True]
Items in a list can be accessed using their index. Python indexes start at 0.
fruits = ["apple", "banana", "cherry"]
print(fruits[0]) # Output: apple
print(fruits[2]) # Output: cherry
Extract a portion of a list using slicing:
fruits = ["apple", "banana", "cherry", "date"]
print(fruits[1:3]) # Output: ['banana', 'cherry']
print(fruits[:2]) # Output: ['apple', 'banana']
print(fruits[2:]) # Output: ['cherry', 'date']
fruits[1] = "blueberry"append() or insert() methodsremove(), pop(), or delfruits = ["apple", "banana", "cherry"]
fruits.append("date") # Add at the end
fruits.insert(1, "orange") # Add at index 1
fruits.remove("banana") # Remove specific item
fruits.pop() # Remove last item
print(fruits) # Output: ['apple', 'orange', 'cherry']
[1,2] + [3,4] = [1,2,3,4][1,2] * 2 = [1,2,1,2]3 in [1,2,3] → Truelen(list) - Returns the number of itemslist.sort() - Sorts the listlist.reverse() - Reverses the listlist.clear() - Removes all itemslist.copy() - Returns a copy of the listPython lists are flexible and powerful tools for storing and manipulating data. By mastering list operations and methods, you can efficiently handle collections of items in your programs.
In Python, a tuple is an ordered collection of items, similar to a list. However, the key difference is that tuples are immutable, which means their items cannot be changed, added, or removed after creation.
You can create tuples using parentheses () or the tuple() function:
# Using parentheses
my_tuple = (1, 2, 3, "Python")
# Using tuple() function
another_tuple = tuple([4, 5, 6])
print(my_tuple)
print(another_tuple)
Items in a tuple can be accessed using indexing:
my_tuple = ("apple", "banana", "cherry")
print(my_tuple[0]) # Output: apple
print(my_tuple[2]) # Output: cherry
You can extract parts of a tuple using slicing:
fruits = ("apple", "banana", "cherry", "date")
print(fruits[1:3]) # Output: ('banana', 'cherry')
print(fruits[:2]) # Output: ('apple', 'banana')
print(fruits[2:]) # Output: ('cherry', 'date')
(1,2) + (3,4) = (1,2,3,4)(1,2) * 2 = (1,2,1,2)3 in (1,2,3) → TrueTuples have only two built-in methods:
count(x) - Returns the number of times x appears in the tupleindex(x) - Returns the first index of x in the tupleTuples are simple, immutable sequences that are ideal for storing fixed collections of items. They are faster than lists and can be safely used in programs where data should not change.
In Python, a set is an unordered collection of unique items. Sets are useful when you want to store multiple items without duplicates and perform operations like union, intersection, and difference.
You can create a set using curly braces {} or the set() function:
# Using curly braces
my_set = {1, 2, 3, 4}
# Using set() function
another_set = set([3, 4, 5, 6])
print(my_set)
print(another_set)
Since sets are unordered, you cannot access items using an index. You can, however, loop through the set:
fruits = {"apple", "banana", "cherry"}
for fruit in fruits:
print(fruit)
set.add(item)set.update([item1, item2])set.remove(item) or set.discard(item)set.clear() removes all itemsfruits = {"apple", "banana"}
fruits.add("cherry")
fruits.update(["orange", "mango"])
fruits.remove("banana")
print(fruits) # Output: {'apple', 'cherry', 'orange', 'mango'}
{1,2} | {2,3} = {1,2,3}{1,2} & {2,3} = {2}{1,2,3} - {2,3} = {1}
{1,2} ^ {2,3} = {1,3}
Python sets are powerful for storing unique items and performing mathematical set operations. They are ideal for removing duplicates, checking membership, and handling collections without caring about order.
In Python, a dictionary is an unordered collection of key-value pairs. Dictionaries are used to store data where each item has a unique key associated with a value, making it easy to retrieve, update, and manage information.
You can create a dictionary using curly braces {} or the dict() function:
# Using curly braces
my_dict = {"name": "Ashish", "age": 20, "city": "Delhi"}
# Using dict() function
another_dict = dict(name="Python", version=3.11)
print(my_dict)
print(another_dict)
You can access dictionary values using their keys:
print(my_dict["name"]) # Output: Ashish
print(my_dict.get("age")) # Output: 20
my_dict["age"] = 21my_dict["email"] = "ashish@example.com"del my_dict["city"] or my_dict.pop("age")You can get all the keys or values in a dictionary:
print(my_dict.keys()) # Output: dict_keys(['name', 'age', 'city'])
print(my_dict.values()) # Output: dict_values(['Ashish', 20, 'Delhi'])
You can loop through dictionaries using for loops:
for key in my_dict:
print(key, ":", my_dict[key])
# Output:
# name : Ashish
# age : 20
# city : Delhi
Dictionaries can contain other dictionaries as values, allowing complex data storage:
student = {
"name": "Ashish",
"marks": {"math": 95, "science": 90}
}
print(student["marks"]["math"]) # Output: 95
Python dictionaries are extremely useful for storing and managing structured data. With unique keys and flexible values, dictionaries provide fast access and efficient data manipulation, making them one of the most important data types in Python programming.
In Python, if-else statements are used to make decisions in your programs.
They allow the program to execute certain code only if a specific condition is True, and
optionally execute another block of code if the condition is False.
The if statement runs a block of code only if a condition is True:
age = 18
if age >= 18:
print("You are an adult.")
The else block runs if the if condition is False:
age = 16
if age >= 18:
print("You are an adult.")
else:
print("You are a minor.")
Use elif (else if) to check multiple conditions:
marks = 75
if marks >= 90:
print("Grade: A")
elif marks >= 75:
print("Grade: B")
elif marks >= 50:
print("Grade: C")
else:
print("Grade: F")
You can place an if statement inside another if statement:
age = 20
citizen = True
if age >= 18:
if citizen:
print("You are eligible to vote.")
else:
print("You must be a citizen to vote.")
else:
print("You are not eligible to vote.")
elif instead of multiple if statements for better performance.Python if-else statements are essential for controlling the flow of your program. They allow you to make decisions based on conditions and handle multiple scenarios effectively. Mastering if-else statements is crucial for writing intelligent and responsive Python programs.
In Python, loops are used to execute a block of code repeatedly until a condition is met. Loops help automate repetitive tasks, making your programs more efficient and concise.
The while loop repeats a block of code as long as a condition is True:
count = 1
while count <= 5:
print("Count:", count)
count += 1 # increment count
The for loop is used to iterate over a sequence like a list, tuple, string, or range:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
# Using range()
for i in range(5):
print(i) # Output: 0 1 2 3 4
# Break example
for i in range(10):
if i == 5:
break
print(i) # Output: 0 1 2 3 4
# Continue example
for i in range(5):
if i == 2:
continue
print(i) # Output: 0 1 3 4
You can use loops inside another loop:
for i in range(1, 4):
for j in range(1, 4):
print(i, j)
Python loops are powerful tools for repeating tasks efficiently.
By mastering for and while loops along with control statements like
break and continue, you can write dynamic and efficient programs.
In Python, a function is a block of reusable code that performs a specific task. Functions help organize your code, avoid repetition, and make programs easier to read and maintain.
You can define a function using the def keyword:
def greet():
print("Hello, welcome to Python!")
greet() # Calling the function
Functions can accept input values, called parameters:
def greet(name):
print("Hello, " + name + "!")
greet("Ashish") # Output: Hello, Ashish!
Functions can return a value using the return keyword:
def add(a, b):
return a + b
result = add(5, 3)
print(result) # Output: 8
You can assign default values to parameters if no value is provided:
def greet(name="Guest"):
print("Hello, " + name + "!")
greet() # Output: Hello, Guest!
greet("Ashish") # Output: Hello, Ashish!
You can call functions using parameter names:
def greet(name, age):
print(name, "is", age, "years old.")
greet(age=20, name="Ashish") # Output: Ashish is 20 years old.
Python functions are essential for creating structured, efficient, and reusable code. By learning to define functions with parameters and return values, you can build scalable and maintainable programs.
In Python, a lambda function is a small, anonymous function. It can take any number of arguments but can only have one expression. Lambda functions are often used when you need a function for a short period of time.
lambda arguments : expression
- lambda keyword is used to define the function.
- arguments are the inputs (like normal function parameters).
- expression is evaluated and returned.
(It is always a single line.)
add = lambda a, b: a + b
print(add(5, 3)) # Output: 8
map(), filter(), and sorted().
square = lambda x: x * x
print(square(4)) # Output: 16
multiply = lambda a, b, c: a * b * c
print(multiply(2, 3, 4)) # Output: 24
map()map() applies a function to each element in a list.
nums = [1, 2, 3, 4, 5]
squares = list(map(lambda x: x**2, nums))
print(squares) # [1, 4, 9, 16, 25]
filter()filter() selects items based on a condition.
nums = [10, 15, 20, 25, 30]
even = list(filter(lambda x: x % 2 == 0, nums))
print(even) # [10, 20, 30]
sorted()sorted() can use a lambda to customize sorting.
students = [("Alice", 25), ("Bob", 20), ("Charlie", 23)]
# Sort by age
sorted_students = sorted(students, key=lambda x: x[1])
print(sorted_students)
# Output: [('Bob', 20), ('Charlie', 23), ('Alice', 25)]
map() and lambda, convert a list of temperatures from Celsius to Fahrenheit.filter() and lambda to find numbers divisible by 5 in a list.[("apple", 50), ("banana", 20), ("cherry", 30)] by price using a
lambda.
In Python, an array is a collection of elements of the same type.
Arrays are useful when you need to store multiple values in a single variable and perform operations on
them.
Unlike lists, arrays are more memory-efficient and require importing the array module.
To use arrays, you need to import the array module:
import array as arr
numbers = arr.array('i', [1, 2, 3, 4, 5])
print(numbers) # array('i', [1, 2, 3, 4, 5])
- The first argument 'i' specifies the **type code** (here, integer).
- Common type codes: 'i' → int, 'f' → float, 'u' → Unicode
character.
print(numbers[0]) # 1
print(numbers[3]) # 4
numbers[1] = 10
print(numbers) # array('i', [1, 10, 3, 4, 5])
append(x) → Add an element at the endinsert(i, x) → Insert element at position iremove(x) → Remove first occurrence of xpop() → Remove last elementindex(x) → Returns first index of xreverse() → Reverse the arraynumbers.append(6)
numbers.insert(2, 7)
numbers.remove(3)
numbers.pop()
print(numbers) # array('i', [1, 10, 7, 4])
for num in numbers:
print(num)
# Output:
# 1
# 10
# 7
# 4
Python is an object-oriented programming (OOP) language. In Python, a class is a blueprint for creating objects, and an object is an instance of a class. Classes allow you to group data (attributes) and functions (methods) together.
class Person:
def __init__(self, name, age):
self.name = name # attribute
self.age = age # attribute
def greet(self):
print(f"Hello, my name is {self.name} and I am {self.age} years old.")
p1 = Person("Alice", 25)
p2 = Person("Bob", 30)
p1.greet() # Hello, my name is Alice and I am 25 years old.
p2.greet() # Hello, my name is Bob and I am 30 years old.
- Attributes are variables that belong to an object.
- Methods are functions that belong to an object.
print(p1.name) # Alice
print(p2.age) # 30
__init__ Method
The __init__ method is called automatically when an object is created.
It is used to initialize the attributes of the object.
Car with attributes brand and year, and a
method that prints these details.Car class and display their details.Person class that calculates the year of birth using the age
attribute.Rectangle with width and height, and a method to calculate the area.
In Python, inheritance is a feature of object-oriented programming that allows a class (child class) to inherit attributes and methods from another class (parent class). Inheritance helps in code reusability and makes programs easier to maintain.
class Parent:
# parent class code
class Child(Parent):
# child class code
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def greet(self):
print(f"Hello, my name is {self.name}")
# Child class inherits from Person
class Student(Person):
def __init__(self, name, age, student_id):
super().__init__(name, age) # call parent constructor
self.student_id = student_id
def display_id(self):
print(f"My student ID is {self.student_id}")
# Creating objects
s1 = Student("Alice", 20, "S101")
s1.greet() # Inherited method → Hello, my name is Alice
s1.display_id() # Child class method → My student ID is S101
Vehicle with a method vehicle_type(). Create a child
class Car that inherits it and adds a method car_brand().Grandparent → Parent → Child with a method in each
class and call them from the child object.Teacher class that inherits from a Person class and adds a
subject attribute. Create an object and display all details.In Python, an iterator is an object that allows you to traverse through all the elements of a collection (like lists, tuples, or dictionaries) one by one. Iterators are used with loops and are memory-efficient because they do not store all elements at once.
iter() function, which is used to
traverse an iterable.my_list = [1, 2, 3, 4]
# Get an iterator using iter()
my_iter = iter(my_list)
# Access elements using next()
print(next(my_iter)) # 1
print(next(my_iter)) # 2
print(next(my_iter)) # 3
print(next(my_iter)) # 4
# next(my_iter) # Raises StopIteration
Iterators are commonly used with for loops, which handle the StopIteration automatically.
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
# Output:
# apple
# banana
# cherry
class Counter:
def __init__(self, low, high):
self.current = low
self.high = high
def __iter__(self):
return self
def __next__(self):
if self.current > self.high:
raise StopIteration
else:
self.current += 1
return self.current - 1
# Using the custom iterator
for num in Counter(1, 5):
print(num)
# Output: 1 2 3 4 5
next().iter() and next() with examples.for loop.
In Python, polymorphism means the ability of a function, method, or object to take multiple forms. It allows the same operation to behave differently on different data types or classes.
The same function name can work with different data types.
def add(a, b):
return a + b
print(add(5, 10)) # Output: 15 (integers)
print(add("Hello ", "World")) # Output: Hello World (strings)
print(add([1, 2], [3, 4])) # Output: [1, 2, 3, 4] (lists)
Different classes can have methods with the same name, performing different tasks.
class Dog:
def speak(self):
print("Woof!")
class Cat:
def speak(self):
print("Meow!")
animals = [Dog(), Cat()]
for animal in animals:
animal.speak()
# Output:
# Woof!
# Meow!
Child classes can override methods of the parent class while maintaining the same method name.
class Vehicle:
def start(self):
print("Vehicle starts")
class Car(Vehicle):
def start(self):
print("Car starts")
v = Vehicle()
c = Car()
v.start() # Vehicle starts
c.start() # Car starts
Bird and Fish with a method move(), each
printing different outputs. Call move() for both objects.Shape and child classes
Circle and Square.
In Python, scope refers to the region of the program where a variable is accessible. Understanding scope is important to avoid naming conflicts and to know where a variable can be used.
print(),
len(), etc.
def greet():
name = "Alice" # Local variable
print(name)
greet() # Output: Alice
# print(name) # Error: name is not defined outside the function
name = "Bob" # Global variable
def greet():
print(name) # Can access global variable
greet() # Output: Bob
print(name) # Output: Bob
global KeywordTo modify a global variable inside a function, use the global keyword.
x = 10
def modify():
global x
x = 20
modify()
print(x) # Output: 20
def outer():
x = "Outer variable"
def inner():
print(x) # Accesses variable from enclosing function
inner()
outer() # Output: Outer variable
global keyword.In Python, a module is a file containing Python code, such as functions, classes, or variables, that can be imported and used in other Python programs. Modules help organize code, make it reusable, and improve readability.
Create a Python file (e.g., mymodule.py) with functions or variables:
# mymodule.py
def greet(name):
print(f"Hello, {name}!")
pi = 3.14159
# main.py
import mymodule
mymodule.greet("Alice") # Output: Hello, Alice!
print(mymodule.pi) # Output: 3.14159
from mymodule import greet
greet("Bob") # Output: Hello, Bob!
import mymodule as mm
mm.greet("Charlie") # Output: Hello, Charlie!
Python provides many built-in modules, such as:
math – mathematical operationsrandom – generate random numbersdatetime – work with dates and timesos – operating system functionalitysys – system-specific parameters and functionsimport math
print(math.sqrt(16)) # Output: 4.0
import random
print(random.randint(1, 10)) # Output: Random number between 1 and 10
calculator.py with functions for addition, subtraction, multiplication,
and division. Import and use it in another file.sqrt() function from the math module and calculate the
square root of 49.random module to generate a random number between 50 and 100.In Python, the datetime module is used to work with dates and times. It allows you to create, manipulate, and format date and time objects easily.
import datetime
now = datetime.datetime.now()
print(now) # Output: 2025-09-29 13:45:12.345678
print(now.year) # Current year
print(now.month) # Current month
print(now.day) # Current day
my_date = datetime.datetime(2025, 12, 25)
print(my_date) # Output: 2025-12-25 00:00:00
You can format dates using the strftime() method:
today = datetime.datetime.now()
print(today.strftime("%Y-%m-%d")) # 2025-09-29
print(today.strftime("%d/%m/%Y")) # 29/09/2025
print(today.strftime("%A, %B %d")) # Monday, September 29
The timedelta class allows you to add or subtract days, seconds, or other time intervals.
from datetime import datetime, timedelta
today = datetime.now()
tomorrow = today + timedelta(days=1)
yesterday = today - timedelta(days=1)
print("Tomorrow:", tomorrow)
print("Yesterday:", yesterday)
DD-MM-YYYY and Month Day, Year.timedelta.In Python, the math module provides a wide range of mathematical functions and constants. It is commonly used for advanced mathematical operations like square root, trigonometry, factorials, and more.
import math
math.sqrt(x) – Returns the square root of x.math.pow(x, y) – Returns x raised to the power y.math.ceil(x) – Returns the smallest integer greater than or equal to x.
math.floor(x) – Returns the largest integer less than or equal to x.math.factorial(x) – Returns the factorial of x.math.gcd(x, y) – Returns the greatest common divisor of x and
y.
math.sin(x), math.cos(x), math.tan(x) – Trigonometric functions (x in radians).import math
print(math.sqrt(16)) # 4.0
print(math.pow(2, 3)) # 8.0
print(math.ceil(4.2)) # 5
print(math.floor(4.8)) # 4
print(math.factorial(5)) # 120
print(math.gcd(12, 18)) # 6
print(math.sin(math.pi/2))# 1.0
math.pi – Value of π (3.14159…)math.e – Value of Euler’s number e (2.71828…)math.pow().math.ceil() and math.floor() on 7.3 and 7.7 and print results.math.factorial().
In Python, JSON (JavaScript Object Notation) is a popular data format used for
exchanging data between a server and a client.
Python provides the json module to work with JSON data, allowing you to convert between
Python objects and JSON strings.
import json
Use json.dumps() to convert Python objects to JSON strings:
import json
data = {
"name": "Alice",
"age": 25,
"city": "New York"
}
json_string = json.dumps(data)
print(json_string)
# Output: {"name": "Alice", "age": 25, "city": "New York"}
Use json.loads() to parse a JSON string back into a Python object:
json_data = '{"name": "Bob", "age": 30, "city": "London"}'
python_obj = json.loads(json_data)
print(python_obj)
# Output: {'name': 'Bob', 'age': 30, 'city': 'London'}
print(python_obj["name"]) # Bob
import json
with open("data.json", "r") as file:
data = json.load(file)
print(data)
import json
data = {"name": "Charlie", "age": 28, "city": "Paris"}
with open("data.json", "w") as file:
json.dump(data, file)
{"fruit": "apple", "quantity": 10} to a JSON string.'{"name": "Eve", "age": 22}' into a Python dictionary and print
the age.json.load() and json.loads().
In Python, RegEx (Regular Expressions) is a powerful tool for searching, matching, and
manipulating strings.
Python provides the re module to work with regular expressions.
import re
re.match(pattern, string) – Checks if the string starts with the pattern.re.search(pattern, string) – Searches the entire string for the pattern.re.findall(pattern, string) – Returns a list of all matches in the string.re.split(pattern, string) – Splits the string by the pattern.re.sub(pattern, replacement, string) – Replaces occurrences of the pattern with the
replacement.import re
text = "My phone number is 123-456-7890"
pattern = r"\d{3}-\d{3}-\d{4}"
match = re.search(pattern, text)
if match:
print("Found:", match.group())
# Output: Found: 123-456-7890
text = "Email me at alice@example.com or bob@example.com"
pattern = r"[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}"
emails = re.findall(pattern, text)
print(emails)
# Output: ['alice@example.com', 'bob@example.com']
text = "I love cats"
new_text = re.sub(r"cats", "dogs", text)
print(new_text)
# Output: I love dogs
re.sub().re.split().re.match() and re.search() with examples.
PIP stands for "Python Package Installer". It is a tool used to install and manage Python packages from the Python Package Index (PyPI). Using PIP, you can easily add external libraries to your Python projects.
pip --version
# Output example: pip 23.1.2 from /usr/lib/python3/site-packages/pip (python 3.10)
pip install package_name
# Example:
pip install requests
pip install --upgrade package_name
# Example:
pip install --upgrade requests
pip uninstall package_name
# Example:
pip uninstall requests
pip list
pip search keyword
# Example:
pip search flask
numpy package using PIP.numpy package to the latest version.numpy package using PIP.requests.In Python, the try…except block is used to handle exceptions (errors) gracefully. Instead of stopping the program when an error occurs, you can catch the error and take appropriate action.
try:
# Code that might raise an exception
except ExceptionType:
# Code to handle the exception
try:
x = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
# Output: Cannot divide by zero!
try:
x = int(input("Enter a number: "))
y = 10 / x
except ValueError:
print("Invalid input! Please enter a number.")
except ZeroDivisionError:
print("Cannot divide by zero!")
else and finally
- else block executes if no exception occurs.
- finally block executes regardless of whether an exception occurred or not.
try:
x = 10 / 2
except ZeroDivisionError:
print("Cannot divide by zero!")
else:
print("Division successful!")
finally:
print("Execution complete.")
# Output:
# Division successful!
# Execution complete.
ValueError when a user enters a non-integer value.ZeroDivisionError when dividing two numbers input by the user.finally to print a message after executing a try…except block, regardless of
errors.FileNotFoundError gracefully.In Python, the input() function is used to take input from the user. By default, the input is taken as a string, but it can be converted into other data types as needed.
variable = input("Enter something: ")
name = input("Enter your name: ")
print("Hello, " + name + "!")
age = int(input("Enter your age: "))
print("You are", age, "years old.")
price = float(input("Enter the price: "))
print("The price is", price)
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
sum = a + b
print("Sum:", sum)
In Python, string formatting allows you to create strings dynamically by inserting variables or expressions into them. It makes your output readable and customizable.
% Operatorname = "Alice"
age = 25
print("My name is %s and I am %d years old." % (name, age))
# Output: My name is Alice and I am 25 years old.
str.format() Methodname = "Bob"
age = 30
print("My name is {} and I am {} years old.".format(name, age))
# Output: My name is Bob and I am 30 years old.
# Using positional arguments
print("I am {1} years old and my name is {0}.".format(name, age))
name = "Charlie"
age = 28
print(f"My name is {name} and I am {age} years old.")
# Output: My name is Charlie and I am 28 years old.
# Using expressions
print(f"Next year, I will be {age + 1} years old.")
# Output: Next year, I will be 29 years old.
pi = 3.14159265
print("Pi rounded to 2 decimal places: {:.2f}".format(pi))
# Output: Pi rounded to 2 decimal places: 3.14
print(f"Pi rounded to 3 decimal places: {pi:.3f}")
# Output: Pi rounded to 3 decimal places: 3.142
% operator.str.format() to print a sentence with your favorite color and hobby.
In Python, file handling allows you to create, read, update, and delete files.
The built-in open() function is used to work with files in different modes.
# Open a file in read mode
file = open("example.txt", "r") # "r" = read mode
content = file.read()
print(content)
file.close()
"r" – Read (default), file must exist"w" – Write, creates a new file or truncates existing file"a" – Append, adds content to the end of the file"x" – Create, creates a new file, fails if file exists"b" – Binary mode (used with other modes, e.g., "rb", "wb")file = open("example.txt", "w")
file.write("Hello, World!\n")
file.write("Python File Handling")
file.close()
file = open("example.txt", "a")
file.write("\nThis is appended text.")
file.close()
with StatementThe with statement automatically closes the file after its block finishes:
with open("example.txt", "r") as file:
content = file.read()
print(content)
with open("example.txt", "r") as file:
for line in file:
print(line.strip()) # Remove newline characters
data.txt and write your name and age into it.data.txt and print it line by line.data.txt containing your favorite hobby.with statement to read and print the file content.In Python, the Requests library is used to send HTTP requests easily. It allows you to interact with web services, APIs, and websites by sending GET, POST, PUT, DELETE, and other HTTP requests.
pip install requests
import requests
response = requests.get("https://jsonplaceholder.typicode.com/posts/1")
print(response.status_code) # 200
print(response.text) # JSON data as string
print(response.json()) # JSON data as Python dictionary
import requests
data = {"title": "foo", "body": "bar", "userId": 1}
response = requests.post("https://jsonplaceholder.typicode.com/posts", json=data)
print(response.status_code) # 201
print(response.json()) # Response data
headers = {"Authorization": "Bearer YOUR_TOKEN"}
response = requests.get("https://api.example.com/data", headers=headers)
print(response.json())
params = {"userId": 1}
response = requests.get("https://jsonplaceholder.typicode.com/posts", params=params)
print(response.json())
https://api.github.com.https://jsonplaceholder.typicode.com/posts with custom data and
print the response.response.text and response.json().
BeautifulSoup is a powerful Python library used for web scraping. It helps you parse
and navigate
HTML or XML documents to extract specific information such as titles, links, tables, and text data.
It’s often used alongside the requests library to download webpage content and then process
it locally.
pip install beautifulsoup4
pip install requests
After installation, import both libraries in your Python file to start scraping:
from bs4 import BeautifulSoup
import requests
from bs4 import BeautifulSoup
import requests
url = "https://example.com"
response = requests.get(url)
soup = BeautifulSoup(response.text, "html.parser")
print(soup.title.text) # Print the page title
print(soup.find("p").text) # Print the first paragraph
# Find first <h1> tag
h1_tag = soup.find("h1")
print(h1_tag.text)
# Find all <p> tags
paragraphs = soup.find_all("p")
for p in paragraphs:
print(p.text)
link = soup.find("a")
print(link["href"]) # Get href attribute of the first <a> tag
# Find elements by CSS selectors
titles = soup.select("h2.article-title")
for title in titles:
print(title.text)
# Find elements by class or ID
content = soup.select_one("#main-content")
print(content.text)
# Extract all hyperlinks
for a in soup.find_all("a", href=True):
print(a["href"])
# Extract all image sources
for img in soup.find_all("img", src=True):
print(img["src"])
# Extract all text content from the page
print(soup.get_text())
.text.
Fix: Add a condition:
if tag:
print(tag.text)
response.encoding = "utf-8" before parsing.
https://example.com.
<a> tags) and print their URLs.find() and find_all() in BeautifulSoup.
select() to extract all headings with a specific CSS class.
BeautifulSoup is an essential tool for ethical hackers, data analysts, and developers who want to
automate
information gathering. When combined with Python libraries like requests,
pandas, or
re, it becomes a powerful way to extract and structure data from any website efficiently.
Python is one of the most widely used languages in cybersecurity due to its simplicity and the powerful libraries it provides for networking, automation, and ethical hacking. Building real-world projects is the best way to strengthen your understanding of security concepts and practical hacking skills.
Perfect for those just starting out in cybersecurity and Python. These projects help you understand the basics of networking, automation, and data handling.
socket module to
find open ports on a target system.scapy to
understand how data travels in networks.requests and
BeautifulSoup to identify outdated headers or open directories.
These projects involve multiple libraries and simulate real-world security automation tasks and penetration testing workflows.
scapy and
socket to detect suspicious packet patterns.
PIL or OpenCV.
scikit-learn to detect fake or malicious URLs.
cryptography module.
For professionals who want to master ethical hacking automation, real-time monitoring, and AI-powered defense systems.
TensorFlow or
PyTorch to classify files as safe or malicious.
socket and ssl modules
to create a secure communication channel.Flask or Django.socket library and display all open ports for a
given IP.cryptography module.These projects help you move from basic scripting to real-world cybersecurity applications. Each one enhances your Python skills while preparing you for ethical hacking, network defense, and security automation tasks.
Welcome to the Elite Python Series — a rapid, hands-on course designed to help you master Python programming from fundamentals to advanced topics in the shortest time possible. Each topic in this series includes detailed explanations, examples, and practice questions to strengthen your concepts.
🎓 Certification Notice: To receive your official Elite Python Series Certification, you must register yourself for the program. Registration gives you access to live sessions, assignments, evaluation tests, and a personalized digital certificate upon completion.
👉 Register now for the Elite Python Series Certification through the official Cyber_Squad6351 platform to begin your certified Python learning journey.
In Python, the Requests library is one of the most popular tools for working with the web. It allows you to send HTTP requests to interact with websites, APIs, and servers effortlessly — enabling everything from downloading data to automating web interactions in a few lines of code.
pip install requests
import requests
response = requests.get("https://jsonplaceholder.typicode.com/posts/1")
print(response.status_code) # 200 means OK
print(response.text) # Prints the response body as text
print(response.json()) # Converts JSON response into a Python dictionary
import requests
data = {"title": "foo", "body": "bar", "userId": 1}
response = requests.post("https://jsonplaceholder.typicode.com/posts", json=data)
print(response.status_code) # 201 means created successfully
print(response.json()) # Prints the newly created resource details
headers = {"Authorization": "Bearer YOUR_TOKEN"}
response = requests.get("https://api.example.com/data", headers=headers)
print(response.json())
params = {"userId": 1}
response = requests.get("https://jsonplaceholder.typicode.com/posts", params=params)
print(response.json())
https://api.github.com.https://jsonplaceholder.typicode.com/posts with custom data and print the response.response.text and response.json().The Requests library simplifies the way you interact with the web — making API integration, automation, and data retrieval in Python smooth and intuitive. Once you master Requests, you’ll have a strong foundation for projects involving APIs, data collection, and web automation.
💡 Tip: Complete this lesson and take the short quiz available after registration to earn progress points toward your Elite Python Certification.
BeautifulSoup is another essential Python library, mainly used for web scraping.
It helps you parse HTML or XML documents and extract meaningful data such as titles, links, images, or table data.
When combined with the requests library, it becomes a complete toolset for web data extraction and automation.
pip install beautifulsoup4
pip install requests
from bs4 import BeautifulSoup
import requests
url = "https://example.com"
response = requests.get(url)
soup = BeautifulSoup(response.text, "html.parser")
print(soup.title.text)
print(soup.find("p").text)
# Find first
tag h1_tag = soup.find("h1") print(h1_tag.text) # Find all
tags paragraphs = soup.find_all("p") for p in paragraphs: print(p.text)
link = soup.find("a")
print(link["href"]) # Get href attribute of the first tag
# Find elements by CSS selectors
titles = soup.select("h2.article-title")
for title in titles:
print(title.text)
# Find elements by class or ID
content = soup.select_one("#main-content")
print(content.text)
# Extract all hyperlinks
for a in soup.find_all("a", href=True):
print(a["href"])
# Extract all image sources
for img in soup.find_all("img", src=True):
print(img["src"])
# Extract all text content from the page
print(soup.get_text())
https://example.com.<a> tags and print their URLs.select() to extract all headings with a specific CSS class.
Together, Requests and BeautifulSoup make an unbeatable combination
for building web scrapers, automation tools, and research applications.
These are core skills every certified Python developer should master before advancing to
complex frameworks like Django, Flask, or FastAPI.
Python is a versatile, high-level programming language widely used for web development, data science, automation, artificial intelligence, cybersecurity, and scripting. Its simple syntax and massive ecosystem of libraries make it ideal for both beginners and professionals. Popular frameworks like Django and Flask enable powerful web apps, while NumPy, Pandas, and TensorFlow power data-driven applications.
Python’s popularity comes from its readability, cross-platform support, and vast community. It allows developers to build projects quickly without worrying about complex syntax. From automation scripts to enterprise-level web apps, Python is used everywhere. It also integrates easily with C, C++, Java, and APIs—making it a go-to language in 2025.
Python includes several developer-friendly features:
Python is heavily used across:
To install Python:
python --version to verify the installation.
The best IDE depends on your workflow:
Save your Python code in a file with the .py extension (for example, hello.py).
Then open your terminal or command prompt and run:
python hello.py
This will execute your program. You can also run Python code inside IDEs like VS Code, PyCharm, or
Jupyter.
Libraries and modules are reusable pieces of code that add functionality to your Python programs. For example:
pip install <library-name>.
Start by understanding core concepts like variables, loops, and functions. Then, move on to projects—automation scripts, small games, or data analysis tasks. Practice regularly, read official documentation, and explore open-source projects on GitHub. Joining Python communities (Reddit, Discord, or Stack Overflow) also accelerates your learning.
Yes! Python is one of the most used languages in cybersecurity. You can create network scanners, brute-force tools, packet sniffers, and vulnerability checkers. Libraries like Scapy, Socket, and Requests make it easy to interact with networks and servers. Always use these tools ethically and with permission.
Python 3.12+ introduces performance boosts, more precise error messages, and improved type hinting. These updates help developers write faster and more reliable code. You can check the latest release notes on the official Python documentation.
Yes, Python is completely free and open-source. It is maintained by the Python Software Foundation (PSF) and has a global community of contributors. You can use it for personal, academic, or commercial purposes without paying any licensing fees.