0% found this document useful (0 votes)
6 views66 pages

CONTENT -Python Programming

Chapter 1 introduces Python as a high-level programming language known for its simplicity and versatility, covering its history, features, and applications. It also discusses installation procedures for Python and popular IDEs, along with basic syntax essentials. Chapter 2 focuses on variables, data types, and operators in Python, explaining the dynamic typing nature of the language and providing an overview of common data types and type conversion methods.

Uploaded by

yesudossj
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views66 pages

CONTENT -Python Programming

Chapter 1 introduces Python as a high-level programming language known for its simplicity and versatility, covering its history, features, and applications. It also discusses installation procedures for Python and popular IDEs, along with basic syntax essentials. Chapter 2 focuses on variables, data types, and operators in Python, explaining the dynamic typing nature of the language and providing an overview of common data types and type conversion methods.

Uploaded by

yesudossj
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 66

Chapter 1:

Introduction to Python

Python is a high-level, general-purpose programming language developed by


Guido van Rossum and first released in 1991. It is widely known for its simple
syntax, which makes it easy to read and write. Python supports multiple
programming paradigms, including procedural, object-oriented, and functional
programming.
Python is an interpreted language, meaning code is executed line by line, which
simplifies debugging and development. It is open-source and has a large
community, contributing to a vast ecosystem of libraries and frameworks. Python
is commonly used in web development, data analysis, artificial intelligence,
machine learning, automation, and more.Due to its versatility and ease of use,
Python has become one of the most popular programming languages in the world.

1.1 History of Python


Python was created by Guido van Rossum in the late 1980s and was officially
released in 1991. The idea behind Python was to develop an easy-to-read and easy-
to-use programming language that also had the power of more complex languages
like C.
Van Rossum started working on Python during his time at the Centrum Wiskunde
& Informatica (CWI) in the Netherlands. He wanted to create a language that
would overcome the limitations of the ABC language, which was also developed at
CWI.
The name "Python" was inspired not by the snake, but by the British comedy group
Monty Python, reflecting Van Rossum's aim to make programming fun.
Key milestones:
1991: First official release (Python 0.9.0), with features like classes, functions,
exceptions, and core data types.
2000: Python 2.0 was released, introducing features like list comprehensions and
garbage collection.

1
2008: Python 3.0 launched, not fully backward compatible with Python 2.x,
focused on removing legacy issues.
2020: Official end of support for Python 2.x.
Present: Python continues to grow in popularity and is widely used in areas like
data science, AI, web development, and automation.
1.2 Features of Python:
Python is a powerful and versatile programming language known for its
simplicity and readability. It is easy to learn and use, making it an excellent choice
for both beginners and experienced developers. Since it is an interpreted language,
Python executes code line by line, which simplifies debugging and testing. Being a
high-level language, it handles complex programming details such as memory
management automatically.
Python uses dynamic typing, so you don’t need to declare the type of variables
explicitly. It supports multiple programming paradigms, including object-oriented,
procedural, and functional programming. One of Python’s strengths is its large
standard library, which provides tools and modules for a wide range of tasks,
including file handling, regular expressions, networking, and web services.
Python is cross-platform, meaning it can run on different operating systems like
Windows, macOS, and Linux without modification. Its vast ecosystem includes
thousands of third-party packages that extend its capabilities in areas like web
development, machine learning, data analysis, and automation. Python can also be
embedded in other languages like C or C++, making it highly extensible.
Additionally, it supports the development of graphical user interfaces through
libraries such as Tkinter and PyQt.
Thanks to its clear syntax and wide community support, Python is widely used for
rapid application development, scripting, and prototyping across many industries.
1.3 Applications of Python
Python is used in a wide range of applications across various industries due
to its simplicity, versatility, and extensive libraries. In web development, Python is
popular for building server-side applications using frameworks like Django and
Flask. In the field of data science and machine learning, Python is a dominant
language, supported by powerful libraries such as NumPy, Pandas, Matplotlib,
Scikit-learn, and TensorFlow. It is also widely used in automation and scripting to

2
write programs that automate repetitive tasks, such as file handling, web scraping,
and system administration. In software development, Python is often used for
creating desktop applications, games, and command-line tools. Additionally,
Python plays a significant role in the development of artificial intelligence and
deep learning systems. It is used in the scientific and academic community for
simulations, research, and data analysis. Python is also commonly used in the
finance industry for quantitative and algorithmic trading. Its role in embedded
systems, IoT projects, and network programming further highlights its flexibility
and growing relevance in modern technology
1.4 Installing Python and IDEs (IDLE, VS Code, PyCharm)
To start programming in Python, you need to install Python itself and
optionally choose an Integrated Development Environment (IDE) to write and run
your code more efficiently. Below is a guide on installing Python and popular
IDEs like IDLE, Visual Studio Code (VS Code), and PyCharm.
Installing Python
To install Python, follow these steps:
Go to the official Python website:
https://www.python.org/downloads/
Download the latest version suitable for your operating system (Windows, macOS,
or Linux).
Run the installer:
On Windows, make sure to check the box "Add Python to PATH" before clicking
"Install Now."
On macOS and Linux, you may need to use terminal commands if it’s not installed
by default.
After installation, open a terminal or command prompt and type:
To verify that Python is installed correctly.
IDLE (Integrated Development and Learning Environment)
IDLE comes installed with Python, so you don’t need to install it separately.
To open it:

3
On Windows, search for IDLE in the Start Menu.
On macOS/Linux, type idle or idle3 in the terminal.
IDLE is lightweight and suitable for beginners. It includes a simple code editor and
an interactive shell.
Installing Visual Studio Code (VS Code)
Download VS Code from:
https://code.visualstudio.com/
Install it like any regular application.
Install the Python extension:
Open VS Code.
Go to the Extensions panel (Ctrl+Shift+X or Cmd+Shift+X).
Search for "Python" and install the extension provided by Microsoft.
After setting up, you can create .py files and run them directly from VS Code.
Installing PyCharm
Download PyCharm from:
https://www.jetbrains.com/pycharm/download/
Choose between:
Community Edition (free and suitable for most users)
Professional Edition (paid, includes advanced features for web development,
database tools, etc.)
Install PyCharm and set the interpreter to the version of Python you installed.
PyCharm is a powerful IDE, especially useful for larger projects and professional
development.
1.5 Python syntax basics
Python syntax is designed to be simple and readable, making it easy for
beginners to learn and use. Here's a basic overview of Python syntax essentials:
1. Printing Output
4
To display something on the screen, use the print() function:
print("Hello, world!")
2. Variables and Data Types
You don’t need to declare variable types in Python:
name = "Alice" # String
age = 25 # Integer
height = 5.6 # Float
is_student = True # Boolean
3. Indentation
Python uses indentation (spaces or tabs) to define blocks of code instead of
braces {}:
if age > 18:
print("Adult")
else:
print("Minor")
4. Comments
Use # for single-line comments:
# This is a comment
Use triple quotes for multi-line comments or docstrings:
"""
This is a
multi-line comment
"""
5. Input from User
To take input from the user:
name = input("Enter your name: ")

5
print("Hello, " + name)
6. Control Structures
Conditional Statements:
if age >= 18:
print("You can vote.")
elif age == 17:
print("Almost there!")
else:
print("Too young to vote.")
Loops:
# For loop
for i in range(5):
print(i)
# While loop
count = 0
while count < 5:
print(count)
count += 1
7. Functions
Define and call functions using def:
def greet(name):
print("Hello, " + name)
greet("Alice")
8. Lists
Lists are ordered, mutable collections:

6
Chapter 2:
Variables, Data Types, and Operators

In Python, variables are used to store data, and they don't require
explicit declaration of their type, making Python a dynamically typed language. A
variable is created by simply assigning a value to a name using the assignment
operator =. For example, x = 10 creates a variable x and assigns it the integer value
of 10. Data types in Python include basic types like integers (int), floating-point
numbers (float), and strings (str). There are also boolean values (True or False),
lists, tuples, dictionaries, sets, and more complex types. Python automatically
determines the type of a variable based on the assigned value, which is why it's
referred to as dynamically typed. In addition to variables and data types, operators
in Python are used to perform operations on variables and values. These include
arithmetic operators like +, -, *, and / for performing mathematical calculations.
Python also supports comparison operators like ==, !=, <, >, and logical operators
like and, or, and not. These operators are essential for controlling the flow of
programs through conditional statements and loops. Understanding how to use
variables, data types, and operators effectively forms the foundation of
programming in Python, allowing developers to manipulate data and create more
complex functionalities.
2.1 Variables and Constants
In Python, variables are used to store data that can be changed during the
execution of a program. A variable is essentially a name that refers to a value in
memory, and it is created by assigning a value to a name using the assignment
operator =. For example, age = 25 creates a variable age and assigns it the value
25. The value of a variable can be modified during runtime. Python is a
dynamically typed language, meaning that variables do not need to be explicitly
declared with a type—Python automatically determines the type based on the
assigned value.
On the other hand, constants are values that are meant to remain unchanged
throughout the execution of a program. While Python does not have built-in
constant types, it is a common convention to use uppercase letters for constants.

7
For example, PI = 3.14159 is a constant in Python, and by convention, it should not
be modified during the program's execution. Although Python does not enforce
immutability of constants, developers rely on this naming convention to signal that
the value should remain constant.
Both variables and constants are fundamental in programming as they store data,
but the key difference lies in whether the data is intended to change or stay the
same throughout the program.
2.2 Data Types: int, float, str, bool, list, tuple, dict, set
In Python, data types define the kind of value a variable can hold. Understanding
these basic data types is crucial for writing effective Python programs. Here's a
look at the most commonly used ones:

1. int (Integer)
An int is a whole number, either positive or negative, without any decimal points.
It is used to represent values like counts, ages, or quantities.
Example:
age = 25
2. float (Floating-point number)
A float is a number that has a decimal point. It’s used to represent real numbers or
numbers that require precision, such as measurements, currency, or scientific data.
Example:
price = 19.99
3. str (String)
A str is used to represent text. A string can contain letters, numbers, symbols, or
spaces and is enclosed in either single quotes (') or double quotes (").
Example:
name = "Alice"
4. bool (Boolean)

8
A bool represents one of two possible values: True or False. It is often used in
conditional statements to evaluate expressions or conditions.
Example:
is_student = True
5. list
A list is a collection of ordered, mutable items. Lists can store different data types
in a single collection, and their elements are indexed. You can modify a list after it
is created
fruits = ["apple", "banana", "cherry"]
6. tuple
A tuple is similar to a list, but it is immutable (cannot be changed after creation).
Tuples are often used for fixed collections of items. They are defined by enclosing
items in parentheses (()).
Example:
coordinates = (10.5, 20.7)
7. dict (Dictionary)
A dict is an unordered collection of key-value pairs. Each item in a dictionary is
accessed via its key rather than an index. Keys must be unique, while values can be
of any data type.
Example:
person = {"name": "John", "age": 30}
8. set
A set is an unordered collection of unique items. It is useful when you need to store
values without duplicates and perform set operations like unions and intersections.
Example:
colors = {"red", "green", "blue"}
2.3 Type Conversion

9
In Python, type conversion refers to the process of converting one data type into
another. This is essential when performing operations between different types or
when specific types are required by certain functions or methods. Python provides
several ways to perform type conversion, which can be broadly classified into
implicit and explicit conversion.
2.3.1 Implicit Type Conversion (Automatic)
Python automatically converts one data type to another when it is required, which
is known as implicit type conversion or type coercion. This happens when you mix
different types in an operation, and Python implicitly converts the data types to a
compatible type.
For example:
x = 10 # int
y = 3.14 # float
result = x + y # Python automatically converts x to float
print(result) # Output: 13.14
Here, x (an integer) is automatically converted to a float during the addition
operation.
2.3.2 Explicit Type Conversion (Manual)
Explicit type conversion is when you manually convert one data type to another
using built-in functions. This is often necessary when you need to ensure a specific
type for a variable, especially when working with user input or when you want to
perform operations that require matching types.
Python provides several built-in functions to convert between types:
int() – Converts a value to an integer
x = "42"
y = int(x) # Converts string to integer
print(y) # Output: 42
float() – Converts a value to a float
x = "3.14"

10
y = float(x) # Converts string to float
print(y) # Output: 3.14
str() – Converts a value to a string
x = 123
y = str(x) # Converts integer to string
print(y) # Output: "123"
bool() – Converts a value to a boolean
x=0
y = bool(x) # Converts integer to boolean (0 is False, any non-zero number is
True)
print(y) # Output: False
list() – Converts an iterable (like a tuple or string) to a list
x = (1, 2, 3)
y = list(x) # Converts tuple to list
print(y) # Output: [1, 2, 3]
tuple() – Converts an iterable to a tuple
x = [1, 2, 3]
y = tuple(x) # Converts list to tuple
print(y) # Output: (1, 2, 3)
set() – Converts an iterable to a set
x = [1, 2, 2, 3]
y = set(x) # Converts list to set (removes duplicates)
print(y) # Output: {1, 2, 3}
dict() – Converts a list of tuples into a dictionary
x = [("name", "Alice"), ("age", 25)]
y = dict(x) # Converts list of tuples to a dictionary

11
print(y) # Output: {'name': 'Alice', 'age': 25}

2.3.3 Type Conversion with User Input


When taking input from the user, the input() function returns a string. If you
need to work with numbers, you will need to explicitly convert the input into the
desired type using int(), float(), or other conversion functions.
Example:
age = input("Enter your age: ") # This will return a string
age = int(age) # Convert the input to an integer
print("Your age is:", age)
Type Conversion Between Compatible Types
String to Number (int/float): Strings that represent valid numbers can be converted
into integers or floats.
num_str = "123"
num = int(num_str) # Converts to integer
print(num) # Output: 123
Number to String: Any numeric type (integer or float) can be converted to a string
using the str() function.
num = 123
num_str = str(num) # Converts to string
print(num_str) # Output: "123"
2.4 Operators: Arithmetic, Comparison, Logical, Assignment
In Python, operators are special symbols that perform operations on variables
and values. Python supports several types of operators, each serving a specific
purpose. These operators are divided into five main categories: Arithmetic
Operators, Comparison Operators, Logical Operators, Assignment Operators, and
Bitwise Operators. Here’s an overview of each category:

12
1. Arithmetic Operators
Arithmetic operators are used to perform mathematical operations like
addition, subtraction, multiplication, division, and more.
+ : Addition (adds two values)
x = 10 + 5 # x = 15
- : Subtraction (subtracts the second value from the first)
x = 10 - 5 # x = 5
* : Multiplication (multiplies two values)
x = 10 * 5 # x = 50
/ : Division (divides the first value by the second, returns float)
x = 10 / 3 # x = 3.3333...
// : Floor Division (divides and returns the integer part of the quotient)
x = 10 // 3 # x = 3
% : Modulus (returns the remainder of the division)
x = 10 % 3 # x = 1
** : Exponentiation (raises the first number to the power of the second)
x = 2 ** 3 # x = 8
2. Comparison Operators
Comparison operators are used to compare two values and return a boolean
(True or False) based on the result of the comparison.
== : Equal to (checks if two values are equal)
5 == 5 # True
!= : Not equal to (checks if two values are not equal)
5 != 3 # True

13
> : Greater than (checks if the left value is greater than the right)
5 > 3 # True
< : Less than (checks if the left value is less than the right)
5 < 10 # True
>= : Greater than or equal to (checks if the left value is greater than or equal to the
right)
5 >= 5 # True
<= : Less than or equal to (checks if the left value is less than or equal to the right)
5 <= 10 # True
3. Logical Operators
Logical operators are used to combine conditional statements. They help in
determining the truth value of combined conditions.
and : Logical AND (returns True if both conditions are True)
x = (5 > 3) and (10 > 5) # True
or : Logical OR (returns True if at least one condition is True)
x = (5 > 3) or (10 < 5) # True
not : Logical NOT (reverses the logical state of its operand)
x = not(5 > 3) # False
4. Assignment Operators
Assignment operators are used to assign values to variables, and some of them
perform an operation while assigning the result.
= : Simple assignment (assigns a value to a variable)
x = 5 # x gets the value 5
+= : Add and assign (adds the right operand to the left operand and assigns the
result)
x=5
x += 3 # x becomes 8

14
-= : Subtract and assign (subtracts the right operand from the left operand and
assigns the result)
x=5
x -= 3 # x becomes 2
*= : Multiply and assign (multiplies the left operand by the right operand and
assigns the result)
x=5
x *= 3 # x becomes 15
/= : Divide and assign (divides the left operand by the right operand and assigns the
result)
x = 10
x /= 2 # x becomes 5.0
//= : Floor divide and assign (performs floor division and assigns the result)
x = 10
x //= 3 # x becomes 3
%= : Modulus and assign (performs modulus and assigns the result)
x = 10
x %= 3 # x becomes 1
**= : Exponentiation and assign (performs exponentiation and assigns the result)
x=2
x **= 3 # x becomes 8
5. Bitwise Operators
Bitwise operators are used to perform bit-level operations on binary numbers.
They are useful when you need to manipulate individual bits of data.
& : Bitwise AND (returns 1 if both bits are 1, otherwise 0)
5 & 3 # Result: 1 (binary: 0101 & 0011 = 0001)
| : Bitwise OR (returns 1 if at least one of the bits is 1)

15
5 | 3 # Result: 7 (binary: 0101 | 0011 = 0111)
^ : Bitwise XOR (returns 1 if only one of the bits is 1, but not both)
5 ^ 3 # Result: 6 (binary: 0101 ^ 0011 = 0110)
~ : Bitwise NOT (inverts the bits)
~5 # Result: -6 (binary: ~0101 = 1010 in two's complement)
<< : Left shift (shifts the bits of the number to the left by the specified number of
positions)
5 << 1 # Result: 10 (binary: 0101 << 1 = 1010)
>> : Right shift (shifts the bits of the number to the right by the specified number
of positions)
5 >> 1 # Result: 2 (binary: 0101 >> 1 = 0010)
Bitwise XOR (returns 1 if only one of the bits is 1, but not both)
5 ^ 3 # Result: 6 (binary: 0101 ^ 0011 = 0110)
~ : Bitwise NOT (inverts the bits)
~5 # Result: -6 (binary: ~0101 = 1010 in two's complement)
<< : Left shift (shifts the bits of the number to the left by the specified number of
positions)
5 << 1 # Result: 10 (binary: 0101 << 1 = 1010)
>> : Right shift (shifts the bits of the number to the right by the specified number
of positions)
5 >> 1 # Result: 2 (binary: 0101 >> 1 = 0010)

16
Chapter 3:
Control Flow
Control flow in Python refers to the order in which individual statements,
instructions, or function calls are executed or evaluated. Python provides several
tools to control the flow of a program, allowing developers to make decisions,
repeat tasks, and branch off in different directions based on conditions. The
primary control flow statements in Python include conditional statements, loops,
and loop control statements.
The most basic form of control flow is the conditional statement, using if, elif, and
else. These allow the program to make decisions and execute different blocks of
code depending on whether certain conditions are true. For example, an if
statement checks a condition, and if it's true, the corresponding block is executed.
If it’s false, the program can check other conditions using elif (else if) or fall back
to a default case using else.
Another essential part of control flow is loops, which are used to execute a block
of code multiple times. Python supports two types of loops: for loops and while
loops. A for loop is used to iterate over a sequence like a list, tuple, or string, and it
executes the block for each item in the sequence. A while loop, on the other hand,
continues to run as long as a specified condition remains true. Both loops are
commonly used for tasks such as processing items, repeating calculations, or
collecting data.
Python also provides loop control statements such as break, continue, and pass to
manage loop behavior more precisely. The break statement is used to exit the loop
prematurely, while continue skips the current iteration and moves to the next one.
The pass statement acts as a placeholder when no action is required.
Together, these control flow elements allow Python programs to make decisions
and repeat actions, forming the logical backbone of most software. Mastery of
control flow is essential for writing clear, efficient, and flexible code.
3.1 if, elif, else
In Python, if, elif, and else are conditional statements used to make decisions based
on certain conditions. These statements allow a program to execute different
blocks of code depending on whether a condition is true or false.
17
if Statement
The if statement is used to test a condition. If the condition is true, the block of
code under the if statement is executed.
x = 10
if x > 5:
print("x is greater than 5")
In this example, since x is greater than 5, the message will be printed.
elif Statement (short for else if)
The elif statement checks another condition if the previous if condition was false.
You can have multiple elif blocks in a chain.
x = 10
if x > 15:
print("x is greater than 15")
elif x == 10:
print("x is equal to 10")
Here, the first condition is false, but the elif condition is true, so the second
message is printed.
else Statement
The else statement runs if none of the if or elif conditions are true. It does not take
a condition.
x=3
if x > 10:
print("x is greater than 10")
elif x == 5:
print("x is equal to 5")
else:
print("x does not match any condition")

18
In this case, since both the if and elif conditions are false, the else block is
executed.
score = 75
if score >= 90:
print("Grade: A")
elif score >= 80:
print("Grade: B")
elif score >= 70:
print("Grade: C")
else:
print("Grade: F")
This code checks the value of score and prints the appropriate grade. It stops
checking as soon as one condition is True.
3.2 Nested conditions
Nested conditions refer to placing one if, elif, or else statement inside another if or
else block. This allows you to check multiple levels of conditions, meaning one
condition depends on the result of another.
Basic Syntax of Nested if
if condition1:
if condition2:
# Code block if both condition1 and condition2 are true
else:
# Code block if condition1 is true but condition2 is false
else:
# Code block if condition1 is false
Example 1: Checking Age and Citizenship
age = 20

19
citizen = True
if age >= 18:
if citizen:
print("You are eligible to vote.")
else:
print("You are old enough but not a citizen.")
else:
print("You are not old enough to vote.")
Explanation:
First, it checks if the person is 18 or older.
If true, it then checks if the person is a citizen.
If both are true, the person can vote; otherwise, it provides the appropriate
message.
Example 2: Nested with elif and else
score = 85
if score >= 60:
if score >= 90:
print("Excellent")
elif score >= 75:
print("Good")
else:
print("Passed")
else:
print("Failed")
Explanation:
The first if checks if the score is at least 60.

20
If true, it goes further to check specific ranges.
If not, the student fails.
3.3 while and for loops
Loops in Python: while and for loop
Loops in Python are used to execute a block of code repeatedly until a condition is
met or a sequence is fully processed. The two main types of loops in Python are
while loops and for loops.
while Loop
A while loop runs as long as a condition is true. It is typically used when the
number of iterations is not known in advance.
Syntax:
while condition:
# Code to execute repeatedly
Example:
count = 1
while count <= 5:
print("Count is:", count)
count += 1
Explanation:
The loop runs as long as count is less than or equal to 5. Each time, it prints the
current value and then increases it by 1.
for Loop
A for loop is used to iterate over a sequence (like a list, string, tuple, or range). It is
used when the number of iterations is known or defined.
Syntax:
for variable in sequence:
# Code to execute for each item in the sequence

21
Example:
for i in range(1, 6):
print("Number:", i)
Explanation:
This loop prints numbers from 1 to 5. range(1, 6) generates numbers starting from
1 up to (but not including) 6.
Loop Control Statements
break – Exits the loop early.
continue – Skips the current iteration and moves to the next.
pass – A placeholder that does nothing (used when a statement is syntactically
required).
Example with break and continue:
for i in range(1, 10):
if i == 5:
break # Stop the loop at 5
if i == 3:
continue # Skip 3
print(i)
3.4 break, continue, pass
Loop Control Statements in Python: break, continue, and pass
Python provides special statements that help control the behavior of loops. These
are break, continue, and pass. Each serves a specific purpose when managing how
and when loop iterations should execute or stop.
1. break Statement
The break statement is used to exit a loop prematurely, even if the loop condition is
still true or there are remaining items in the sequence.
Example:

22
for i in range(1, 10):
if i == 5:
break # Exit the loop when i is 5
print(i)
Output:
1
2
3
4
Explanation: The loop stops running when i equals 5.
2. continue Statement
The continue statement is used to skip the current iteration and move to the next
iteration of the loop.
Example:
for i in range(1, 6):
if i == 3:
continue # Skip when i is 3
print(i)
Output:
1
2
4
5
Explanation: When i is 3, the loop skips printing and moves to the next number.

23
3. pass Statement
The pass statement is a placeholder. It does nothing and is used when a statement
is syntactically required but you don’t want to perform any action.
Example:
for i in range(1, 6):
if i == 3:
pass # Do nothing, just a placeholder
print(i)
Output
1
2
3
4
5
Explanation: The loop runs normally. When i is 3, pass does nothing, and the loop
continues as usual.
3.5 Pattern Program
A pattern program in Python prints a specific visual structure using loops and
characters like *, numbers, or alphabets. These programs help build logical
thinking and loop control skills.

Loops: for, while


Nested loops: Loop inside another loop
print(): Used with end=' ' or \n for formatting
String multiplication: ' * ' * 3 → * * *

24
1. Right-Angled Triangle
n=5
for i in range(1, n+1):
print("*" * i)
Output:

*
**
***
****
*****

2. Inverted Right-Angled Triangle


n=5
for i in range(n, 0, -1):
print("*" * i)
Output:

*****
****
***
**
*

25
3. Pyramid Pattern

n=5
for i in range(n):
print(" " * (n-i-1) + "*" * (2*i+1))
Output:

*
***
*****
*******
*********

4. Number Triangle
python

n=5
for i in range(1, n+1):
for j in range(1, i+1):
print(j, end=" ")
print()

26
Output:

1
12
123
1234
12345

5. Repeated Row Number

n=4
for i in range(1, n+1):
print(str(i) * i)
Output:

1
22
333
4444

6. Alphabet Triangle

n=5
ch = 65 # ASCII of A
for i in range(n):

27
for j in range(i+1):
print(chr(ch), end=" ")
ch += 1
print()
Output:
mathematica

A
BB
CCC
DDDD
EEEEE

7. Hollow Square

n=5
for i in range(n):
for j in range(n):
if i == 0 or i == n-1 or j == 0 or j == n-1:
print("*", end=" ")
else:
print(" ", end=" ")
print()

28
Output:
markdown

*****
* *
* *
* *
*****

8. Diamond Pattern
n=5
for i in range(n):
print(" " * (n-i-1) + "*" * (2*i+1))
for i in range(n-2, -1, -1):
print(" " * (n-i-1) + "*" * (2*i+1))
Output:
*
***
*****
*******
*********
*******
*****
***
*

29
Tips for Pattern Problems
Rows vs Columns: Outer loop = rows, inner loop = columns.
Use range() smartly: Count up or down as needed.
ASCII values for alphabets: Use chr() and ord().
Spacing matters for triangle/pyramid shapes.
Try dry runs: Manually trace loop variables.
Explanation
Pattern programming in Python is a fundamental skill for beginners that focuses on
printing structured designs or shapes using loops. These patterns can include stars
(*), numbers, alphabets, or symbols, arranged in specific shapes such as triangles,
pyramids, squares, or diamonds.
Pattern programs help students understand the flow of loops, nested loops, and
output formatting. They are commonly used in interviews to test logic-building
capabilities.
Why Learn Pattern Programming?
Builds strong logical thinking and problem-solving skills.
Improves understanding of loop control and nested loops.
Helps in mastering print formatting in Python.
Frequently asked in coding interviews and competitive exams.
Tools Required
A basic Python environment like:
Python IDE (IDLE, PyCharm, VS Code)
Online compilers (Replit, Jupyter Notebook)
Basic knowledge of:
for and while loops
Conditional statements (if, else)
The print() function

30
Core Concepts
1. Loops
The for loop is widely used in pattern programming to iterate through rows and
columns.
Nested loops help in creating rows (outer loop) and columns (inner loop).
Example:
for i in range(5): # Outer loop for rows
for j in range(i+1): # Inner loop for columns
print("*", end=" ")
print() # Moves to next line
2. String Multiplication
Python allows multiplication of strings:
print("*" * 3) # Output: ***
This is useful for creating repeated patterns without inner loops.
3. ASCII Characters
For alphabet patterns:
print(chr(65)) # Output: A
Use ord() to convert characters to ASCII values and chr() to convert them back.

Types of Patterns
Star Patterns
Right-Angled Triangle
Inverted Triangle
Pyramid
Diamond

31
Chapter 4:
Functions and Modules
In Python, functions and modules are powerful tools that help organize
code, promote reusability, and make programs more manageable and readable.
This chapter explores how to define and use functions, pass data between them,
and how to structure programs using modules.
4.1 Defining and calling functions
Defining a Function
You define a function using the def keyword followed by the function name and
parentheses () that may include parameters. The function body is indented, and it
can contain any valid Python code.
Syntax:
def function_name(parameters):
# code block
return value # optional
Example: Function without Parameters
def greet():
print("Hello, welcome to Python!")
Calling a Function
Once a function is defined, you can call it by using its name followed by
parentheses.
Example:
greet() # Output: Hello, welcome to Python!
Function with Parameters
Functions can accept input values called parameters. You provide the actual values
(arguments) when calling the function.

32
Example:
def greet(name):
print("Hello,", name)
greet("Alice") # Output: Hello, Alice
greet("Bob") # Output: Hello, Bob
Function with Return Value
A function can return a result using the return statement. This allows the result to
be used elsewhere in the program.
Example:
def add(a, b):
return a + b
result = add(5, 3)
print("Sum is:", result) # Output: Sum is: 8
Function with Default Parameters
You can provide default values for parameters. If no value is provided during the
call, the default is used.
Example:
def greet(name="Guest"):
print("Hello,", name)
greet() # Output: Hello, Guest
greet("Sophia") # Output: Hello, Sophia

4.2.Arguments and Return Values


Arguments and Return Values in Python Functions

33
In Python, arguments are the values you pass into a function, and return values are
the outputs that a function can send back to the part of the program that called it.
These two features make functions flexible, reusable, and powerful.
Arguments
Arguments are actual values passed to a function's parameters when the function is
called. Python supports different types of arguments:
1. Positional Arguments
These are passed in the same order as the function's parameters.
def add(a, b):
print(a + b)
add(5, 3) # Output: 8
2. Keyword Arguments
You specify the parameter names when calling the function.
def greet(name, age):
print(f"Hello {name}, you are {age} years old.")

greet(age=25, name="Alice")
3. Default Arguments
You can assign default values to parameters. If no value is passed, the default is
used.
def greet(name="Guest"):
print("Hello", name)

greet() # Output: Hello Guest


greet("Sophia") # Output: Hello Sophia
4. Variable-Length Arguments

34
If you don’t know how many arguments you'll get, use *args (for positional) or
**kwargs (for keyword).
def add_all(*numbers):
total = sum(numbers)
print("Total:", total)

add_all(1, 2, 3, 4) # Output: Total: 10


Return Values
Functions can return data back to the caller using the return keyword. This allows
the result of a function to be stored in a variable or used in an expression.
Example:
def multiply(a, b):
return a * b
result = multiply(4, 5)
print("Result:", result) # Output: Result: 20
Returning Multiple Values
Python functions can return more than one value as a tuple.
def calculate(a, b):
return a + b, a - b
sum_result, diff_result = calculate(10, 3)
print("Sum:", sum_result) # Output: Sum: 13
print("Difference:", diff_result) # Output: Difference: 7

4.3 Lambda Function


A lambda function in Python is an anonymous, one-line function defined using the
lambda keyword. It is commonly used when a short, throwaway function is
needed, especially as an argument to functions like map(), filter(), and sorted().

35
Unlike regular functions defined using def, a lambda function can take multiple
arguments but only contains a single expression. The result of the expression is
automatically returned. Lambda functions are ideal for simplifying code where full
function definitions would be unnecessarily verbose.
Example:

# Lambda function to find the square of a number


square = lambda x: x * x
print(square(5)) # Output: 25

4.4 Scope: Local and Global


Scope: Local and Global (Explanation in One Paragraph)
In Python, scope refers to the region of the code where a variable is recognized.
There are two main types: local and global scope. A local variable is declared
inside a function and can only be accessed within that function. A global variable,
on the other hand, is defined outside of all functions and can be accessed from
anywhere in the code. If a variable is assigned within a function, Python treats it as
local by default, unless explicitly declared as global using the global keyword.
Understanding variable scope is important to prevent unintended changes to
variables and to manage memory efficiently.
Introduction to Python Libraries
Python is known for its simplicity and readability, but what truly makes it powerful
is its vast collection of libraries. These libraries provide pre-written code for
various functionalities, allowing developers to focus more on logic than low-level
details. Libraries act as building blocks that extend the core Python language,
making it suitable for data analysis, machine learning, web development,
automation, computer vision, and more. Whether you're a beginner learning the
ropes or an experienced developer tackling complex projects, Python’s standard
and third-party libraries help reduce development time and increase efficiency. The
wide availability and continuous growth of these libraries are major reasons Python
remains one of the most widely used programming languages in the world.

36
Data Science and Numerical Computing Libraries
In the field of data science and numerical computing, several Python libraries stand
out. NumPy is a foundational library for handling large, multi-dimensional arrays
and matrices, along with a vast collection of mathematical functions to operate on
these arrays. It provides fast and memory-efficient operations essential for
scientific computing. Pandas builds on NumPy and offers high-level data structures
like DataFrames, making it ideal for data cleaning, manipulation, and analysis. Its
intuitive syntax and rich feature set make tasks like handling missing data,
grouping, merging datasets, and time-series analysis straightforward. For
visualization, Matplotlib allows the creation of static, animated, and interactive
plots, while Seaborn builds on it to offer prettier, more informative statistical
graphics. These libraries form the backbone of any data science workflow in
Python.

Machine Learning and AI Libraries


For machine learning and artificial intelligence, Python offers a range of powerful
libraries. Scikit-learn is one of the most popular machine learning libraries,
offering tools for classification, regression, clustering, dimensionality reduction,
and model selection. It's built on top of NumPy, SciPy, and Matplotlib, and is easy
to integrate into both academic and production environments. TensorFlow,
developed by Google, and PyTorch, developed by Facebook, are deep learning
libraries that provide robust tools for building neural networks and large-scale AI
systems. TensorFlow includes high-level APIs like Keras for quick prototyping,
while PyTorch is favored for its dynamic computation graph and user-friendly
interface. These libraries are widely used in cutting-edge research and applications
like natural language processing, image recognition, and autonomous systems.

Web Development, Automation, and Scripting Libraries


Python is also a dominant force in web development and automation. Django is a
high-level web framework that encourages rapid development and clean, pragmatic
design. It includes built-in features like user authentication, an admin panel, and a
templating engine, making it suitable for building full-stack web applications.

37
Flask, in contrast, is a lightweight and flexible web framework that provides the
bare essentials, making it ideal for microservices and smaller web apps. In the area
of automation and scripting, Selenium allows Python scripts to control web
browsers automatically, which is widely used in automated testing and web
scraping. BeautifulSoup is another popular library used for parsing HTML and
XML documents, enabling developers to extract data from web pages with ease.
These libraries make Python a go-to language for backend development and
automation tasks.

Specialized Libraries
Beyond the major fields, Python offers specialized libraries for almost any task.
OpenCV is a leading library in computer vision, offering tools for image and video
analysis, facial recognition, and object detection. NLTK and spaCy are popular for
natural language processing, enabling developers to work with human language
data. SQLAlchemy and PyMySQL provide database access, while Requests
simplifies HTTP requests for web communication. Tkinter helps create GUI
applications, and PyGame supports simple game development. The Python
Package Index (PyPI) hosts over 400,000 packages, ensuring that developers can
find a library for virtually any problem. In conclusion, Python’s rich library
ecosystem is a key factor in its popularity and versatility, empowering developers
across industries to build robust, scalable, and intelligent applications with minimal
effort.
Example:
x = 10 # Global variable
def my_function():
x = 5 # Local variable
print("Local x:", x)

my_function()
print("Global x:", x)
Output:

38
Local x: 5
Global x: 10

Chapter :5 DATA STRUCTURE IN PYTHON

5.1: Data Structures in Python


In Python, data structures are essential tools that allow developers to store,
organize, and manipulate data efficiently. Python provides several built-in data
structures that are easy to use yet powerful enough to solve complex programming
problems. The four most commonly used data structures are lists, tuples,
dictionaries, and sets. Each of these structures serves a specific purpose and offers
unique advantages in different scenarios. Lists are used for ordered and changeable
collections, tuples for immutable sequences, dictionaries for key-value mappings,
and sets for unordered collections of unique items. Understanding these data
structures is fundamental to writing effective Python code, as they are frequently
used in data manipulation, algorithm implementation, and software development.
Data Structures
Data structures are fundamental concepts used to store and organize data
efficiently for access and modification. In Python, they help in solving problems
quickly and effectively.

2. Built-in Data Structures in Python


Python provides several built-in data structures, which are:
a) List
A list is a mutable, ordered collection of elements.
Elements can be of any data type and duplicates are allowed.
Syntax:

39
python

my_list = [1, 2, 3, 'Python', 3.14]


Common Operations:
append(): Adds an item
remove(): Removes an item
sort(), reverse()
Indexing and slicing: my_list[1:3]
Example:
python

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


fruits.append('grape')
print(fruits)
b) Tuple
A tuple is an immutable, ordered collection.
Faster than lists for read-only operations.
Syntax:
python

my_tuple = (1, 2, 3)
Common Uses:
Represent fixed data: e.g., coordinates (x, y)
Used as dictionary keys
Example:

40
python

dimensions = (1920, 1080)


print("Width:", dimensions[0])

c) Set
A set is an unordered, mutable collection of unique elements.
Useful for membership testing and removing duplicates.
Syntax:
python

my_set = {1, 2, 3, 2}
print(my_set) # Output: {1, 2, 3}
Set Operations:
union(), intersection(), difference(), add(), remove()
Example:
python

a = {1, 2, 3}
b = {3, 4, 5}
print(a.union(b)) # {1, 2, 3, 4, 5}

d) Dictionary
A dictionary stores key-value pairs.
Keys must be unique and immutable.

41
Syntax:
python

my_dict = {'name': 'Alice', 'age': 25}


Common Operations:
Access: my_dict['name']
Add/update: my_dict['city'] = 'Chennai'
Delete: del my_dict['age']
Example:
python

student = {'name': 'Rahul', 'marks': 85}


student['grade'] = 'A'
print(student)

3. Other Data Structures from Collections Module


Python's collections module provides additional data structures:
a) deque
Double-ended queue, faster append and pop from both ends.
Example:
python

from collections import deque


dq = deque([1, 2, 3])
dq.appendleft(0)

42
print(dq)
b) defaultdict
Like a dictionary, but provides a default value for missing keys.
c) Counter
Used for counting hashable objects.
Example:
python

from collections import Counter


cnt = Counter('banana')
print(cnt)

4. Choosing the Right Data Structure


Need Use

Ordered collection List / Tuple

Unique items Set

Key-value pair Dictionary

Fast insert/delete from both ends deque

Frequency count Counter

5.2: Lists in Python – Introduction and Creation


Lists in Python are ordered, mutable (changeable) sequences of elements. They
can store items of any data type, including other lists, and allow duplicates. Lists
are defined by placing elements inside square brackets [], separated by commas.

43
For example, my_list = [1, 2, 3, 'Python', 4.5] creates a list containing integers, a
string, and a float. Lists are highly flexible and are often used when the order of
elements matters or when the collection needs to be updated frequently. Python
also supports list comprehensions, which offer a concise way to create lists using
loops and conditions. Lists are ideal for storing sequences of items such as names,
numbers, or objects that may need to be changed or re-ordered.

5.3: List Operations and Slicing


Python provides a variety of list operations that make them versatile and easy to
work with. You can access individual elements using indexing (my_list[0]) or
retrieve a subset using slicing (my_list[1:4]), which returns a portion of the list.
Lists support basic operations like concatenation (+), repetition (*), and
membership testing (in). You can also use built-in functions like len() to get the
length, min() and max() for numerical lists, and sum() to calculate totals. Slicing
allows for powerful data manipulation, such as reversing a list (my_list[::-1]) or
skipping elements (my_list[::2]). These operations make lists suitable for a wide
range of applications, from data processing to managing collections of objects.

5.4: List Methods and Modifications


Lists in Python come with many methods for modifying content. Common
methods include append() to add a single item, extend() to add multiple items,
insert() to add an item at a specific index, and remove() or pop() to delete elements.
The sort() method arranges elements in ascending order, while reverse() reverses
their order. These methods allow lists to be used as dynamic arrays, where
elements can be added or removed as needed. Other useful methods include
index() to find the position of an element, and count() to count how many times an
item appears. The ability to modify and interact with data easily makes lists one of
the most commonly used data structures in Python programming.

5.5: Tuples in Python – Introduction and Properties


Tuples are similar to lists but are immutable, meaning their contents cannot be
changed after creation. They are defined using parentheses (), such as my_tuple =
(1, 2, 3, 'Python'). Because they are immutable, tuples are safer for storing data that

44
should not be altered accidentally, such as fixed configuration values or
coordinates. Python also allows for a single-element tuple using a trailing comma
(e.g., t = (5,)). Tuples support indexing and slicing like lists but lack methods for
modification such as append() or remove(). Their immutability also makes them
hashable, so they can be used as keys in dictionaries, which is not possible with
lists.
Tuple Example Program in Python

# Creating a tuple
fruits = ("apple", "banana", "cherry", "banana")

# Accessing elements by index


print("First fruit:", fruits[0])
print("Last fruit:", fruits[-1])

# Checking length of tuple


print("Total fruits:", len(fruits))

# Counting occurrences of an element


print("Banana appears:", fruits.count("banana"), "times")

# Finding index of an element


print("Index of cherry:", fruits.index("cherry"))

# Iterating over a tuple


print("All fruits:")
for fruit in fruits:

45
print(fruit)

Output:

First fruit: apple


Last fruit: banana
Total fruits: 4
Banana appears: 2 times
Index of cherry: 2
All fruits:
apple
banana
cherry
banana

5.6: Tuple Operations and Use Cases


Though tuples are immutable, many operations can still be performed. You can
access elements using indexing (t[0]), slice them (t[1:3]), and concatenate them (t1
+ t2). You can also use built-in functions like len(), max(), min(), and sum() on
numerical tuples. Tuples can be nested and are often used to represent structured
data, like a record in a database. They are also faster than lists in iteration and less
memory-intensive, making them useful in performance-critical applications.
Tuples are commonly used for returning multiple values from functions, especially
when the data should not be modified later.

46
Tuple Example Program in Python
python

# Tuple creation
student_info = ("John", 21, "Computer Science")

# Accessing tuple elements


print("Name:", student_info[0])
print("Age:", student_info[1])
print("Department:", student_info[2])

# Length of tuple
print("Total items:", len(student_info))

# Tuple unpacking
name, age, dept = student_info
print(f"Unpacked - Name: {name}, Age: {age}, Dept: {dept}")

Output:

Name: John
Age: 21
Department: Computer Science
Total items: 3
Unpacked - Name: John, Age: 21, Dept: Computer Science

47
Explanation:
A tuple is a collection of ordered, immutable elements.
Elements are accessed using indexing like lists.
Tuples support unpacking, where each value is assigned to a variable.
len() is used to find how many items are in the tuple.

5.7 Dictionaries in Python – Key-Value Pairs


Dictionaries in Python store key-value pairs, making them ideal for representing
real-world data like a contact list, inventory, or JSON-like data structures.
Dictionaries are defined using curly braces {}, such as my_dict = {'name': 'Alice',
'age': 25}. Each key must be unique and immutable (like a string, number, or
tuple), while values can be any type. Dictionaries are unordered before Python 3.7
and maintain insertion order from Python 3.7 onwards. They are incredibly fast for
lookups, making them useful for cases where quick access to data is required based
on identifiers or labels.
Dictionary Example Program in Python
python
# Creating a dictionary
student = {
"name": "Alice",
"age": 20,
"course": "Data Science"
}

# Accessing values
print("Name:", student["name"])

48
print("Age:", student["age"])
print("Course:", student["course"])

# Adding a new key-value pair


student["grade"] = "A"

# Updating an existing value


student["age"] = 21

# Iterating through the dictionary


print("\nStudent Information:")
for key, value in student.items():
print(key, ":", value)
Output:
yaml

Name: Alice
Age: 20
Course: Data Science

Student Information:
name : Alice
age : 21
course : Data Science
grade : A

49
5.8: Dictionary Methods and Applications
Dictionaries come with a rich set of methods for manipulating key-value pairs.
The get() method safely retrieves a value without raising an error if the key doesn't
exist. The update() method adds or modifies entries, pop() removes a key, and
keys(), values(), and items() allow iteration over the dictionary. You can also use
del to delete keys and in to check for the existence of a key. Dictionaries are
widely used in real-life applications such as storing user data, counting occurrences
(using elements as keys), and implementing lookup tables. They are one of the
most flexible and widely used data structures in Python.
Methods and Applications

What is a Dictionary?
A dictionary in Python is an unordered collection of key-value pairs. It is
mutable, meaning it can be changed after creation.
Syntax:
python

my_dict = {'key1': 'value1', 'key2': 'value2'}

Common Dictionary Methods


Here are the most commonly used dictionary methods in Python:

1. dict.keys()
Returns a view object that displays a list of all the keys.
python

50
student = {'name': 'Ali', 'age': 20}
print(student.keys()) # dict_keys(['name', 'age'])

2. dict.values()
Returns a view object of all values.
python

print(student.values()) # dict_values(['Ali', 20])

3. dict.items()
Returns a view object of key-value tuple pairs.
python

print(student.items()) # dict_items([('name', 'Ali'), ('age', 20)])

4. dict.get(key, default)
Returns the value of the specified key. If key not found, returns default value.
python

print(student.get('name')) # Ali
print(student.get('grade', 'N/A')) # N/A

5. dict.update(other_dict)
Updates the dictionary with key-value pairs from another dictionary.
python

51
student.update({'grade': 'A'})
print(student) # {'name': 'Ali', 'age': 20, 'grade': 'A'}

6. dict.pop(key)
Removes the key and returns its value.
python

age = student.pop('age')
print(age) # 20
print(student) # {'name': 'Ali', 'grade': 'A'}

7. dict.popitem()
Removes and returns the last inserted key-value pair.
python

print(student.popitem()) # ('grade', 'A')

8. dict.clear()
Removes all items from the dictionary.
python

student.clear()
print(student) # {}

52
9. dict.copy()
Returns a shallow copy of the dictionary.
python

data = {'a': 1, 'b': 2}


new_data = data.copy()
print(new_data) # {'a': 1, 'b': 2}

10. fromkeys(seq, value)


Creates a new dictionary from a sequence of keys and a single value.
python

keys = ['a', 'b', 'c']


d = dict.fromkeys(keys, 0)
print(d) # {'a': 0, 'b': 0, 'c': 0}

Applications of Dictionary in Real-world Projects


1. Storing Configuration Settings
python

config = {
'theme': 'dark',
'font': 'Arial',
'fontsize': 12
}

53
2. Counting Frequency of Elements
python

text = "apple banana apple orange"


words = text.split()
freq = {}
for word in words:
freq[word] = freq.get(word, 0) + 1
print(freq) # {'apple': 2, 'banana': 1, 'orange': 1}

3. Storing and Accessing Student Records


python

student = {
'name': 'Divya',
'roll_no': 101,
'marks': {'math': 90, 'science': 88}
}
print(student['marks']['science']) # 88

4. Database-like Storage
python

database = {

54
1001: {'name': 'Amit', 'dept': 'CS'},
1002: {'name': 'Sara', 'dept': 'IT'}
}
print(database[1002]['name']) # Sara

5. JSON Data Handling


Dictionaries are often used to load/store JSON data.
python

import json
data = '{"name": "John", "age": 30}'
parsed = json.loads(data)
print(parsed['name']) # John

5.9: Sets in Python – Uniqueness and Definition


Sets are unordered collections of unique elements. They are defined using curly
braces like dictionaries, but without key-value pairs, e.g., my_set = {1, 2, 3}. Sets
automatically remove duplicates, making them useful for membership tests,
removing duplicates from lists, or performing mathematical set operations. Python
also provides a set() constructor to convert other data types (like lists or strings)
into sets. Since sets are unordered, elements cannot be accessed via indexing, but
they support iteration using loops. Sets are an excellent choice when working with
data where the uniqueness of items is important.

5.10: Set Operations and Methods


Python sets support several mathematical operations such as union (|),
intersection (&), difference (-), and symmetric difference (^). These operations

55
are efficient and useful for comparing data collections. Sets also include methods
like add() to insert an element, remove() and discard() to delete items, and clear()
to remove all elements. The in keyword can be used to test membership. Sets are
commonly used in applications such as eliminating duplicate entries from a list,
managing unique user IDs, or filtering data. Their efficiency and built-in methods
make them a handy tool in every Python programmer’s toolkit.

This internship has provided a comprehensive foundation in core Python


programming concepts, with a strong focus on essential data structures such as
lists, tuples, dictionaries, and sets. Through practical examples and hands-on
exercises, we explored how these structures store, manage, and manipulate data
efficiently. We also examined key concepts like lambda functions, variable
scope (local and global), and the utility of Python standard libraries such as
math, random, and datetime, as well as explored top third-party libraries used in
data science, AI, and web development. This learning experience has strengthened
our problem-solving abilities, encouraged structured thinking, and enhanced our
coding proficiency. Overall, the internship has laid a solid groundwork for further
learning in Python and has prepared us to tackle real-world applications and more
advanced programming tasks confidently.
Sets: Operations and Methods

What is a Set?
A set is an unordered, mutable collection of unique elements in Python.
Key Characteristics:
Duplicate elements are not allowed.
Elements must be immutable (e.g., numbers, strings, tuples).
Sets are defined using curly braces {} or the set() constructor.
Example:
python

56
my_set = {1, 2, 3, 3, 2}
print(my_set) # Output: {1, 2, 3}

Common Set Methods


Python provides many built-in methods for working with sets:

1. add(element)
Adds an element to the set.
python

s = {1, 2}
s.add(3)
print(s) # {1, 2, 3}

2. remove(element)
Removes the specified element. Raises an error if the element is not found.
python

s.remove(2)
print(s) # {1, 3}

3. discard(element)
Removes the specified element. Does not raise an error if the element is not found.
python

57
s.discard(5) # No error

4. pop()
Removes and returns a random element.
python

item = s.pop()
print(item, s)

5. clear()
Removes all elements from the set.
python

s.clear()
print(s) # set()

6. copy()
Returns a shallow copy of the set.
python

s = {1, 2, 3}
new_s = s.copy()
print(new_s)

58
Set Operations
Sets support many mathematical operations:

1. Union (| or .union())
Returns a set with all elements from both sets (no duplicates).
python
a = {1, 2, 3}
b = {3, 4, 5}
print(a | b) # {1, 2, 3, 4, 5}
print(a.union(b))

2. Intersection (& or .intersection())


Returns only the elements common to both sets.
python

print(a & b) # {3}


print(a.intersection(b))

3. Difference (- or .difference())
Returns the elements in the first set but not in the second.
python

print(a - b) # {1, 2}
print(a.difference(b))

59
4. Symmetric Difference (^ or .symmetric_difference())
Returns elements in either set but not in both.
python

print(a ^ b) # {1, 2, 4, 5}
print(a.symmetric_difference(b))

Set Comparisons
1. Subset (<=) and Superset (>=)
python

a = {1, 2}
b = {1, 2, 3}
print(a <= b) # True (a is a subset of b)
print(b >= a) # True (b is a superset of a)

2. Disjoint Sets (isdisjoint())


Returns True if two sets have no elements in common.
python

x = {1, 2}
y = {3, 4}
print(x.isdisjoint(y)) # True

Applications of Sets

60
1. Removing Duplicates from a List
python

nums = [1, 2, 2, 3, 1]
unique = list(set(nums))
print(unique) # [1, 2, 3]

2. Set Membership Test


python

vowels = {'a', 'e', 'i', 'o', 'u'}


print('e' in vowels) # True

3. Mathematical Set Operations


Used in problems involving:
Common elements
Unique elements
Finding elements not in another group

4. Efficient Lookups
Set lookups are faster than lists for large data.
python

data = set(range(1_000_000))
print(500_000 in data) # Fast

61
Lambda Function?
A lambda function is a small anonymous function in Python.
It is used when you need a simple function for a short period of time.
Key Points:
Defined using the lambda keyword.
Can take any number of arguments.
Has only one expression (no statements like loops or multiple lines).

🧾 Syntax:
python

lambda arguments: expression

Example:
python

add = lambda a, b: a + b
print(add(3, 5)) # Output: 8
It is the same as:
python

def add(a, b):


return a + b

Use Cases of Lambda Functions

62
1. Using with map()
Applies a function to all elements in a list.
python

numbers = [1, 2, 3, 4]
squared = list(map(lambda x: x*x, numbers))
print(squared) # [1, 4, 9, 16]

2. Using with filter()


Filters elements based on a condition.
python

numbers = [1, 2, 3, 4, 5, 6]
even = list(filter(lambda x: x % 2 == 0, numbers))
print(even) # [2, 4, 6]

3. Using with sorted()


Sort list of tuples by the second item.
python

pairs = [(1, 2), (3, 1), (5, 0)]


sorted_pairs = sorted(pairs, key=lambda x: x[1])
print(sorted_pairs) # [(5, 0), (3, 1), (1, 2)]

4. Quick Math Operations

63
python

square = lambda x: x * x
print(square(6)) # 36
square = lambda x: x * x
print(square(6)) # 36

When to Use Lambda?


Use lambda when:
The function is small and simple.
Used only once or temporarily.
Passed as an argument to higher-order functions (like map, filter, sorted).

Limitations of Lambda Functions


Limitation Explanation

One Expression Only You can't use multiple lines or statements

No Function Name Debugging is harder

No Annotations Can't add type hints easily

Practice Examples
Example 1:
python

double = lambda x: x * 2
print(double(4)) # Output: 8

64
Example 2:
python

max_num = lambda a, b: a if a > b else b


print(max_num(10, 20)) # Output

LEARNING OUT COMES :


Understanding Core Python Concepts
Gained a strong understanding of Python syntax, data types, and fundamental
programming concepts such as variables, operators, and control structures.
Mastery of Data Structures
Learned how to effectively use Python’s built-in data structures—lists, tuples,
dictionaries, and sets—to store, access, and manipulate data.
Use of Lambda Functions
Understood the use of lambda (anonymous) functions for writing concise,
functional-style code and how they can be applied in filtering, mapping, and
sorting tasks.
Variable Scope Awareness
Gained clarity on the concepts of local and global scope, and how variable
accessibility affects function design and program behavior.
Hands-on Practice with Standard Libraries
Applied Python’s standard libraries like math, random, and datetime to perform
real-world computations and automate routine tasks.
Familiarity with Top Python Libraries
Developed awareness of powerful third-party libraries like NumPy, Pandas,
Matplotlib, TensorFlow, and Flask, and their roles in data science, web
development, and AI.

65
Problem-Solving and Logical Thinking
Improved problem-solving skills through practice exercises and coding tasks that
required logical reasoning and creative thinking.
Real-World Application Readiness
Built confidence to use Python in real-world scenarios including data analysis,
automation, web development, and basic machine learning.
Code Debugging and Optimization
Learned how to write clean, readable code and debug errors efficiently using
Python’s tools and best practices.

66

You might also like