Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
7 views46 pages

Python Note

python note1

Uploaded by

gtecstudent795
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)
7 views46 pages

Python Note

python note1

Uploaded by

gtecstudent795
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/ 46

INTRODUCTION TO PROGRAMMING & PYTHON INSTALLATION

• Overview of Programming Languages


• Machine language
• Assembly language
• High level language
• Compilers & Interpreters
• History of python
• Evolution of Python
• Features of python
• Applications of Python
• Installation & Environment Setup

BASICS OF PYTHON PROGRAMMING


• Introduction
• Python characterset
• Tokens
• Values & types
• Variables
• Variable name & keyword
• Data Types: Int, float, complex Number, Boolean & string
• Data type conversion
• Multiple assignmentto variables
• Input &Print Function
• Formatting Number & string

OPERATORS & EXPRESSIONS


• Operators & operands, types
• ArithmeticOperators: Unary, Binary
• ComparisonOperators
• LogicalOperators: not, and, or
• MembershipOperators

G-TEC EDUCATION
ISO 9001:2015 CERTIFIED
TRAINER GUIDE

DECISION & LOOP CONTROL STATEMENTS


• Boolean Expression & relational operators
• Decision making statements
o The if statements
o The If-else statement
o Nested if statement
o Multi way if else statements
• Conditional expressions
• While Loop
• Break statement
• Continue statement
• Nested loops
• For loops
• Range Functions

LISTS
• List values
• Create, Accessing elements
• List length, membership
• List & for loops
• List operations
• List slices [Start:end]
• List deletion
• Object & values
• Passing list to a function
• Cloning lists
• Nested list

TUPLES, SET & DICTIONARIES


Tuples
• Introduction to tuples
• Creating tuple
• Tuple assignment
• Operations on tuples
Sets
• Introduction
• Set with List - operations
• Set operations and functions
Dictionaries
• Basics of dictionaries
• Creating a dictionary
• Add, Replace, retrieve, format, delete itemsin a dictionary

G-TEC EDUCATION
ISO 9001:2015 CERTIFIED
TRAINER GUIDE

STRING MANIPULATION
• Built-in string functions
• Pattern Searching
• Replacing and removing substrings
• Working with Slice Operator
• Applying Slice Operatorsin Lists and Tuples

FUNCTIONS
• Introduction to Functions
• Parameters& argumentsin a function
❖ Arguments
❖ Positional arguments
❖ Arguments with default values
• Function with return values
• Lambda Keyword
• Custom Libraries
• Custom Packages

EXCEPTIONS
• Introduction
• Try .. Except Blocks
• Try .. Except .. Else Blocks
• Try .. Except .. Finally Blocks
• Multiple Exception Handlers
• Nested Exception Handlers
• Raising Exceptions

OBJECT ORIENTED PROGRAMMING: CLASS, OBJECT & INHERITANCE


• Classes and objects
• Constructors
• Operator overloading
• Inheritance
• Multilevel, multiple inheritance
• Method overriding

FILES MANIPULATION
• Introduction
• Writing & Reading Text Files
• Writing & Reading Data Files
• Writing and Reading objectsinto binary files using pickle
• Directory Manipulation

Introduction to Programming & Python


Installation
Overview of Programming Languages
A programming language is a way for humans to communicate with computers. It is used to write
instructions (code) that a computer can understand and execute. There are different types of programming
languages, categorized based on their complexity and usage.

1. Machine Language

• The lowest-level language, understood directly by computers.


• Written in binary (0s and 1s).
• Hard to write and understand for humans.
• Example: 1010101011101010

2. Assembly Language

• A step above machine language, using short codes (mnemonics) instead of binary.
• Needs an assembler to convert into machine language.
• Easier to read than machine language but still complex.
• Example: MOV A, B (Moves data from B to A).

3. High-Level Language

• Designed to be human-friendly.
• Uses simple syntax (English-like words).
• Needs a compiler or interpreter to convert it into machine code.
• Examples: Python, Java, C++, JavaScript.

Compilers & Interpreters


• Compiler: Converts the entire code into machine language at once before execution (e.g., C, C++).
• Interpreter: Converts code line-by-line and executes it immediately (e.g., Python, JavaScript).

History & Evolution of Python


• Created by: Guido van Rossum in 1991.
• Why?: To make programming easy and readable.
• Inspired by: ABC language.
• Named after: "Monty Python's Flying Circus" (a British comedy show).
• Over time, Python has improved, with versions like Python 2 (legacy) and Python 3 (modern &
widely used).

Features of Python
• Simple & Readable: Uses English-like syntax.
• Interpreted: Executes line by line.
• Portable: Runs on different operating systems (Windows, Mac, Linux).
• Object-Oriented: Supports object-based programming.
• Huge Libraries: Many pre-built modules for different tasks (e.g., math, web development, AI).

Applications of Python
• Web Development: Django, Flask frameworks.
• Data Science & AI: Used in machine learning and data analysis (Pandas, NumPy, TensorFlow).
• Automation & Scripting: Automates repetitive tasks.
• Game Development: Used in creating games (Pygame).
• Cybersecurity: Ethical hacking and penetration testing.

BASICS OF PYTHON PROGRAMMING


1. Introduction to Python
Python is a simple, easy-to-learn, and powerful programming language used for web development,
automation, AI, and more. It has clear syntax that makes it great for beginners.

Example:

python
CopyEdit
print("Welcome to Python Programming!")

Output:

css
CopyEdit
Welcome to Python Programming!

Python is case-sensitive, meaning Print("Hello") will give an error, while print("Hello") works.

2. Python Character Set


The character set is the set of characters Python recognizes and uses.
• Letters: A-Z, a-z
• Digits: 0-9
• Special symbols: + - * / % @ # $ &
• White spaces: Space, tab, new line
• Other characters: Unicode characters

Example:

python
CopyEdit
# This is a comment using special characters like # and "
print("Python supports special characters like @, #, &, %")

Output:

nginx
CopyEdit
Python supports special characters like @, #, &, %

3. Tokens in Python
Tokens are the smallest building blocks of a Python program.

Types of Tokens:

1. Keywords (reserved words): if, else, while, for, break, return, True, False
2. Identifiers (variable & function names): name, age, sum1
3. Literals (constant values): 123, "hello", 3.14
4. Operators (+ - * / == != > <)
5. Punctuators (brackets {}, [], (), ,, :)

Example:

python
CopyEdit
if True:
print("Tokens are important!")

Output:

sql
CopyEdit
Tokens are important!

4. Values & Types


Values are actual data, and types define what kind of data it is.

Basic Data Types in Python:

• int → Integer (e.g., 5, -10, 1000)


• float → Decimal numbers (e.g., 3.14, -2.5, 0.99)
• complex → Numbers with imaginary parts (e.g., 2 + 3j)
• bool → Boolean (True or False)
• str → String (e.g., "Hello", 'Python')

Example:

python
CopyEdit
print(type(10)) # int
print(type(3.14)) # float
print(type(2 + 3j)) # complex
print(type(True)) # bool
print(type("Hello")) # str

Output:

kotlin
CopyEdit
<class 'int'>
<class 'float'>
<class 'complex'>
<class 'bool'>
<class 'str'>

5. Variables in Python
A variable is a container for storing values.

Rules for Variable Names:

✅ Can contain letters, digits, and underscores (_).


✅ Cannot start with a digit.
✅ Cannot use Python keywords (if, else, for).
✅ Case-sensitive (Age and age are different).

Example:

python
CopyEdit
name = "Alice"
age = 25
PI = 3.14

print(name, age, PI)

Output:

nginx
CopyEdit
Alice 25 3.14

6. Variable Names & Keywords


Example (Correct & Incorrect Variable Names):

python
CopyEdit
# Valid variable names
my_name = "Bob"
_age = 30
score1 = 95

# Invalid variable names


2name = "Error" # Starts with a digit (❌)
for = 10 # Using a keyword (❌)

Error will occur for 2name and for.

7. Data Types in Python


Data Type Example
int 10, -5, 0
float 3.14, -2.5
complex 2 + 3j, -5j
bool True, False
string "Hello", 'Python'

Example:

python
CopyEdit
num1 = 10
num2 = 3.5
num3 = 2 + 4j
flag = True
text = "Python"

print(type(num1), type(num2), type(num3), type(flag), type(text))

Output:

kotlin
CopyEdit
<class 'int'> <class 'float'> <class 'complex'> <class 'bool'> <class 'str'>

8. Data Type Conversion (Type Casting)


You can convert one data type into another.

Example:

python
CopyEdit
a = 10
b = 3.5
c = "15"

print(int(b)) # float to int (Output: 3)


print(float(a)) # int to float (Output: 10.0)
print(int(c)) # string to int (Output: 15)
9. Multiple Assignments to Variables
You can assign values to multiple variables in one line.

Example:

python
CopyEdit
x, y, z = 10, 20, 30
print(x, y, z)

Output:

CopyEdit
10 20 30

Example (Same Value for Multiple Variables):

python
CopyEdit
a = b = c = 100
print(a, b, c)

Output:

CopyEdit
100 100 100

10. Input & Print Function


input() - Taking User Input

Example:

python
CopyEdit
name = input("Enter your name: ")
print("Hello,", name)

User enters John → Output:

CopyEdit
Hello, John

print() - Display Output

Example:

python
CopyEdit
age = 25
print("Your age is:", age)
Output:

csharp
CopyEdit
Your age is: 25

11. Formatting Numbers & Strings


Python allows formatting of strings and numbers for better display.

Example (Using format()):

python
CopyEdit
name = "Alice"
age = 25
print("My name is {} and I am {} years old.".format(name, age))

Output:

pgsql
CopyEdit
My name is Alice and I am 25 years old.

Example (Using f-strings - Recommended):

python
CopyEdit
name = "Bob"
salary = 5000.50
print(f"{name} earns ${salary:.2f} per month.")

Output:

nginx
CopyEdit
Bob earns $5000.50 per month.

Exercise: Try It Yourself!

1. Write a program to input your name and age and print them.
2. Convert an integer to float and print it.
3. Swap two variables without using a third variable.
4. Print "The sum of 10 and 5 is: 15" using format().

OPERATORS & EXPRESSIONS IN PYTHON


1. Operators & Operands
• Operators: Symbols used to perform operations on values/variables.
• Operands: The values on which operators work.

Example:
python
CopyEdit
a = 10
b = 5
sum_value = a + b # '+' is the operator, 'a' & 'b' are operands
print(sum_value)

Output:

CopyEdit
15

2. Types of Operators in Python


1. Arithmetic Operators (Addition, Subtraction, etc.)
2. Comparison Operators (Greater than, Less than, etc.)
3. Logical Operators (and, or, not)
4. Membership Operators (in, not in)

3. Arithmetic Operators
Used to perform mathematical operations.

Operator Name Example


+ Addition 5 + 3 → 8
- Subtraction 10 - 4 → 6
* Multiplication 6 * 2 → 12
/ Division 9 / 2 → 4.5
// Floor Division 9 // 2 → 4
% Modulus 10 % 3 → 1
** Exponentiation 2 ** 3 → 8

Unary vs Binary Operators

• Unary Operator: Works with a single operand.


• Binary Operator: Works with two operands.

Example (Unary & Binary Operators):

python
CopyEdit
x = 5
print(-x) # Unary operator (-) changes sign → Output: -5

a, b = 10, 3
print(a + b) # Binary operator → Output: 13

4. Comparison Operators
Used to compare two values and return True or False.
Operator Meaning
== Equal to
!= Not equal to
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to

Example:

python
CopyEdit
a = 10
b = 20

print(a == b) # False
print(a != b) # True
print(a > b) # False
print(a < b) # True

5. Logical Operators
Used to combine multiple conditions.

Operator Meaning Example


and True if both conditions are True (5 > 2) and (10 > 3) → True
or True if at least one condition is True (5 > 2) or (10 < 3) → True
not Reverses the boolean value not(5 > 2) → False

Example:

python
CopyEdit
x, y = 10, 20

print((x > 5) and (y > 15)) # True


print((x > 15) or (y > 15)) # True
print(not (x > 5)) # False

6. Membership Operators
Used to check if a value is present in a sequence (list, string, tuple, etc.).

Operator Meaning
in Returns True if value is found
not in Returns True if value is NOT found

Example:

python
CopyEdit
text = "Python is fun"
print("Python" in text) # True
print("Java" not in text) # True

Example (With List):

python
CopyEdit
numbers = [1, 2, 3, 4, 5]

print(3 in numbers) # True


print(10 not in numbers) # True

Exercise Questions

1. Write a Python program to perform all arithmetic operations on two numbers.


2. Check if a number is greater than 50 and even using logical operators.
3. Check if "apple" is present in the list ["banana", "cherry", "apple"].
4. Swap two numbers without using a third variable.

DECISION & LOOP CONTROL STATEMENTS


IN PYTHON
Python provides decision-making and loop control statements to control the flow of execution in a
program. These statements allow a program to execute specific blocks of code based on conditions and
repeat tasks efficiently.

1. Boolean Expressions & Relational Operators


Boolean Expressions

A Boolean expression is an expression that evaluates to True or False. It is used in decision-making and
loops to control program flow.

Example:

python
CopyEdit
a = 10
b = 20
print(a < b) # True
print(a == b) # False

Output:

graphql
CopyEdit
True
False

Relational (Comparison) Operators


These operators compare two values and return True or False.

Operator Meaning Example (a=10, b=20)


== Equal to a == b → False
!= Not equal to a != b → True
> Greater than a > b → False
< Less than a < b → True
>= Greater than or equal a >= b → False
<= Less than or equal a <= b → True

2. Decision Making Statements


Decision-making statements allow a program to execute a block of code based on a condition.

(a) if Statement

The if statement executes a block only if the condition is True.

Example:

python
CopyEdit
age = 18
if age >= 18:
print("You are eligible to vote.")

Output:

css
CopyEdit
You are eligible to vote.

Why use if?

• To execute specific actions only when a condition is met.


• Example: Checking password validity before granting access.

(b) if-else Statement

The if-else statement executes different code based on a condition.

Example:

python
CopyEdit
num = 10
if num % 2 == 0:
print("Even number")
else:
print("Odd number")
Output:

typescript
CopyEdit
Even number

Why use if-else?

• To handle multiple possibilities, like login success or failure.

(c) Nested if Statement

An if statement inside another if.

Example:

python
CopyEdit
num = 10
if num > 0:
print("Positive number")
if num % 2 == 0:
print("Even number")

Output:

typescript
CopyEdit
Positive number
Even number

Why use nested if?

• When multiple conditions need to be checked hierarchically.

(d) Multi-way if-elif-else Statement

Checks multiple conditions one after another.

Example:

python
CopyEdit
marks = 85

if marks >= 90:


print("Grade: A")
elif marks >= 75:
print("Grade: B")
elif marks >= 60:
print("Grade: C")
else:
print("Grade: F")
Output:

makefile
CopyEdit
Grade: B

Why use if-elif-else?

• When you need to choose one option from many (e.g., assigning grades).

3. Conditional Expressions (Ternary Operator)


A one-line if-else statement that makes code concise.

Example:

python
CopyEdit
age = 20
status = "Adult" if age >= 18 else "Minor"
print(status)

Output:

nginx
CopyEdit
Adult

Why use a conditional expression?

• To simplify if-else statements for small conditions.

4. Loops in Python
Loops allow repeating a block of code multiple times, saving time and effort.

(a) while Loop

Repeats a block while the condition is true.

Example:

python
CopyEdit
count = 1
while count <= 5:
print("Count:", count)
count += 1

Output:

makefile
CopyEdit
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5

Why use a while loop?

• When we don't know the number of iterations in advance (e.g., waiting for user input).

5. break Statement
Used to exit a loop immediately.

Example:

python
CopyEdit
num = 1
while num <= 10:
if num == 5:
break
print(num)
num += 1

Output:

CopyEdit
1
2
3
4

Why use break?

• To stop loops when a certain condition is met (e.g., stopping search after finding an item).

6. continue Statement
Skips the current iteration and continues the loop.

Example:

python
CopyEdit
num = 0
while num < 5:
num += 1
if num == 3:
continue
print(num)

Output:
CopyEdit
1
2
4
5

Why use continue?

• To skip specific cases in a loop (e.g., ignoring invalid input values).

7. Nested Loops
A loop inside another loop.

Example:

python
CopyEdit
for i in range(1, 4): # Outer loop
for j in range(1, 4): # Inner loop
print(f"({i}, {j})", end=" ")
print()

Output:

scss
CopyEdit
(1, 1) (1, 2) (1, 3)
(2, 1) (2, 2) (2, 3)
(3, 1) (3, 2) (3, 3)

Why use nested loops?

• Useful for working with grids, tables, and patterns.

8. for Loop
A for loop repeats a block a fixed number of times.

Example:

python
CopyEdit
for i in range(1, 6):
print("Iteration:", i)

Output:

makefile
CopyEdit
Iteration: 1
Iteration: 2
Iteration: 3
Iteration: 4
Iteration: 5

Why use for loops?

• When we know the number of iterations in advance.

9. range() Function
The range() function is used in for loops to generate sequences.

Syntax:
python
CopyEdit
range(start, stop, step)

• start: Starting value (default 0).


• stop: Ending value (not included).
• step: Increment (default 1).

Example:

python
CopyEdit
for i in range(1, 10, 2):
print(i, end=" ")

Output:

CopyEdit
1 3 5 7 9

Why use range()?

• It helps control the loop iterations efficiently.

Summary
✅ Decision-making (if, if-else, if-elif-else) controls which part of the code runs.
✅ Loops (while, for) help repeat tasks efficiently.
✅ Control statements (break, continue) modify loop behavior.
✅ range() helps control loop sequences.

Practice Questions

1. Write a program to check if a number is positive, negative, or zero.


2. Print numbers from 1 to 10 using a while loop.
3. Use a for loop to print multiplication table of 5.
4. Print all even numbers from 1 to 50 using range().

Python Lists - Complete Guide with Explanation,


Examples & Use Cases
Python lists are one of the most versatile and widely used data structures. They allow us to store multiple
values in a single variable and provide a flexible way to manage data.

1. What is a List?
A list is an ordered, mutable collection of elements that can hold items of different data types, such as
numbers, strings, or even other lists.

Why use Lists?

✅ Lists allow storing multiple items in a single variable.


✅ They are ordered, meaning the order of elements is preserved.
✅ Lists are mutable, meaning elements can be modified after creation.
✅ Lists support various operations like slicing, iteration, and modification.

Example of a List
python
CopyEdit
fruits = ["apple", "banana", "cherry", "date"]
print(fruits)

Output:

css
CopyEdit
['apple', 'banana', 'cherry', 'date']

2. Creating a List
Lists are created using square brackets [ ].

Examples of List Creation


python
CopyEdit
# List of integers
numbers = [10, 20, 30, 40]

# List of strings
names = ["Alice", "Bob", "Charlie"]

# Mixed data type list


mixed_list = [10, "Python", 3.14, True]

# Empty list
empty_list = []

3. Accessing Elements in a List


Each element in a list has an index number, starting from 0.

Indexing in Lists

List Elements A B C D E
Index Numbers 0 1 2 3 4
Negative Index -5 -4 -3 -2 -1

Examples
python
CopyEdit
letters = ["A", "B", "C", "D", "E"]

# Accessing elements using index


print(letters[0]) # A
print(letters[3]) # D

# Accessing elements using negative index


print(letters[-1]) # E
print(letters[-3]) # C

4. List Length & Membership


• The len() function returns the number of elements in a list.
• The in operator checks if an element exists in the list.

Examples
python
CopyEdit
colors = ["red", "blue", "green"]

# List length
print(len(colors)) # Output: 3

# Membership check
print("blue" in colors) # Output: True
print("yellow" in colors) # Output: False

5. Lists & Loops


Using for Loop with Lists
python
CopyEdit
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
Output:

nginx
CopyEdit
apple
banana
cherry

6. List Operations
Python supports various operations on lists.

Operation Syntax Example Output


Concatenation + [1, 2] + [3, 4] [1, 2, 3, 4]
Repetition * ["Hello"] * 3 ['Hello', 'Hello', 'Hello']
Membership in 3 in [1, 2, 3] True

Examples
python
CopyEdit
list1 = [1, 2, 3]
list2 = [4, 5]

# Concatenation
print(list1 + list2) # [1, 2, 3, 4, 5]

# Repetition
print(["Hello"] * 3) # ['Hello', 'Hello', 'Hello']

# Membership
print(3 in list1) # True

7. List Slicing [start:end]


List slicing extracts a portion of a list.

Syntax
python
CopyEdit
list[start:end] # Includes 'start' but excludes 'end'

Examples
python
CopyEdit
numbers = [10, 20, 30, 40, 50]

print(numbers[1:4]) # [20, 30, 40] (Indexes 1 to 3)


print(numbers[:3]) # [10, 20, 30] (First 3 elements)
print(numbers[2:]) # [30, 40, 50] (From index 2 to end)
print(numbers[-3:]) # [30, 40, 50] (Last 3 elements)
8. Deleting Elements from a List
Methods to Delete List Elements

Method Syntax Description


del del list[index] Removes a specific element
remove() list.remove(value) Removes the first occurrence of a value
pop() list.pop(index) Removes and returns an element
clear() list.clear() Removes all elements

Examples
python
CopyEdit
numbers = [10, 20, 30, 40, 50]

del numbers[2] # Deletes 30


print(numbers) # [10, 20, 40, 50]

numbers.remove(20) # Removes value 20


print(numbers) # [10, 40, 50]

print(numbers.pop()) # Removes & returns last element (50)

9. Objects & Values in Lists


Lists store references to objects, not actual values.
python
CopyEdit
list1 = [1, 2, 3]
list2 = list1 # Both point to the same object

list2.append(4)
print(list1) # [1, 2, 3, 4] (list1 is also affected!)

10. Passing Lists to Functions


Lists can be passed as function arguments.

Example
python
CopyEdit
def modify_list(lst):
lst.append("New Item")

my_list = ["A", "B"]


modify_list(my_list)
print(my_list) # ['A', 'B', 'New Item']

Why pass lists to functions?

• To manipulate data without returning new lists.


11. Cloning (Copying) Lists
Since lists store references, using = creates a reference, not a copy.

Proper Ways to Clone a List


python
CopyEdit
original = [1, 2, 3]

# Using slicing
copy1 = original[:]

# Using copy() method


copy2 = original.copy()

# Using list() function


copy3 = list(original)

copy1.append(4)
print(original) # [1, 2, 3] (original remains unchanged)

12. Nested Lists (Lists inside Lists)


Lists can contain other lists.

Example
python
CopyEdit
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

# Accessing elements
print(matrix[0]) # [1, 2, 3]
print(matrix[1][2]) # 6

Why use Nested Lists?

• Useful for storing tabular data, like matrices and grids.

Summary
✅ Lists are ordered, mutable collections that allow storage of multiple values.
✅ You can access, modify, and delete elements efficiently.
✅ Lists support loops, slicing, copying, and nesting.
✅ They are commonly used in data processing, sorting, and dynamic storage.

Practice Questions
1. Create a list of your favorite movies and print each one.
2. Write a program to find the largest number in a list.
3. Use list slicing to print the first 3 elements of a list.
4. Implement a nested list to store students' names and their scores.

Keep Practicing! Python Lists are Powerful!

1️⃣ TUPLES in Python


What is a Tuple?

A tuple is an ordered, immutable collection of elements in Python. It is similar to a list, but cannot be
modified after creation.

Why Use Tuples?

✅ Tuples are faster than lists (because they are immutable).


✅ They provide data integrity (values cannot be accidentally changed).
✅ They can be used as dictionary keys (because they are hashable).

1.1 Creating a Tuple

Tuples are created using parentheses () or simply by separating values with commas.

python
CopyEdit
# Creating Tuples
empty_tuple = () # Empty tuple
single_element_tuple = (5,) # Note the comma (without it, it's just an integer)
numbers = (10, 20, 30, 40)
mixed_tuple = (1, "hello", 3.14, True)

print(numbers) # (10, 20, 30, 40)

1.2 Tuple Assignment

Tuple allows multiple assignments in a single line.

python
CopyEdit
# Assigning values using a tuple
(a, b, c) = (10, 20, 30)

print(a) # 10
print(b) # 20
print(c) # 30

1.3 Accessing Tuple Elements

Elements are accessed using indexing (similar to lists).

python
CopyEdit
fruits = ("apple", "banana", "cherry")
print(fruits[0]) # apple
print(fruits[-1]) # cherry

1.4 Operations on Tuples

Operation Example Output


Concatenation (1, 2) + (3, 4) (1, 2, 3, 4)
Repetition ("hello",) * 3 ('hello', 'hello', 'hello')
Membership 3 in (1, 2, 3) True
python
CopyEdit
tuple1 = (1, 2, 3)
tuple2 = (4, 5)

# Concatenation
print(tuple1 + tuple2) # (1, 2, 3, 4, 5)

# Repetition
print(("Python",) * 3) # ('Python', 'Python', 'Python')

# Membership Test
print(2 in tuple1) # True

1.5 Tuple Immutability

Tuples cannot be changed once created.

python
CopyEdit
t = (1, 2, 3)
# t[0] = 10 # ❌ TypeError: 'tuple' object does not support item assignment

1.6 Tuple Unpacking


python
CopyEdit
person = ("John", 25, "Developer")
name, age, job = person

print(name) # John
print(age) # 25
print(job) # Developer

2️⃣ SETS in Python


What is a Set?

A set is an unordered, mutable collection of unique elements.

Why Use Sets?


✅ Fast lookup operations (better than lists).
✅ Automatically removes duplicate elements.
✅ Supports mathematical set operations (union, intersection, etc.).

2.1 Creating a Set

Sets are created using curly braces {} or the set() function.

python
CopyEdit
# Creating Sets
empty_set = set() # Empty set
numbers = {1, 2, 3, 4, 5}
mixed_set = {1, "hello", 3.14}

print(numbers) # {1, 2, 3, 4, 5}

2.2 Set Operations

Operation Example Output


Union `{1, 2} {2, 3}`
Intersection {1, 2} & {2, 3} {2}
Difference {1, 2} - {2, 3} {1}
Symmetric Diff {1, 2} ^ {2, 3} {1, 3}
python
CopyEdit
A = {1, 2, 3}
B = {2, 3, 4}

# Union
print(A | B) # {1, 2, 3, 4}

# Intersection
print(A & B) # {2, 3}

# Difference
print(A - B) # {1}

# Symmetric Difference
print(A ^ B) # {1, 4}

2.3 Set Functions


python
CopyEdit
fruits = {"apple", "banana", "cherry"}

# Add an element
fruits.add("mango")

# Remove an element
fruits.remove("banana")

# Discard an element (no error if not found)


fruits.discard("grape")
print(fruits)

3️⃣ DICTIONARIES in Python


What is a Dictionary?

A dictionary is an unordered, mutable collection of key-value pairs.

Why Use Dictionaries?

✅ Fast data retrieval using keys (better than lists).


✅ Flexible (can store any data type).
✅ Used in database storage, JSON, APIs, etc.

3.1 Creating a Dictionary

Dictionaries are created using curly braces {} with key-value pairs.

python
CopyEdit
# Creating a Dictionary
person = {
"name": "Alice",
"age": 25,
"city": "New York"
}

print(person)

3.2 Accessing Dictionary Elements

Elements are accessed using keys.

python
CopyEdit
print(person["name"]) # Alice
print(person.get("age")) # 25

3.3 Adding & Updating Dictionary Elements


python
CopyEdit
person["job"] = "Engineer" # Adding a new key-value pair
person["age"] = 30 # Updating an existing key

print(person)

3.4 Deleting Dictionary Elements


Operation Syntax
Remove key del dict[key]
Pop key-value dict.pop(key)
Clear dictionary dict.clear()
python
CopyEdit
# Removing a key
del person["city"]

# Using pop()
age = person.pop("age")

# Clearing dictionary
person.clear()

3.5 Looping through a Dictionary


python
CopyEdit
for key, value in person.items():
print(key, ":", value)

Summary
Tuples

✅ Ordered & Immutable


✅ Faster than lists
✅ Used for data integrity

Sets

✅ Unordered & Unique


✅ Used for fast lookup & set operations
✅ Automatically removes duplicates

Dictionaries

✅ Unordered key-value pairs


✅ Fast access using keys
✅ Used for data storage, JSON, APIs

Practice Questions
1. Create a tuple with 5 elements and access the 3rd element.
2. Write a program to find common elements in two sets.
3. Create a dictionary of student names and marks, then print the student with the highest mark.

Keep practicing! Python data structures are powerful!


STRING MANIPULATION in Python
Strings are one of the most used data types in Python. They are immutable sequences of characters and provide
various built-in methods for manipulation.

1️⃣ Why Use String Manipulation?


✅ Extract specific parts of a string (e.g., substring, pattern searching).
✅ Modify strings (e.g., replacing words, removing spaces).
✅ Format data for user-friendly display.
✅ Validate user inputs (e.g., checking for emails, phone numbers).

2️⃣ Creating Strings


Strings in Python can be created using single, double, or triple quotes.

python
CopyEdit
# Different ways to define strings
str1 = 'Hello'
str2 = "Python"
str3 = """This is a multi-line string."""

print(str1, str2, str3)

3️⃣ Built-in String Functions


Python provides many built-in functions to work with strings.

Function Description Example Output

len() Get length of a string len("Python") 6

upper() Convert to uppercase "hello".upper() "HELLO"

lower() Convert to lowercase "HELLO".lower() "hello"

strip() Remove spaces " hello ".strip() "hello"

replace() Replace substring "hello".replace("h", "H") "Hello"

find() Find substring index "Python".find("y") 1

count() Count occurrences "apple".count("p") 2

python
CopyEdit
text = " Hello Python! "
print(text.strip()) # Removes spaces: "Hello Python!"
print(text.upper()) # Converts to uppercase: "HELLO PYTHON!"
print(text.replace("Hello", "Hi")) # " Hi Python! "

4️⃣ Pattern Searching (Finding Substrings)


find() Method

The find() method returns the index of the first occurrence of a substring, or -1 if not found.

python
CopyEdit
sentence = "Python is powerful and easy to learn."
index = sentence.find("powerful")

print(index) # Output: 10

Using in Operator

The in operator checks if a substring exists in a string.

python
CopyEdit
text = "Python is amazing!"
print("Python" in text) # True
print("Java" in text) # False

5️⃣ Replacing and Removing Substrings


Replacing Substrings (replace())

Used to replace occurrences of a substring with another.

python
CopyEdit
text = "I love Java."
new_text = text.replace("Java", "Python")

print(new_text) # "I love Python."

Removing Substrings

To remove a substring, replace it with an empty string ("").

python
CopyEdit
sentence = "Hello, how are you?"
sentence = sentence.replace("Hello, ", "")

print(sentence) # "how are you?"

6️⃣ Working with Slice Operator ([:])


The slice operator allows extracting parts of a string.
python
CopyEdit
text = "PythonProgramming"

# Extract "Python"
print(text[0:6]) # Python

# Extract "Programming"
print(text[6:]) # Programming

# Reverse the string


print(text[::-1]) # gnimmargorPnohtyP

Slice Operator Format


vbnet
CopyEdit
string[start:end:step]

• start: Starting index (default 0)


• end: Ending index (exclusive)
• step: Increment (default 1)

Examples:
python
CopyEdit
text = "abcdef"

print(text[1:4]) # "bcd"
print(text[:4]) # "abcd"
print(text[::2]) # "ace" (every second character)
print(text[::-1]) # "fedcba" (reverse string)

7️⃣ Applying Slice Operators in Lists and Tuples


String Slicing in Lists
python
CopyEdit
fruits = ["apple", "banana", "cherry", "date"]
print(fruits[1:3]) # ['banana', 'cherry']
print(fruits[::-1]) # Reverse list: ['date', 'cherry', 'banana', 'apple']

String Slicing in Tuples


python
CopyEdit
numbers = (10, 20, 30, 40, 50)
print(numbers[2:]) # (30, 40, 50)
print(numbers[:3]) # (10, 20, 30)

Summary
✅ Built-in String Functions

• upper(), lower(), strip(), replace(), find(), count()


• Useful for modifying and searching strings.
✅ Pattern Searching

• find() for locating substrings.


• in operator for checking existence.

✅ Replacing & Removing Substrings

• replace() method to replace or remove words.

✅ Slice Operator [:]

• Extract parts of strings, lists, and tuples.


• Reverse sequences using [::-1].

Practice Questions
1️⃣ Write a program to count occurrences of a word in a sentence.
2️⃣ Create a function to remove spaces from a given string.
3️⃣ Given "hello world", extract "world" using slicing.
4️⃣ Write a function to check if a string is a palindrome (same forward & backward).

FUNCTIONS in Python
Functions are blocks of reusable code that perform a specific task. They improve code reusability, readability, and
modularity.

1️⃣ Introduction to Functions


What is a Function?

A function is a named block of code that executes when called. Functions help break down complex problems into
smaller, manageable parts.

Why Use Functions?

✅ Avoid repetition – Write code once and use it multiple times.


✅ Better readability – Code is easier to understand.
✅ Modular approach – Divide code into logical sections.
✅ Easy debugging – Fix issues in one place rather than multiple.

1.1 Defining a Function

A function is defined using the def keyword.


python
CopyEdit
# Function Definition
def greet():
print("Hello, Welcome to Python!")

# Function Call
greet()

Output:

css
CopyEdit
Hello, Welcome to Python!

2️⃣ Parameters & Arguments in Functions


Parameters: Variables listed in the function definition.
Arguments: Values passed to the function when calling it.

python
CopyEdit
# Function with Parameters
def greet(name): # 'name' is a parameter
print("Hello,", name)

greet("Alice") # 'Alice' is an argument

Output:

CopyEdit
Hello, Alice

3️⃣ Types of Function Arguments


3.1 Positional Arguments

Arguments are passed in order.

python
CopyEdit
def student_info(name, age):
print(f"Name: {name}, Age: {age}")

student_info("John", 21) # Correct Order


# student_info(21, "John") # Wrong Order

Output:

yaml
CopyEdit
Name: John, Age: 21

3.2 Arguments with Default Values

If an argument is not provided, the default value is used.


python
CopyEdit
def greet(name="Guest"):
print(f"Hello, {name}!")

greet() # Uses default value


greet("Alice") # Overwrites default value

Output:

CopyEdit
Hello, Guest!
Hello, Alice!

4️⃣ Function with Return Values


Functions can return a value using the return keyword.

python
CopyEdit
def square(num):
return num * num # Function returns num^2

result = square(5)
print("Square:", result)

Output:

makefile
CopyEdit
Square: 25

5️⃣ Lambda (Anonymous) Functions


A lambda function is a short, single-expression function.

python
CopyEdit
# Lambda function to add two numbers
add = lambda x, y: x + y
print(add(3, 5))

Output:

CopyEdit
8

✅ Use Cases of Lambda Functions


Sorting:

python
CopyEdit
students = [("Alice", 85), ("Bob", 75), ("Charlie", 95)]
students.sort(key=lambda x: x[1]) # Sort by marks
print(students)

Filtering Data:
python
CopyEdit
numbers = [1, 2, 3, 4, 5, 6]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers) # [2, 4, 6]

6️⃣ Custom Libraries


A library is a collection of functions stored in a .py file. You can import and use it in multiple programs.

6.1 Creating a Custom Library

1️⃣ Create a Python file (mymath.py)

python
CopyEdit
# mymath.py
def add(a, b):
return a + b

def multiply(a, b):


return a * b

2️⃣ Import and use it in another file

python
CopyEdit
import mymath

print(mymath.add(3, 5)) # 8
print(mymath.multiply(4, 2)) # 8

7️⃣ Custom Packages


A package is a folder that contains multiple modules and a special __init__.py file.

7.1 Creating a Package

1️⃣ Create a package folder (mypackage/)


2️⃣ Inside the folder, create an __init__.py file (can be empty).
3️⃣ Add modules, e.g., mathutils.py

python
CopyEdit
# mathutils.py
def square(n):
return n * n

4️⃣ Import and use the package

python
CopyEdit
from mypackage import mathutils

print(mathutils.square(4)) # 16
Summary
✅ Functions allow code reuse and improve readability.
✅ Parameters & Arguments allow functions to accept inputs.
✅ Lambda Functions are useful for short operations.
✅ Libraries & Packages allow creating reusable modules.

Practice Questions
1️⃣ Write a function that returns the factorial of a number.
2️⃣ Create a lambda function to check if a number is even.
3️⃣ Write a custom library with a function to calculate area of a circle.
4️⃣ Create a package with multiple math functions (addition, multiplication, square).

EXCEPTIONS in Python
An exception is an error that occurs during program execution, causing it to stop unless handled properly.

1️⃣ Introduction to Exceptions


What is an Exception?

An exception is an unwanted event that disrupts the normal flow of execution in a program.

✅ Why Handle Exceptions?


✔ Prevents program crashes.
✔ Provides user-friendly error messages.
✔ Helps debugging by logging errors.

2️⃣ Try .. Except Blocks


To handle exceptions, use try and except blocks.

python
CopyEdit
try:
num = int(input("Enter a number: ")) # User input
print(10 / num) # Division operation
except ZeroDivisionError: # Handling division by zero
print("Error! Cannot divide by zero.")
except ValueError: # Handling invalid input
print("Invalid input! Please enter a number.")

Example Runs:
Input: 2 → Output: 5.0
Input: 0 → Output: "Error! Cannot divide by zero."
Input: "abc" → Output: "Invalid input! Please enter a number."

3️⃣ Try .. Except .. Else Blocks


• else block runs if no exceptions occur.

python
CopyEdit
try:
num = int(input("Enter a number: "))
result = 10 / num
except ZeroDivisionError:
print("Cannot divide by zero!")
else:
print("Success! Result:", result)

✅ If no error, else block executes.


❌ If error occurs, else block skips.

4️⃣ Try .. Except .. Finally Blocks


• finally block always executes, whether an exception occurs or not.

python
CopyEdit
try:
file = open("data.txt", "r") # Trying to open a file
print(file.read())
except FileNotFoundError:
print("File not found!")
finally:
print("Execution completed!") # Always runs

✅ Used for cleanup operations (e.g., closing files, releasing memory).

5️⃣ Handling Multiple Exceptions


A program can handle multiple exceptions using multiple except blocks.

python
CopyEdit
try:
num = int(input("Enter a number: "))
print(10 / num)
except (ZeroDivisionError, ValueError) as e:
print("Error:", e) # Prints error message
6️⃣ Nested Exception Handlers
Exception handlers can be nested inside each other.

python
CopyEdit
try:
try:
num = int(input("Enter a number: "))
print(10 / num)
except ZeroDivisionError:
print("Cannot divide by zero!")
except ValueError:
print("Invalid input! Enter a number.")

✅ Useful when different errors require different handling logic.

7️⃣ Raising Exceptions (raise)


Use raise to manually trigger an exception.

python
CopyEdit
def check_age(age):
if age < 18:
raise ValueError("Age must be 18 or above")
else:
print("Access granted!")

check_age(15) # Raises ValueError

Output:

makefile
CopyEdit
ValueError: Age must be 18 or above

Summary
✅ try .. except handles exceptions.
✅ else runs if no exception occurs.
✅ finally always executes.
✅ Multiple exceptions can be handled together.
✅ raise manually triggers exceptions.

Practice Questions
1️⃣ Write a Python program to handle file-not-found exceptions.
2️⃣ Create a function that raises an exception if an input number is negative.
3️⃣ Write a program that asks for a number and handles zero-division errors.
4️⃣ Use finally to ensure a database connection is closed even if an error occurs.

OBJECT-ORIENTED PROGRAMMING (OOP)


in Python
Object-Oriented Programming (OOP) is a programming paradigm that organizes code into objects, allowing for
reusability, modularity, and scalability.

1️⃣ Classes & Objects


What is a Class?

A class is a blueprint for creating objects. It defines attributes (variables) and methods (functions).

python
CopyEdit
# Defining a Class
class Car:
def __init__(self, brand, model): # Constructor
self.brand = brand
self.model = model

def show_info(self): # Method


print(f"Car: {self.brand} {self.model}")

# Creating an Object
my_car = Car("Toyota", "Camry")
my_car.show_info()

Output:

makefile
CopyEdit
Car: Toyota Camry

2️⃣ Constructors (__init__ method)


A constructor is a special method that runs when an object is created.
It initializes object properties.

python
CopyEdit
class Person:
def __init__(self, name, age):
self.name = name
self.age = age

def greet(self):
print(f"Hello, my name is {self.name} and I am {self.age} years old.")

p1 = Person("Alice", 25)
p1.greet()
Output:

pgsql
CopyEdit
Hello, my name is Alice and I am 25 years old.

3️⃣ Operator Overloading


Python allows overloading operators to work with custom objects.

python
CopyEdit
class Point:
def __init__(self, x, y):
self.x = x
self.y = y

def __add__(self, other): # Overloading `+` operator


return Point(self.x + other.x, self.y + other.y)

p1 = Point(2, 3)
p2 = Point(4, 5)
result = p1 + p2 # Uses overloaded `+` operator
print(f"({result.x}, {result.y})")

Output:

scss
CopyEdit
(6, 8)

4️⃣ Inheritance
Inheritance allows a child class to inherit attributes and methods from a parent class.

python
CopyEdit
# Parent Class
class Animal:
def __init__(self, name):
self.name = name

def speak(self):
print("Animal sound!")

# Child Class (Inheriting Animal)


class Dog(Animal):
def speak(self):
print("Bark!")

d = Dog("Buddy")
d.speak() # Calls overridden method

Output:

CopyEdit
Bark!
5️⃣ Multilevel & Multiple Inheritance
5.1 Multilevel Inheritance

A class inherits from another class, which itself is inherited from another.

python
CopyEdit
class Animal:
def eat(self):
print("Eating...")

class Mammal(Animal):
def walk(self):
print("Walking...")

class Dog(Mammal):
def bark(self):
print("Barking...")

d = Dog()
d.eat() # Inherited from Animal
d.walk() # Inherited from Mammal
d.bark() # Own method

Output:

CopyEdit
Eating...
Walking...
Barking...

5.2 Multiple Inheritance

A class inherits from multiple parent classes.

python
CopyEdit
class Engine:
def start(self):
print("Engine started")

class Wheels:
def rotate(self):
print("Wheels moving")

class Car(Engine, Wheels): # Multiple Inheritance


def drive(self):
print("Car is driving")

c = Car()
c.start() # From Engine
c.rotate() # From Wheels
c.drive() # Own method

Output:

csharp
CopyEdit
Engine started
Wheels moving
Car is driving

6️⃣ Method Overriding


Child classes can override methods from their parent classes.

python
CopyEdit
class Parent:
def show(self):
print("Parent class method")

class Child(Parent):
def show(self): # Overriding Parent's method
print("Child class method")

c = Child()
c.show() # Calls overridden method

Output:

kotlin
CopyEdit
Child class method

Summary
✅ Classes define the blueprint for objects.
✅ Objects are instances of classes.
✅ Constructors (__init__) initialize object properties.
✅ Operator Overloading allows custom behaviors for operators.
✅ Inheritance enables code reuse.
✅ Multilevel & Multiple Inheritance provide complex relationships.
✅ Method Overriding allows redefining parent class methods.

Practice Questions
1️⃣ Create a Student class with name, age, and marks attributes.
2️⃣ Implement operator overloading for subtraction (-) in a class.
3️⃣ Create an Employee class with Manager and Developer as subclasses.
4️⃣ Implement multiple inheritance in a program.

FILE MANIPULATION in Python


File manipulation allows us to store, retrieve, and modify data permanently in files. Python provides
built-in functions to work with files efficiently.
1️⃣ Introduction to File Handling
Why Use Files?

✅ Store data permanently (unlike variables, which lose data when the program ends).
✅ Read & write data without needing user input every time.
✅ Manage large amounts of data efficiently.

Python uses the open() function to work with files.

python
CopyEdit
file = open("example.txt", "r") # Open file in read mode
content = file.read() # Read file content
file.close() # Close file

2️⃣ Writing & Reading Text Files


Writing to a File

• Use "w" mode (write) to create or overwrite a file.


• Use "a" mode (append) to add content without overwriting.

python
CopyEdit
file = open("sample.txt", "w") # Open file in write mode
file.write("Hello, Python File Handling!\n")
file.close() # Always close file

Reading from a File

• Use "r" mode (read) to read a file.

python
CopyEdit
file = open("sample.txt", "r") # Open file in read mode
print(file.read()) # Print file content
file.close()

Output:

arduino
CopyEdit
Hello, Python File Handling!

✅ Using with open() (Better Practice)


No need to explicitly close the file.

python
CopyEdit
with open("sample.txt", "r") as file:
content = file.read()
print(content)
3️⃣ Writing & Reading Data Files (CSV, JSON)
Reading & Writing CSV Files

CSV files store data in table format (comma-separated values).

python
CopyEdit
import csv

# Writing to CSV
with open("data.csv", "w", newline="") as file:
writer = csv.writer(file)
writer.writerow(["Name", "Age", "City"])
writer.writerow(["Alice", 25, "New York"])
writer.writerow(["Bob", 30, "London"])

# Reading from CSV


with open("data.csv", "r") as file:
reader = csv.reader(file)
for row in reader:
print(row)

Output:

css
CopyEdit
['Name', 'Age', 'City']
['Alice', '25', 'New York']
['Bob', '30', 'London']

Reading & Writing JSON Files

JSON files store data in key-value format (like Python dictionaries).

python
CopyEdit
import json

data = {
"name": "Alice",
"age": 25,
"city": "New York"
}

# Writing to JSON file


with open("data.json", "w") as file:
json.dump(data, file)

# Reading from JSON file


with open("data.json", "r") as file:
content = json.load(file)
print(content)

Output:

bash
CopyEdit
{'name': 'Alice', 'age': 25, 'city': 'New York'}
4️⃣ Writing & Reading Objects in Binary Files using pickle
The pickle module is used for storing Python objects in binary format.

python
CopyEdit
import pickle

# Writing (Pickling)
data = {"name": "Alice", "age": 25, "city": "New York"}

with open("data.pkl", "wb") as file:


pickle.dump(data, file)

# Reading (Unpickling)
with open("data.pkl", "rb") as file:
content = pickle.load(file)
print(content)

Output:

bash
CopyEdit
{'name': 'Alice', 'age': 25, 'city': 'New York'}

5️⃣ Directory Manipulation


Python’s os and shutil modules help create, delete, and manage directories.

Working with Directories


python
CopyEdit
import os

# Create a new directory


os.mkdir("NewFolder")

# Check if a directory exists


if os.path.exists("NewFolder"):
print("Folder exists!")

# Rename a directory
os.rename("NewFolder", "RenamedFolder")

# Delete a directory
os.rmdir("RenamedFolder")

Summary
✅ Text files store normal text data (.txt).
✅ CSV files store tabular data.
✅ JSON files store structured data (key-value).
✅ Pickle files store Python objects (binary format).
✅ Directory manipulation allows managing folders.
Practice Questions
1️⃣ Write a program to store student details in a text file and read it later.
2️⃣ Create a CSV file for employees and read the details.
3️⃣ Write a JSON file containing product details and retrieve it.
4️⃣ Store multiple student records in a binary file using pickle.
5️⃣ Create a Python program that creates, renames, and deletes a directory.

Keep practicing! File handling is essential for real-world applications!

You might also like