📌 1.
Introduction to Python
Python is a high-level, interpreted programming language that is widely used for web
development, data science, automation, and AI. It is known for its simple syntax and
readability.
🔹 Why Learn Python?
Easy to read and write
Large community support
Used in various fields like machine learning, web development, and game
development
Free and open-source
Supports multiple programming paradigms (object-oriented, procedural, functional)
Example:
print("Hello, Python!")
✨ Task:
Write a Python program to print your name and age.
🎯 2. Data Types, Variables, and Keywords
📍 Data Types in Python:
• int – Whole numbers (e.g., 5, 10, -3)
• float – Decimal numbers (e.g., 3.14, -2.5)
• str – Text (e.g., "Hello")
• bool – Boolean values (True, False)
• list, tuple, set, dictionary – Collections of values
📍 Variables
A variable stores data in memory.
name = "Alice" # String
age = 25 # Integer
height = 5.6 # Float
is_student = True # Boolean
📍 Keywords
Python has reserved words that cannot be used as variable names, such as if, else,
while, def, import, etc.
✨ Tasks:
Create variables for your name, age, and favorite color, and print them.
Write a program to swap two numbers without using a third variable.
🔍 3. Syntax of Python Compared to Other Languages
Python has a simple and clean syntax, unlike other languages like C or Java.
Example in Python:
if age > 18:
print("You are an adult.")
Same code in Java:
if (age > 18) {
[Link]("You are an adult.");
Python does not use curly braces {} or semicolons ;, making it more readable.
✨ Tasks:
Write a Python program to check if a number is positive, negative, or zero.
Convert a simple C program into Python.
⏳ 4. Python Installation
📌 Steps to Install Python:
1. Download from [Link]
2. Install the downloaded file
3. Open the command prompt and type python to check the installation
✨ Task:
Install Python and run a simple print("Hello, Python!") program.
🖥️ 5. Print Statement
Used to display output.
print("Hello, World!")
You can also print multiple values:
print("My name is", name)
✨ Tasks:
Write a Python program to print a greeting message with your name.
Print a triangle pattern using the print function.
📑 6. Comments in Python
Comments help make the code readable.
• Single-line comment:
# This is a comment
• Multi-line comment:
"""
This is a multi-line comment.
Python ignores these lines.
"""
✨ Tasks:
Write a Python program with both single-line and multi-line comments explaining
each step.
🖊 7. Input & Output in Python
📌 Getting user input:
name = input("Enter your name: ")
print("Hello,", name)
✨ Tasks:
Write a Python program to take user input for age and print whether they are eligible
to vote.
Write a program that takes two numbers as input and prints their sum.
8. Strings in Python
Strings are sequences of characters.
text = "Python is fun!"
print([Link]()) # Converts to uppercase
print([Link]()) # Converts to lowercase
Tasks:
• Write a Python program to convert a string to uppercase.
• Write a Python program to convert a string to lowercase.
count()
• Purpose: Returns the number of occurrences of a substring in a string.
text = "Python is fun! Python is awesome!"
print([Link]("Python")) # Counts occurrences of "Python"
Tasks:
• Write a Python program to count the number of occurrences of a specific
letter in a string.
• Write a Python program to count how many times a word appears in a
sentence.
replace()
• Purpose: Replaces occurrences of a substring with another substring.
text = "Python is fun!"
print([Link]("fun", "awesome")) # Replaces "fun" with "awesome"
Tasks:
• Write a Python program to replace all occurrences of a word with another
word in a sentence.
• Write a Python program to replace vowels in a string with the '*' character.
strip(), lstrip(), rstrip()
• Purpose: Removes leading/trailing spaces or specified characters.
text = " Python is fun! "
print([Link]()) # Removes leading/trailing spaces.
Tasks:
• Write a Python program to remove leading and trailing spaces from a string.
• Write a Python program to remove leading spaces only from a string.
startswith() and endswith()
• Purpose: Check whether a string starts or ends with a specified substring.
text = "Python is fun!"
print([Link]("Python")) # Check if the string starts with "Python"
print([Link]("fun!")) # Check if the string ends with "fun!"
Tasks:
• Write a Python program to check if a string starts with a specific word.
• Write a Python program to check if a string ends with a specific word.
split()
• Purpose: Splits a string into a list based on a delimiter (space by default).
text = "Python is fun!"
words = [Link]() # Splits by space
print(words)
Tasks:
• Write a Python program to split a string into a list of words.
• Write a Python program to split a string by commas
join()
• Purpose: Joins a sequence of strings with a specified delimiter.
words = ["Python", "is", "fun"]
sentence = " ".join(words) # Joins with a space
print(sentence)
Tasks:
• Write a Python program to join a list of words into a sentence with a space
between them.
• Write a Python program to join a list of words into a sentence with commas.
find()
• Purpose: Returns the index of the first occurrence of a substring.
text = "Python is fun!"
print([Link]("fun")) # Returns the index of "fun"
Tasks:
• Write a Python program to find the position of a specific word in a string.
• Write a Python program to find the first occurrence of a letter in a string.
isalpha()
• Purpose: Returns True if all characters in the string are alphabetic.
text = "Python"
print([Link]()) # Returns True if all characters are alphabetic.
Tasks:
• Write a Python program to check if a string contains only letters.
• Write a Python program to check if a string contains any digits.
isdigit()
• Purpose: Returns True if all characters in the string are digits.
text = "12345"
print([Link]()) # Returns True if all characters are digits.
Tasks:
• Write a Python program to check if a string contains only digits.
• Write a Python program to check if a string contains non-numeric characters.
upper() and swapcase()
• Purpose: Swaps uppercase characters to lowercase and vice versa.
text = "Python is Fun!"
print([Link]()) # Swaps case of each character.
Tasks:
• Write a Python program to swap the case of all letters in a string.
• Write a Python program to convert only the first letter to uppercase.
• Write a Python program to count the number of characters in a string.
• Reverse a string using slicing.
Slicing in Python
Slicing allows you to extract parts of a string using a specific range of indices. It is a
powerful technique for working with substrings.
Syntax:
string[start:end:step]
• start: The index from where the slice starts (inclusive).
• end: The index where the slice ends (exclusive).
• step: The interval between each character in the slice (optional).
text = "Python is fun!"
print(text[0:6]) # Output: 'Python'
print(text[7:]) # Output: 'is fun!'
print(text[:6]) # Output: 'Python'
print(text[::2]) # Output: 'Pto sfn'
print(text[::-1]) # Output: '!nuf si nohtyP'
• text[0:6]: Starts from index 0 and extracts up to index 6, not including the character
at index 6, so it returns 'Python'.
• text[7:]: Starts from index 7 and extracts the rest of the string, returning 'is fun!'.
• text[:6]: Extracts from the start of the string up to index 6, giving 'Python'.
• text[::2]: Extracts every second character of the string, resulting in 'Pto sfn'.
• text[::-1]: Reverses the string by using a negative step, producing '!nuf si
nohtyP'.
Write a Python program to reverse a string using slicing.
def reverse_string(text):
return text[::-1]
print(reverse_string("Python"))
Write a Python program to extract every second character from a string.
def every_second_char(text):
return text[::2]
print(every_second_char("Python is fun"))
📋 9. List in Python
A list is an ordered, mutable collection of items.
Lists are ordered collections of items, and they allow duplicate elements. You can store
different types of data (e.g., integers, strings, etc.) in a list.
append()
• Purpose: Adds an element to the end of the list.
my_list = [1, 2, 3]
my_list.append(4) # Adds 4 to the end of the list
print(my_list) # Output: [1, 2, 3, 4]
Tasks:
• Write a Python program to append an item to a list.
• Write a Python program to append a string to a list of numbers.
2. extend()
• Purpose: Extends the list by appending all elements from another iterable (e.g., list,
tuple).
my_list = [1, 2, 3]
my_list.extend([4, 5]) # Adds elements from [4, 5]
print(my_list) # Output: [1, 2, 3, 4, 5]
Tasks:
• Write a Python program to extend a list with another list.
• Write a Python program to merge two lists.
insert()
• Purpose: Inserts an element at a specified index in the list.
my_list = [1, 2, 4]
my_list.insert(2, 3) # Inserts 3 at index 2
print(my_list) # Output: [1, 2, 3, 4]
Tasks:
• Write a Python program to insert an element into the list at the second
position.
• Write a Python program to insert an element at the beginning of a list.
remove()
• Purpose: Removes the first occurrence of a specified element from the list.
my_list = [1, 2, 3, 4, 5]
my_list.remove(3) # Removes the first occurrence of 3
print(my_list) # Output: [1, 2, 4, 5]
Tasks:
• Write a Python program to remove an element from the list.
• Write a Python program to remove a specific item from a list by value.
pop()
• Purpose: Removes and returns an element from the list at the given index (default
is the last element).
my_list = [1, 2, 3, 4]
popped_item = my_list.pop(2) # Removes and returns item at index 2
print(popped_item) # Output: 3
print(my_list) # Output: [1, 2, 4]
Tasks:
• Write a Python program to pop an item from the list by index.
• Write a Python program to pop the last element from a list.
index()
• Purpose: Returns the index of the first occurrence of a specified element.
my_list = [1, 2, 3, 4, 5]
index_of_3 = my_list.index(3) # Finds the index of the element 3
print(index_of_3) # Output: 2
Tasks:
• Write a Python program to find the index of a specified element in a list.
• Write a Python program to return the index of the first occurrence of a string
in a list.
count()
• Purpose: Returns the number of occurrences of an element in the list.
my_list = [1, 2, 3, 2, 1, 2]
count_of_2 = my_list.count(2) # Counts occurrences of 2
print(count_of_2) # Output: 3
Tasks:
• Write a Python program to count the number of occurrences of a specific
number in a list.
• Write a Python program to count how many times a word appears in a list.
sort()
• Purpose: Sorts the list in ascending order by default, or you can specify a custom
order.
my_list = [3, 1, 4, 2]
my_list.sort() # Sorts the list in ascending order
print(my_list) # Output: [1, 2, 3, 4]
Tasks:
• Write a Python program to sort a list in ascending order.
• Write a Python program to sort a list of strings alphabetically.
reverse()
• Purpose: Reverses the elements of the list in place.
my_list = [1, 2, 3, 4]
my_list.reverse() # Reverses the list in place
print(my_list) # Output: [4, 3, 2, 1]
Tasks:
• Write a Python program to reverse a list.
• Write a Python program to reverse a list of strings.
clear()
• Purpose: Removes all elements from the list.
my_list = [1, 2, 3, 4]
my_list.clear() # Clears the list
print(my_list) # Output: []
Tasks:
• Write a Python program to clear all elements from a list.
• Write a Python program to delete a list's contents without deleting the list
itself.
copy()
• Purpose: Returns a shallow copy of the list.
my_list = [1, 2, 3]
my_copy = my_list.copy() # Creates a copy of the list
print(my_copy) # Output: [1, 2, 3]
Tasks:
• Write a Python program to copy a list into another list.
• Write a Python program to make a copy of a list and modify the original list.
max() and min()
• Purpose: Returns the largest and smallest item in the list, respectively
my_list = [1, 2, 3, 4, 5]
print(max(my_list)) # Output: 5
print(min(my_list)) # Output: 1
Tasks:
• Write a Python program to find the largest number in a list.
• Write a Python program to find the smallest string in a list of strings.
Set in Python
A set is an unordered collection that stores unique values. Unlike lists or tuples, sets
cannot contain duplicate elements, and the order of elements in a set is not guaranteed.
Set Methods in Python
Here are some common set methods with examples and tasks.
1. add()
• Purpose: Adds a single element to the set. If the element is already present, the set
remains unchanged.
my_set = {1, 2, 3}
my_set.add(4) # Adds 4 to the set
print(my_set) # Output: {1, 2, 3, 4}
Tasks:
• Write a Python program to add an element to a set.
• Write a Python program to add multiple elements to a set using a loop.
2. update()
• Purpose: Adds multiple elements from an iterable (e.g., list, tuple) to the set.
my_set = {1, 2, 3}
my_set.update([4, 5]) # Adds elements from the list [4, 5]
print(my_set) # Output: {1, 2, 3, 4, 5}
Tasks:
• Write a Python program to update a set with multiple elements.
• Write a Python program to combine two sets using update().
3. remove()
• Purpose: Removes a specific element from the set. If the element is not found, it
raises a KeyError.
my_set = {1, 2, 3, 4}
my_set.remove(3) # Removes 3 from the set
print(my_set) # Output: {1, 2, 4}
Tasks:
• Write a Python program to remove an element from a set.
• Write a Python program to handle a KeyError when trying to remove an
element not in the set.
intersection()
• Purpose: Returns a new set with elements common to both sets.
set1 = {1, 2, 3}
set2 = {3, 4, 5}
intersection_set = [Link](set2) # Returns common elements
print(intersection_set) # Output: {3}
Tasks:
• Write a Python program to find the intersection of two sets.
• Write a Python program to find the common elements between two sets.
difference()
• Purpose: Returns a new set with elements that are in the first set but not in the
second set.
set1 = {1, 2, 3}
set2 = {3, 4, 5}
difference_set = [Link](set2) # Returns elements in set1 but not in set2
print(difference_set) # Output: {1, 2}
Tasks:
• Write a Python program to find the difference between two sets.
• Write a Python program to subtract one set from another.
• Find the common elements between two sets.
Tuple in Python
A tuple is an immutable collection of ordered elements. Unlike lists, tuples cannot be
changed after they are created. You can think of a tuple as a fixed-size list.
Tuple Characteristics:
• Ordered: The items in a tuple have a defined order and can be accessed by their
index.
• Immutable: Once a tuple is created, it cannot be modified. You cannot add, remove,
or change items in a tuple.
• Can Contain Mixed Data Types: Tuples can hold elements of different types (e.g.,
integers, strings, etc.).
• Allow Duplicate Values: Tuples can contain duplicate values, just like lists.
Creating Tuples
You can create a tuple by placing elements inside parentheses, separated by commas.
coordinates = (10, 20)
print(coordinates[0]) # Output: 10
In this example, (10, 20) is a tuple with two elements, and you can access each element
using the index (e.g., coordinates[0]).
Tuple Methods
Unlike lists, tuples have only a few methods because they are immutable. The most
commonly used methods are:
1. count()
• Purpose: Returns the number of occurrences of a specified element in the tuple.
my_tuple = (1, 2, 3, 2, 4, 2)
count_of_2 = my_tuple.count(2) # Counts occurrences of 2
print(count_of_2) # Output: 3
Tasks:
• Write a Python program to count how many times an element appears in a tuple.
2. index()
• Purpose: Returns the index of the first occurrence of a specified element in the
tuple.
my_tuple = (1, 2, 3, 4)
index_of_3 = my_tuple.index(3) # Finds the index of 3
print(index_of_3) # Output: 2
Tasks:
• Write a Python program to find the index of a specified element in a tuple.
• Write a Python program to find the index of the first occurrence of a string in a
tuple.
3. len()
• Purpose: Returns the number of elements in the tuple.
my_tuple = (1, 2, 3, 4)
tuple_length = len(my_tuple) # Returns the length of the tuple
print(tuple_length) # Output: 4
Tasks:
• Write a Python program to find the length of a tuple.
4. max() and min()
• Purpose: Returns the maximum and minimum values from a tuple.
my_tuple = (1, 5, 3, 7, 2)
print(max(my_tuple)) # Output: 7
print(min(my_tuple)) # Output: 1
Tasks:
• Write a Python program to find the largest and smallest element in a tuple.
5. Concatenation and Repetition
• Purpose: Tuples can be concatenated (using +) or repeated (using *).
tuple1 = (1, 2)
tuple2 = (3, 4)
concatenated_tuple = tuple1 + tuple2 # Concatenation
print(concatenated_tuple) # Output: (1, 2, 3, 4)
repeated_tuple = tuple1 * 3 # Repetition
print(repeated_tuple) # Output: (1, 2, 1, 2, 1, 2)
Tasks:
• Write a Python program to concatenate two tuples.
• Write a Python program to repeat a tuple multiple times.
6. tuple() Constructor
• Purpose: You can convert other data types, like lists or strings, into a tuple using
the tuple() constructor.
my_list = [1, 2, 3]
my_tuple = tuple(my_list) # Converts a list to a tuple
print(my_tuple) # Output: (1, 2, 3)
Tasks:
• Write a Python program to convert a list into a tuple.
• Write a Python program to convert a string into a tuple.
Immutability of Tuples
Tuples are immutable, which means you cannot modify them once they are created.
However, if the tuple contains mutable objects like lists, you can modify those objects.
Here's an example of what you cannot do:
my_tuple = (1, 2, 3)
# Trying to modify an element in a tuple will raise an error
# my_tuple[0] = 10 # TypeError: 'tuple' object does not support item assignment.
Dictionary in Python
A dictionary is an unordered collection of key-value pairs. Each key is unique, and each
key is associated with a value. Dictionaries are mutable, which means you can change
them after creation.
Dictionary Characteristics:
• Unordered: The elements in a dictionary do not have a defined order.
• Key-Value Pairs: Each item in a dictionary consists of a key and a value.
• Mutable: You can add, remove, or modify elements in a dictionary.
• Keys are Unique: No two keys can be the same within a dictionary.
Creating a Dictionary
A dictionary is created by placing key-value pairs inside curly braces {}. The key and
value are separated by a colon :.
student = {'name': 'Alice', 'age': 25, 'grade': 'A'}
print(student['name']) # Output: Alice
Dictionary Methods
1. get()
• Purpose: Returns the value associated with the given key. If the key is not found, it
returns None or a default value if provided.
student = {'name': 'Alice', 'age': 25}
age = [Link]('age') # Returns 25
print(age)
Tasks:
• Write a Python program to get the value of a key in a dictionary.
• Write a Python program to get a default value if a key is not present in a
dictionary.
2. keys()
• Purpose: Returns a view object that displays all the keys in the dictionary.
student = {'name': 'Alice', 'age': 25}
keys = [Link]()
print(keys) # Output: dict_keys(['name', 'age'])
Tasks:
• Write a Python program to display all the keys in a dictionary.
3. values()
• Purpose: Returns a view object that displays all the values in the dictionary.
student = {'name': 'Alice', 'age': 25}
values = [Link]()
print(values) # Output: dict_values(['Alice', 25])
Tasks:
• Write a Python program to display all the values in a dictionary.
4. items()
• Purpose: Returns a view object that displays a list of dictionary's key-value tuple
pairs.
student = {'name': 'Alice', 'age': 25}
items = [Link]()
print(items) # Output: dict_items([('name', 'Alice'), ('age', 25)])
Tasks:
• Write a Python program to display all the key-value pairs in a dictionary.
5. update()
• Purpose: Adds key-value pairs to the dictionary, or updates existing keys with new
values.
student = {'name': 'Alice', 'age': 25}
[Link]({'age': 26, 'grade': 'A'})
print(student) # Output: {'name': 'Alice', 'age': 26, 'grade': 'A'}
Tasks:
• Write a Python program to update a value of an existing key in a dictionary.
• Write a Python program to add new key-value pairs to a dictionary.
6. pop()
• Purpose: Removes and returns the value associated with the given key. If the key
does not exist, it raises a KeyError.
student = {'name': 'Alice', 'age': 25}
age = [Link]('age') # Removes the key 'age' and returns its value
print(age) # Output: 25
print(student) # Output: {'name': 'Alice'}
Tasks:
• Write a Python program to remove a key-value pair from a dictionary using
pop().
• Write a Python program to handle KeyError when trying to pop a non-existent
key.
7. popitem()
• Purpose: Removes and returns the last inserted key-value pair as a tuple. If the
dictionary is empty, it raises a KeyError.
student = {'name': 'Alice', 'age': 25}
removed_item = [Link]() # Removes and returns the last inserted item
print(removed_item) # Output: ('age', 25)
print(student) # Output: {'name': 'Alice'}
Tasks:
• Write a Python program to remove and return the last inserted key-value pair
from a dictionary.
8. clear()
• Purpose: Removes all the key-value pairs from the dictionary.
student = {'name': 'Alice', 'age': 25}
[Link]() # Clears the dictionary
print(student) # Output: {}
Tasks:
• Write a Python program to clear all the key-value pairs in a dictionary.
del
• Purpose: Deletes a specific key-value pair from the dictionary.
Tasks:
• Write a Python program to delete a specific key-value pair from a dictionary.
• Write a Python program to handle errors when trying to delete a non-existent
key.
fromkeys()
• Purpose: Creates a new dictionary with keys from an iterable and sets their values
to a specified value.
keys = ['name', 'age', 'grade']
default_value = 'Unknown'
student = [Link](keys, default_value)
print(student) # Output: {'name': 'Unknown', 'age': 'Unknown', 'grade': 'Unknown'}
Tasks:
• Write a Python program to create a dictionary from a list of keys with a
default value.
4. Operators in Python
Operators are symbols in Python that perform operations on variables and values. Python
supports various types of operators including arithmetic, comparison, logical, and more.
Types of Operators:
1. Arithmetic Operators
These operators are used to perform mathematical operations like addition, subtraction,
etc.
• +: Addition
• -: Subtraction
• *: Multiplication
• /: Division
• //: Floor division (returns the integer part)
• %: Modulus (remainder)
• ****: Exponentiation
Example:
x = 10
y=3
print(x + y) # Addition: 13
print(x - y) # Subtraction: 7
print(x * y) # Multiplication: 30
print(x / y) # Division: 3.333
print(x // y) # Floor division: 3
print(x % y) # Modulus: 1
print(x ** y) # Exponentiation: 1000
2. Comparison Operators
These operators are used to compare two values.
• ==: Equal to
• !=: Not equal to
• >: Greater than
• <: Less than
• >=: Greater than or equal to
• <=: Less than or equal to
x = 10
y=5
print(x == y) # False
print(x != y) # True
print(x > y) # True
print(x < y) # False
print(x >= y) # True
print(x <= y) # False
3. Logical Operators
These are used to combine conditional statements.
• and: Returns True if both conditions are True.
• or: Returns True if at least one condition is True.
• not: Reverses the result, returns True if the condition is False.
x = 10
y=5
z=3
print(x > y and y > z) # True
print(x > y or y < z) # True
print(not(x > y)) # False
4. Assignment Operators
Used to assign values to variables.
• =: Assigns a value.
• +=: Adds and assigns.
• -=: Subtracts and assigns.
• *=: Multiplies and assigns.
• /=: Divides and assigns.
• %=: Modulus and assigns.
x=5
x += 3 # x = x + 3 → 8
x -= 2 # x = x - 2 → 6
x *= 2 # x = x * 2 → 12
x /= 4 # x = x / 4 → 3.0
x %= 2 # x = x % 2 → 1
Tasks for Operators:
Task 1: Write a program to calculate the area of a rectangle. Use arithmetic operators
for length and width.
Task 2: Compare two numbers using comparison operators to check if one is greater
than the other.
Indentation in Python
Indentation is crucial in Python. It is used to define the scope of loops, functions, classes,
etc. Python uses indentation (spaces or tabs) to determine the grouping of statements.
Unlike other programming languages that use curly braces {}, Python relies on
indentation to indicate blocks of code.
Why Indentation is Important:
• It helps define the scope of a loop, conditional block, or function.
• Without proper indentation, Python will raise an IndentationError.
Example:
if 5 > 3:
print("5 is greater than 3") # This line is indented
print("This is inside the if block")
print("This is outside the if block") # This is outside the if block
Common Indentation Errors:
1. Mixing tabs and spaces for indentation will raise an error.
2. Uneven indentation can cause the code to fail or behave unexpectedly.
Indentation Example:
if True:
print("This is inside the block") # Indented correctly
print("This will cause an error") # Incorrect indentation, will raise IndentationError.
Control Statements in Python
Control statements are used to alter the flow of execution of the program. These include
conditional statements, loops, and control flow mechanisms like break, continue, and
pass.
1. Conditional Statements
These are used to check conditions and execute code based on whether the condition is
True or False.
• if: Executes the block of code if the condition is True.
• elif: Checks another condition if the if condition is False.
• else: Executes the block of code when all previous conditions are False.
Example –
age = 18
if age >= 18:
print("You are an adult")
elif age < 18:
print("You are a minor")
else:
print("Unknown age")
elif Statement
The elif (short for "else if") statement is used to check additional conditions if the
previous if condition was False. You can use multiple elif statements to test various
conditions.
Syntax:
if condition1:
# Code block if condition1 is True
elif condition2:
# Code block if condition2 is True
elif condition3:
# Code block if condition3 is True
else:
# Code block if all previous conditions are False.
Example –
age = 16
if age >= 18:
print("You are an adult")
elif age >= 13:
print("You are a teenager")
else:
print("You are a child").
Task 1: Write a Python program that checks if a number is even or odd using an if statement.
✅ Task 2: Write a Python program that checks if a given number is positive or negative using
an if statement.
✅ Task 3: Write a Python program that checks if a person is eligible to vote (age 18 or above)
using an if statement.
✅ Task 4: Write a Python program to check if a given string is a palindrome using an if
statement.
✅ Task 5: Write a Python program to check if a number is divisible by 5 using an if
statement.
✅ Task 6: Write a Python program that checks if a number is greater than 100 and less than
200 using an if statement.
✅ Task 7: Write a Python program that checks if the entered temperature is above freezing
(32°F) or not using an if statement.
✅ Task 8: Write a Python program that checks if a given year is a leap year using an if
statement. (Hint: A leap year is divisible by 4 but not by 100 unless also divisible by 400.)
✅ Task 9: Write a Python program that checks if a number is greater than 50 but less than
100 using an if statement.
✅ Task 10: Write a Python program that checks if a number is greater than or equal to 1000,
and print "Large" if True, otherwise print "Small".
else Statement
The else statement provides a block of code that will be executed if all previous if or
elif conditions are False. It is optional and can be added as the final block.
Syntax:
if condition:
# Code block if condition is True
else:
# Code block if condition is False.
Example
x=5
if x == 10:
print("x is 10")
else:
print("x is not 10")
Nested Conditional Statements
Conditional statements can be nested, meaning you can place an if, elif, or else inside
another if, elif, or else.
Example:
x=5
y = 10
if x < y:
if x == 5:
print("x is 5 and less than y")
else:
print("x is less than y, but not 5")
else:
print("x is not less than y")
Task 1: Write a Python program to check if a number is positive, negative, or zero.
Task 2: Write a Python program to check if a year is a leap year or not.
Task 3: Write a Python program that takes an input age and prints whether the
person is a child (0-12), teenager (13-19), adult (20-64), or senior (65+).
Task 4: Write a program that checks whether a number is divisible by both 3 and 5
using logical operators.
Task 5: Create a program that asks for the user’s score and prints the corresponding
grade:
• If the score is 90 or above, print "A"
• If the score is between 80 and 89, print "B"
• If the score is between 70 and 79, print "C"
• If the score is below 70, print "F"
Break and Continue
• break: Terminates the current loop and exits.
• continue: Skips the current iteration and moves to the next one.
Example:
for i in range(5):
if i == 3:
break # Exits the loop when i is 3
print(i)
Example
for i in range(5):
if i == 3:
continue # Skips the iteration when i is 3
print(i)
Pass Statement
The pass statement is a placeholder that does nothing. It is often used when a statement
is required syntactically but you don't want to execute any code.
Example:
if True:
pass # Placeholder for future code
Task 1: Write a Python program using if, elif, and else to check if a number is
positive, negative, or zero.
Task 2: Write a program that uses continue to skip even numbers and print only the
odd numbers from 1 to 10.
Task 3: Use a break statement in a loop to stop printing when the number reaches 7.
🔄 13. Loops in Python
Loops allow you to execute a block of code repeatedly. In Python, there are two primary
types of loops: for loops and while loops. These loops are useful when you want to
automate repetitive tasks.
For Loop
A for loop is used to iterate over a sequence (like a list, tuple, string, or range) and
execute a block of code for each item in the sequence.
Syntax:
for item in sequence:
# Code block to execute for each item.
Example 1: Iterating with range()
You can use range() to generate a sequence of numbers. Here's an example of using a
for loop to iterate through the numbers 0 to 4.
for i in range(5): # Loop runs from 0 to 4
print(i)
The range(5) generates a sequence of numbers starting from 0 up to, but not including, 5.
Task 1: Print numbers from 1 to 10 using a for loop.
Task 2: Print the squares of numbers from 1 to 5 using a for loop.
Task 3: Calculate the sum of numbers from 1 to 100 using a for loop.
Task 4: Find the largest number in a given list using a for loop.
Task 5: Count the occurrences of a specific element (e.g., 2) in a list using a for loop.
Task 6: Print the first 10 Fibonacci numbers using a for loop.
Task 7: Print the reverse of a string using a for loop.
Task 8: Find the factorial of a number using a for loop.
Task 9: Print a multiplication table for a given number (e.g., 5) using a for loop.
Task 10: Find the common elements between two lists using a for loop.
While Loop in Python
A while loop is used to execute a block of code repeatedly as long as a specified
condition evaluates to True. Once the condition becomes False, the loop stops executing.
Syntax of While Loop:
while condition:
# Code block to execute as long as the condition is True.
• Condition: The condition is evaluated before each iteration. If the condition is True,
the code inside the loop is executed. If the condition is False, the loop terminates.
• The code inside the loop is executed repeatedly until the condition becomes False.
Key Points:
1. Condition must be Boolean: The condition inside a while loop must evaluate to a
boolean value (True or False).
2. Infinite Loop: If the condition never becomes False, the loop will run forever,
causing an infinite loop. This can be avoided by ensuring that the condition
eventually becomes False.
3. Updating the condition: Inside the loop, you should modify the variables involved
in the condition to avoid an infinite loop. Usually, this is done by incrementing or
changing a variable.
Example-
count = 0
while count < 5:
print(count)
count += 1 # Incrementing the counter.
Tasks for While Loop:
Task 1: Write a Python program to print numbers from 1 to 10 using a while loop.
Task 2: Write a Python program to calculate the sum of digits of a number using a
while loop.
Task 3: Write a Python program that prints the Fibonacci sequence up to the 10th
term using a while loop.
Task 4: Write a Python program that keeps asking the user for input until they enter
the word "stop."
Comparison with For Loop:
• A for loop is generally used when you know the exact number of iterations, or you
are iterating over a sequence (like a list or range).
• A while loop is used when you don’t know beforehand how many times the loop
will execute and when you want the loop to continue based on a condition.
Functions in Python
What is a Function?
A function is a block of reusable code that performs a specific task. Instead of writing the
same code multiple times, we define a function once and call it whenever needed.
Benefits of Using Functions:
✔ Code Reusability: Write once, use multiple times.
✔ Modularity: Break a large program into smaller parts.
✔ Readability: Makes the code easier to understand.
✔ Avoid Repetition: No need to write the same code multiple times.
Types of Functions in Python
1. Built-in Functions – Predefined functions like print(), len(), max(), etc.
2. User-defined Functions – Functions created by the user using the def keyword.
3. Lambda Functions – Anonymous functions (one-liner functions).
4. Recursive Functions – Functions that call themselves.
1️⃣ Defining and Calling a Function
How to Define a Function?
In Python, we define a function using the def keyword, followed by a function name and
parentheses ().
Syntax:
def function_name():
# Function body (code)
print("This is a function")
Calling a Function:
function_name() # Calling the function
Example:
def greet():
print("Hello, welcome to Python!")
greet() # Output: Hello, welcome to Python!
✅ Task 1:
Write a function hello() that prints "Hello, World!".
Function with Parameters
A function can take parameters (inputs) to perform operations on different values.
Syntax:
def function_name(parameter1, parameter2):
# Function body
print(parameter1, parameter2)
Function with Parameters
A function can take parameters (inputs) to perform operations on different values.
Syntax:
def function_name(parameter1, parameter2):
# Function body
print(parameter1, parameter2)
Example:
def add_numbers(a, b):
sum = a + b
print("Sum:", sum)
add_numbers(5, 10) # Output: Sum: 15
✅ Task 2:
Write a function multiply(x, y) that takes two numbers and prints their product.
3️⃣ Function with Return Statement
A function can return a value using the return keyword.
Example:
def square(num):
return num * num
result = square(4)
print("Square:", result) # Output: Square: 16
✅ Task 3:
Write a function subtract(a, b) that returns the difference of two numbers.
4️⃣ Default Parameters
Default parameters allow setting a default value for a function parameter. If no value is
provided when calling the function, the default value is used.
Example:
def greet(name="Guest"):
print("Hello,", name)
greet() # Output: Hello, Guest
greet("Alice") # Output: Hello, Alice
✅ Task 4:
Write a function power(base, exponent=2) that returns base raised to exponent.
5️⃣ Keyword Arguments (kwargs)
Python allows passing arguments with keywords, so their order doesn’t matter.
Example:
def introduce(name, age):
print(f"My name is {name} and I am {age} years old.")
introduce(age=25, name="John") # Output: My name is John and I am 25 years old.
✅ Task 5:
Write a function student_info(name, grade) that takes keyword arguments and
prints student details.
6️⃣ Arbitrary Arguments (*args and **kwargs)
1. *args (Multiple Positional Arguments) – Used to pass multiple values as a tuple.
2. **kwargs (Multiple Keyword Arguments) – Used to pass multiple key-value pairs
as a dictionary.
Example of *args:
def sum_numbers(*args):
total = sum(args)
print("Sum:", total)
sum_numbers(5, 10, 15) # Output: Sum: 30
Example of **kwargs:
def student_details(**kwargs):
for key, value in [Link]():
print(f"{key}: {value}")
student_details(name="Alice", age=22, course="Python")
✅ Task 6:
Write a function calculate_total(*prices) that returns the sum of all prices
passed.
7️⃣ Lambda (Anonymous) Function
A lambda function is a small, one-line function without a name.
Syntax:
lambda arguments: expression
example:
square = lambda x: x * x
print(square(4)) # Output: 16
✅ Task 7:
Write a lambda function to find the maximum of two numbers.
8️⃣ Recursive Function
A recursive function calls itself to solve a problem.
Example: Factorial Calculation
def factorial(n):
if n == 1:
return 1
return n * factorial(n - 1)
print(factorial(5)) # Output: 120
✅ Task 8:
Write a recursive function to calculate the sum of numbers from 1 to N.
9️⃣ Nested Functions
A function inside another function is called a nested function.
def outer():
print("Outer function")
def inner():
print("Inner function")
inner()
outer()
✅ Task 9:
Write a function parent() that defines and calls a nested function child().
Summary of Function Concepts
Concept Description
Function Definition def function_name(): Defines a function
Function Call function_name() Calls a function
Parameters Inputs to a function (def func(x, y))
Return Statement Returns a value (return x + y)
Default Parameters Assigns a default value (def func(x=10))
*args Multiple positional arguments (def func(*args))
**kwargs Multiple keyword arguments (def func(**kwargs))
Lambda Function One-line anonymous function (lambda x: x * x)
Recursion Function calling itself (def func(): func())
Object-Oriented Programming (OOP) in Python
What is OOP?
Object-Oriented Programming (OOP) is a programming approach that uses objects and
classes to organize and structure code efficiently. It helps in modeling real-world entities
using attributes (data) and methods (functions).
🔹 Key OOP Concepts
Concept Description
Class A blueprint for creating objects.
Concept Description
Object An instance of a class.
Encapsulation Hiding data to protect it from unauthorized access.
Inheritance Acquiring properties from another class.
Polymorphism Using the same method in different ways.
Abstraction Hiding implementation details and showing only necessary features.
1️⃣ Classes and Objects
Class:
A class is a blueprint or template for creating objects (instances). It defines the attributes
(properties) and behaviors (methods) that the objects created from the class will have.
• Attributes (Properties): Variables inside a class that store data or characteristics
of an object.
• Methods (Behaviors): Functions inside a class that define the actions an object
can perform.
Syntax for Creating a Class:
class ClassName:
# Constructor (optional)
def __init__(self, parameters):
self.attribute1 = value
self.attribute2 = value
# Method
def method_name(self):
pass
What is an Object?
An object is an instance of a class. It is created based on the blueprint (class) and has the
actual values for the attributes. Objects can perform actions defined in the methods of the
class.
Creating an Object:
object_name = ClassName(arguments)
1️⃣ Creating a Class and Object
Example:
class Dog:
def __init__(self, name, breed):
[Link] = name
[Link] = breed
def speak(self):
print(f"{[Link]} says Woof!")
# Creating an object of class Dog
dog1 = Dog("Buddy", "Golden Retriever")
dog2 = Dog("Max", "Bulldog")
# Accessing attributes
print([Link]) # Output: Buddy
print([Link]) # Output: Bulldog
# Calling methods
[Link]() # Output: Buddy says Woof!
[Link]() # Output: Max says Woof!
✅ Task 1:
Create a class Student with attributes name and marks, and a method display() to
print student details.
• Create two objects of the Student class and print their details.
2️⃣ Constructor (__init__ Method)
The constructor is a special method __init__() that is automatically called when an
object is created. It is used to initialize the object's attributes with values.
Syntax:
def __init__(self, param1, param2):
self.attribute1 = param1
self.attribute2 = param2
Example:
class Car:
def __init__(self, brand, model, year):
[Link] = brand
[Link] = model
[Link] = year
def display_info(self):
print(f"Car Info: {[Link]} {[Link]} {[Link]}")
car1 = Car("Toyota", "Corolla", 2020)
car1.display_info() # Output: Car Info: 2020 Toyota Corolla
Explanation:
• self refers to the current instance of the class.
• The __init__() method is used to set the brand, model, and year attributes when
an object is created.
✅ Task 2:
Create a class Book with attributes title, author, and price. Write a method
discount() to apply a discount and print the discounted price.
Accessing Attributes and Methods of an Object
You can access the attributes and methods of an object using the dot notation:
object_name.attribute_name or object_name.method_name().
Example:
class Person:
def __init__(self, name, age):
[Link] = name
[Link] = age
def greet(self):
print(f"Hello, my name is {[Link]} and I am {[Link]} years old.")
# Creating an object of class Person
person1 = Person("John", 25)
[Link]() # Output: Hello, my name is John and I am 25 years old.
Explanation:
• [Link] accesses the name attribute.
• [Link]() calls the greet method to print the greeting message.
✅ Task 3:
Create a class Employee with attributes name, id, and salary. Write a method
display_details() to print employee details. Create an object and print the details.
Encapsulation (Data Hiding)
Encapsulation restricts direct access to an object's data. It is achieved using private
variables (prefixing variables with __).
Encapsulation is one of the fundamental principles of Object-Oriented Programming
(OOP). It is the concept of bundling data (attributes) and methods (functions) that operate
on the data into a single unit called a class. It also restricts direct access to some of the
object's components, which is a way of preventing unintended interference and misuse of
the data.
In simple terms, encapsulation is about protecting data inside a class and providing
controlled access to it using methods. This is achieved by:
• Making attributes private or protected.
• Using public methods (getters and setters) to access and update the private
attributes.
Key Points about Encapsulation:
1. Private Attributes: Attributes that cannot be accessed directly outside the class.
2. Public Methods: Methods that allow controlled access to private attributes.
3. Getters and Setters: Methods that allow access and modification of private
attributes.
1️⃣ How to Implement Encapsulation in Python?
Using Public and Private Attributes:
• Public attributes are those that can be accessed from outside the class.
• Private attributes are those that cannot be accessed directly from outside the class.
These are typically declared using a double underscore prefix (__).
Syntax:
• Public attribute: self.attribute_name
• Private attribute: self.__attribute_name
Example of Encapsulation in Python:
class Person:
def __init__(self, name, age):
[Link] = name # Public attribute
self.__age = age # Private attribute
# Getter for private attribute __age
def get_age(self):
return self.__age
# Setter for private attribute __age
def set_age(self, age):
if age > 0:
self.__age = age
else:
print("Invalid age")
# Creating an object of the Person class
person1 = Person("John", 25)
# Accessing the public attribute
print([Link]) # Output: John
# Accessing the private attribute using getter method
print(person1.get_age()) # Output: 25
# Modifying the private attribute using setter method
person1.set_age(30)
print(person1.get_age()) # Output: 30
# Trying to access the private attribute directly (will give an error)
# print(person1.__age) # Error: AttributeError: 'Person' object has no attribute '__age'
Explanation:
• Public attribute name can be accessed directly.
• Private attribute __age is accessed and modified using getter and setter methods.
• Direct access to __age from outside the class is not allowed, protecting the data.
Example:
class BankAccount:
def __init__(self, balance):
self.__balance = balance # Private variable
Types of Encapsulation
There are three types of attributes in Python that represent different levels of
encapsulation:
1. Public Attributes: These attributes can be accessed from outside the class.
o Syntax: self.attribute_name
2. Protected Attributes: These attributes should not be accessed directly from
outside the class, but it is allowed to access them in subclasses. They are declared
with a single underscore (_).
o Syntax: self._attribute_name
3. Private Attributes: These attributes cannot be accessed directly from outside the
class. They are declared with a double underscore (__).
o Syntax: self.__attribute_name
Example:
class Animal:
def __init__(self, name, type_):
[Link] = name # Public
self._type = type_ # Protected
self.__species = "Mammal" # Private
def display(self):
print(f"Name: {[Link]}, Type: {self._type}, Species: {self.__species}")
# Creating an object
animal = Animal("Lion", "Wild")
# Accessing public attribute
print([Link]) # Output: Lion
# Accessing protected attribute (should be avoided)
print(animal._type) # Output: Wild
# Accessing private attribute directly (will raise an error)
# print(animal.__species) # AttributeError: 'Animal' object has no attribute '__species'
def deposit(self, amount):
self.__balance += amount
def get_balance(self):
return self.__balance
# Creating an object
account = BankAccount(1000)
[Link](500)
print(account.get_balance()) # Output: 1500
✅ Task 2:
Create a class Employee with a private attribute salary. Provide methods to set and
get the salary.
What is Inheritance?
Inheritance is a key concept in Object-Oriented Programming (OOP) where one class
(child class) inherits the attributes and methods of another class (parent class). It allows
you to reuse code, create a hierarchical class structure, and implement shared behavior.
Why Use Inheritance?
• Code Reusability: You can reuse the attributes and methods of the parent class
without rewriting them.
• Extensibility: Child classes can extend or modify the functionality of the parent
class.
• Hierarchical Structure: It helps in creating a hierarchical organization of classes.
Key Points of Inheritance:
1. Parent (Base) Class: The class whose properties and methods are inherited by
other classes.
2. Child (Derived) Class: The class that inherits the properties and methods of the
parent class.
3. Method Overriding: A child class can provide a specific implementation of a
method that is already defined in the parent class.
4. Super Keyword: Allows a child class to call methods or access properties from the
parent class.
1️⃣ Syntax of Inheritance in Python
The syntax for defining inheritance in Python is simple. You define a child class and
specify the parent class in parentheses.
class ParentClass:
# Parent class code
pass
class ChildClass(ParentClass):
# Child class code
Pass
Example:
# Parent class
class Animal:
def __init__(self, name):
[Link] = name
def speak(self):
print(f"{[Link]} makes a sound")
# Child class inherits from Animal
class Dog(Animal):
def speak(self):
print(f"{[Link]} barks")
# Creating an object of the Dog class (child)
dog = Dog("Buddy")
[Link]() # Output: Buddy barks
2️⃣ Types of Inheritance
Python supports multiple types of inheritance. These include:
1. Single Inheritance
In single inheritance, a child class inherits from one parent class.
class Parent:
def display(self):
print("Parent class method")
class Child(Parent):
pass
# Creating an object of Child class
child = Child()
[Link]() # Output: Parent class method
Multiple Inheritance
In multiple inheritance, a child class inherits from more than one parent class.
class Father:
def father_name(self):
print("Father's name is John")
class Mother:
def mother_name(self):
print("Mother's name is Sarah")
# Child class inherits from both Father and Mother
class Child(Father, Mother):
pass
# Creating an object of the Child class
child = Child()
child.father_name() # Output: Father's name is John
child.mother_name() # Output: Mother's name is Sarah
Multilevel Inheritance
In multilevel inheritance, a class is derived from another derived class.
class Grandparent:
def grandparent_method(self):
print("This is the grandparent method")
class Parent(Grandparent):
def parent_method(self):
print("This is the parent method")
class Child(Parent):
def child_method(self):
print("This is the child method")
# Creating an object of the Child class
child = Child()
child.grandparent_method() # Output: This is the grandparent method
child.parent_method() # Output: This is the parent method
child.child_method() # Output: This is the child method
Hierarchical Inheritance
In hierarchical inheritance, one parent class has multiple child classes.
class Animal:
def speak(self):
print("Animal makes a sound")
class Dog(Animal):
def speak(self):
print("Dog barks")
class Cat(Animal):
def speak(self):
print("Cat meows")
# Creating objects of the Dog and Cat classes
dog = Dog()
[Link]() # Output: Dog barks
cat = Cat()
[Link]() # Output: Cat meows
Hybrid Inheritance
Hybrid inheritance is a combination of two or more types of inheritance. It is more
complex and can lead to issues like the diamond problem.
class A:
def method_A(self):
print("Method A")
class B(A):
def method_B(self):
print("Method B")
class C(A):
def method_C(self):
print("Method C")
class D(B, C):
def method_D(self):
print("Method D")
# Creating an object of class D
d = D()
d.method_A() # Output: Method A
d.method_B() # Output: Method B
d.method_C() # Output: Method C
d.method_D() # Output: Method D
Method Overriding
Method overriding occurs when a child class provides a specific implementation of a
method that is already defined in the parent class. This allows the child class to modify or
extend the behavior of the inherited method.
Example of Method Overriding:
class Vehicle:
def start_engine(self):
print("Vehicle engine starts")
class Car(Vehicle):
def start_engine(self): # Overriding the parent class method
print("Car engine starts")
class Bike(Vehicle):
def start_engine(self): # Overriding the parent class method
print("Bike engine starts")
# Creating objects
car = Car()
car.start_engine() # Output: Car engine starts
bike = Bike()
bike.start_engine() # Output: Bike engine starts
The super() Function
The super() function is used to call methods from a parent class. It is useful when you
want to extend or modify the behavior of a parent method while still using it.
Example with super():
class Animal:
def __init__(self, name):
[Link] = name
def speak(self):
print(f"{[Link]} makes a sound")
class Dog(Animal):
def __init__(self, name, breed):
super().__init__(name) # Calling parent class constructor
[Link] = breed
def speak(self):
super().speak() # Calling parent class method
print(f"{[Link]} barks")
# Creating an object of Dog
dog = Dog("Buddy", "Golden Retriever")
[Link]() # Output: Buddy makes a sound
# Buddy barks
Polymorphism in Python
1. What is Polymorphism?
The term Polymorphism is derived from Greek words poly (many) and morphs (forms).
It allows different classes to use the same interface, making code more flexible and
reusable.
Why is Polymorphism Important?
• Code Reusability: We can define methods in a generic way and use them in
multiple places.
• Flexibility and Scalability: New classes can be introduced without modifying
existing code.
• Supports Object-Oriented Programming (OOP) Principles: It enhances
inheritance and encapsulation by allowing objects to interact more naturally.
Definition
Method overriding occurs when a subclass provides a specific implementation of a
method already defined in its superclass.
Key Points:
• The method in the child class must have the same name and parameters as the
method in the parent class.
• The child class method overrides the parent class method when called from an
instance of the child class.
• It allows for dynamic method dispatch, meaning the method that gets called is
determined at runtime.
class Animal:
def make_sound(self):
print("Animal makes a sound")
class Dog(Animal):
def make_sound(self): # Overriding method
print("Dog barks")
class Cat(Animal):
def make_sound(self): # Overriding method
print("Cat meows")
# Creating objects
animals = [Dog(), Cat()]
for animal in animals:
animal.make_sound() # Calls the overridden method
Task 1: Implement Method Overriding
Create a Vehicle class with a fuel_type() method. Then create Car and Bike classes
that override the fuel_type() method.
Task 2: Implement Operator Overloading
Create a Time class where you can add two time durations using the + operator. (Hint:
Overload the __add__ method.)
Task 3: Implement Method Overloading
Create a class Greet with a method say_hello() that can accept one or two arguments
(e.g., say_hello("John") and say_hello("John", "Doe")).
Method Overloading (Compile-Time Polymorphism)
Definition
Method overloading refers to defining multiple methods with the same name but different
parameters. However, Python does not support method overloading directly as
languages like Java or C++ do.
Workarounds in Python
Python achieves a similar effect using:
1. Default arguments: Providing default values for parameters.
2. Variable-length arguments (*args, **kwargs).
Example 1: Using Default Arguments
class MathOperations:
def add(self, a, b, c=0): # Default argument
return a + b + c
math_op = MathOperations()
print(math_op.add(5, 10)) # Output: 15
print(math_op.add(5, 10, 20)) # Output: 35
Example 2: Using Variable-Length Arguments (*args)
class MathOperations:
def add(self, *args): # Accepts multiple arguments
return sum(args)
math_op = MathOperations()
print(math_op.add(5, 10)) # Output: 15
print(math_op.add(5, 10, 20, 30)) # Output: 65
1. Introduction to Encapsulation
Encapsulation is one of the fundamental concepts of Object-Oriented Programming
(OOP). It is the practice of bundling data (variables) and methods (functions) that
operate on the data into a single unit (class) and restricting direct access to some of
the object's components.
Why is Encapsulation Important?
• Data Protection: Prevents accidental modification of important data.
• Code Maintainability: Hides unnecessary implementation details.
• Improved Security: Restricts access to certain methods or variables.
• Encourages Abstraction: Allows a clear separation between how an object works
and how it's used.
2. Encapsulation in Python
Python achieves encapsulation through:
1. Public Members: Accessible from anywhere.
2. Protected Members: Indicated by a single underscore _var. It’s a convention, not
enforced.
3. Private Members: Indicated by a double underscore __var. Not directly accessible
outside the class.
3. Public Members (No Encapsulation)
A public attribute or method is accessible from anywhere.
class Car:
def __init__(self, brand, speed):
[Link] = brand # Public variable
[Link] = speed # Public variable
def show_details(self): # Public method
print(f"Car Brand: {[Link]}, Speed: {[Link]} km/h")
# Creating an object
car = Car("Toyota", 180)
car.show_details()
# Accessing attributes directly
print([Link]) # Output: Toyota
print([Link]) # Output: 180
Protected Members (_var)
A protected attribute is indicated with a single underscore (_var). It’s a convention that
suggests it should not be accessed directly but is not strictly enforced.
Example of Protected Members
class Car:
def __init__(self, brand, speed):
self._brand = brand # Protected variable
self._speed = speed # Protected variable
def show_details(self):
print(f"Car Brand: {self._brand}, Speed: {self._speed} km/h")
class SportsCar(Car):
def boost_speed(self):
self._speed += 50 # Can access _speed because it's protected
print(f"Boosted Speed: {self._speed} km/h")
# Creating an object
car = SportsCar("Ferrari", 200)
car.show_details()
car.boost_speed()
# Accessing protected variable (possible but not recommended)
print(car._speed) # Output: 250
Key Points:
• Can be accessed within the class and subclasses.
• Not strictly private, so it can still be modified from outside (not recommended).
Private Members (__var)
A private attribute is indicated with double underscores (__var). These cannot be
accessed directly from outside the class.
Example of Private Members
class BankAccount:
def __init__(self, account_number, balance):
self.__account_number = account_number # Private variable
self.__balance = balance # Private variable
def deposit(self, amount):
if amount > 0:
self.__balance += amount
print(f"Deposited: ${amount}, New Balance: ${self.__balance}")
else:
print("Invalid deposit amount")
def get_balance(self):
return self.__balance # Accessing private variable through a method
# Creating an object
account = BankAccount("12345678", 1000)
[Link](500)
# Accessing private members (Will cause an error)
# print(account.__balance) # AttributeError: 'BankAccount' object has no attribute
'__balance'
# Correct way to access private data
print(account.get_balance()) # Output: 1500
Key Points:
• Cannot be accessed directly (account.__balance gives an error).
• Can only be accessed via methods inside the class.
Getter and Setter Methods
Since private attributes cannot be accessed directly, getter and setter methods are used
to retrieve and modify private data.
Example of Getters and Setters
class BankAccount:
def __init__(self, account_number, balance):
self.__account_number = account_number # Private variable
self.__balance = balance # Private variable
def get_balance(self): # Getter
return self.__balance
def set_balance(self, amount): # Setter
if amount >= 0:
self.__balance = amount
else:
print("Invalid balance amount")
# Using getters and setters
account = BankAccount("12345678", 1000)
print(account.get_balance()) # Output: 1000
account.set_balance(2000) # Modifies balance
print(account.get_balance()) # Output: 2000
account.set_balance(-500) # Invalid balance amount
Advantages of Getters and Setters:
• Controlled access to private attributes.
• Validation checks before modifying attributes.
Introduction to Abstraction
Abstraction is one of the fundamental principles of Object-Oriented Programming
(OOP). It is the process of hiding implementation details from the user and only
exposing the essential features.
Why is Abstraction Important?
• Hides Complex Implementation: Users interact with simple interfaces instead of
dealing with complex code.
• Enhances Code Maintainability: Changes in implementation do not affect external
code.
• Improves Security: Prevents direct access to sensitive data.
• Encourages Modularity: Helps break a program into manageable sections.
2. Abstraction in Python
Python supports abstraction using abstract classes and abstract methods through the
abc (Abstract Base Class) module.
Key Concepts:
1. Abstract Class
o A class that cannot be instantiated directly.
o Contains abstract methods (methods that must be implemented by
subclasses).
2. Abstract Method
o Declared in an abstract class but does not have an implementation.
o Subclasses must override abstract methods.
3. Implementing Abstraction in Python
Using the abc Module
Python provides the abc (Abstract Base Class) module to enforce abstraction.
Example: Abstract Class and Abstract Method
from abc import ABC, abstractmethod # Importing Abstract Base Class module
class Vehicle(ABC): # Abstract Class
@abstractmethod
def start(self): # Abstract Method
pass # No implementation in the base class
class Car(Vehicle): # Subclass
def start(self): # Implementing abstract method
print("Car starts with a key")
class Bike(Vehicle): # Another subclass
def start(self):
print("Bike starts with a button")
# Creating objects
car = Car()
[Link]() # Output: Car starts with a key
bike = Bike()
[Link]() # Output: Bike starts with a button
# vehicle = Vehicle() # This will cause an error (Cannot instantiate abstract class)
Explanation:
• Vehicle is an abstract class with an abstract method start().
• Car and Bike are concrete subclasses that implement the start() method.
• Vehicle cannot be instantiated.
Real-World Example: Bank System
Example: Abstract Class for a Bank
from abc import ABC, abstractmethod
class Bank(ABC): # Abstract Class
@abstractmethod
def loan_interest(self):
pass
class HDFCBank(Bank): # Subclass
def loan_interest(self):
print("HDFC Bank Loan Interest: 7.5%")
class ICICIBank(Bank): # Subclass
def loan_interest(self):
print("ICICI Bank Loan Interest: 8.2%")
# Creating objects
hdfc = HDFCBank()
hdfc.loan_interest() # Output: HDFC Bank Loan Interest: 7.5%
icici = ICICIBank()
icici.loan_interest() # Output: ICICI Bank Loan Interest: 8.2%
1. Introduction to Exception Handling
Exception handling in Python allows a program to gracefully handle runtime errors
instead of crashing. It uses the try-except block to catch and handle errors.
What is an Exception?
An exception is an error that occurs during program execution, stopping normal flow.
Common Types of Exceptions in Python
Exception Description
ZeroDivisionError Occurs when dividing by zero (10 / 0)
Occurs when performing operations on incompatible types ("5" +
TypeError
3)
ValueError Occurs when passing an invalid value (int("abc"))
FileNotFoundError Occurs when trying to open a non-existent file
IndexError Occurs when accessing an index out of range in a list
KeyError Occurs when accessing a missing dictionary key
NameError Occurs when using an undefined variable
2. Using try-except for Exception Handling
The try-except block is used to handle exceptions.
Basic Syntax
try:
# Code that may cause an exception
except ExceptionType:
# Code to handle the exception.
Example: Handling Division by Zero.
try:
result = 10 / 0 # This will cause ZeroDivisionError
except ZeroDivisionError:
print("Error: Cannot divide by zero.")
Handling Multiple Exceptions
You can handle multiple exceptions using multiple except blocks.
Example: Handling Different Exceptions
try:
x = int("abc") # This will cause ValueError
y = 10 / 0 # This will cause ZeroDivisionError
except ValueError:
print("Error: Invalid value. Please enter a number.")
except ZeroDivisionError:
print("Error: Cannot divide by zero.")
Using except Exception to Catch All Errors
If you are unsure about the type of exception, use except Exception:.
Example: Catching Any Exception
try:
print(10 / 0) # ZeroDivisionError
except Exception as e:
print(f"An error occurred: {e}")
Using else Block
The else block runs only if no exception occurs.
Example: else Block Usage
try:
num = int(input("Enter a number: "))
print(f"You entered: {num}")
except ValueError:
print("Invalid input! Please enter a number.")
else:
print("No errors occurred.")
Using finally Block
The finally block runs regardless of whether an exception occurs or not. It is useful
for cleanup operations (e.g., closing files or database connections).
Example: finally Block Usage
try:
file = open("[Link]", "r")
print([Link]())
except FileNotFoundError:
print("File not found!")
finally:
print("Closing file...")
[Link]() # Will run even if an exception occurs.
Practice Tasks
Task 1: Handle Division Error
• Write a program that asks the user to enter two numbers.
• Handle division by zero using try-except.
Task 2: File Handling with Exception
• Open a file and read its contents.
• If the file is not found, display "File not found!".
Task 3: Create a Custom Exception
• Create a BankAccount class.
• Raise an exception if withdrawal amount is more than the balance.
1. Introduction to File Handling
File handling in Python allows us to read, write, and manipulate files stored on a
computer. It is useful for storing data permanently, processing large data, and
automating tasks.
Python provides built-in functions to work with files, mainly using the open() function.
2. Opening a File in Python
Python uses the open() function to open a file.
Syntax:
file = open("filename", "mode")
Opening a File in Python
Python uses the open() function to open a file.
Syntax:
file = open("filename", "mode")
• "filename": The name of the file (with extension).
• "mode": The operation to be performed (read, write, append, etc.).
File Modes in Python
Mode Description
"r" Read mode (default), opens file for reading, error if file doesn't exist.
"w" Write mode, creates a new file if not exists or overwrites existing file.
"a" Append mode, creates file if not exists and appends new data.
"x" Exclusive creation mode, fails if file already exists.
"rb" Read binary mode (for non-text files like images, videos).
"wb" Write binary mode.
"ab" Append binary mode.
Reading a File
To read a file, use r mode.
Example: Read Entire File
file = open("[Link]", "r") # Open file in read mode
content = [Link]() # Read full content
print(content)
[Link]() # Close the file
Example: Read First 10 Characters
file = open("[Link]", "r")
print([Link](10)) # Reads only first 10 characters
[Link]()
Example: Read Line by Line
file = open("[Link]", "r")
print([Link]()) # Reads first line
print([Link]()) # Reads second line
[Link]()
Example: Read All Lines into a List
file = open("[Link]", "r")
lines = [Link]() # Returns list of all lines
print(lines)
[Link]()
Writing to a File
To write data to a file, use w mode (overwrites existing content).
Example: Write to a File
file = open("[Link]", "w") # Open file in write mode
[Link]("Hello, this is a new file.\n")
[Link]("Python file handling example.")
[Link]()
Writing Multiple Lines
file = open("[Link]", "w")
lines = ["First Line\n", "Second Line\n", "Third Line\n"]
[Link](lines) # Writes multiple lines at once
[Link]()
Appending to a File
To add new content to an existing file, use a mode.
Example: Append to a File
file = open("[Link]", "a") # Open file in append mode
[Link]("\nThis is an appended line.")
[Link]()
Using with Statement (Best Practice)
Using with automatically closes the file after use, preventing resource leaks.
Example: Read Using with
with open("[Link]", "r") as file:
content = [Link]()
print(content) # No need to manually close file
Example: Write Using with
with open("[Link]", "w") as file:
[Link]("This is a safer way to write files!")