Python
Python
Token
In Python, a token is the smallest meaningful unit of code. Just like words make up
sentences, tokens come together to form Python statements and instructions. These
tokens can be categorized into different types, each serving a specific purpose:
Keywords: These are reserved words with special meanings in Python.You cannot
use them for variable names or other purposes. Examples include:
+ (Addition) It is used to add two operands. For example, if a = 10, b = 10 => a+b = 20
- (Subtraction) It is used to subtract the second operand from the first operand. If the first operand is less than
the second operand, the value results negative. For example, if a = 20, b = 5 => a - b = 15
/ (divide) It returns the quotient after dividing the first operand by the second operand. For example, if a =
20, b = 10 => a/b = 2.0
* (Multiplication) It is used to multiply one operand with the other. For example, if a = 20, b = 4 => a * b = 80
% (reminder) It returns the reminder after dividing the first operand by the second operand. For example, if a
= 20, b = 10 => a%b = 0
** (Exponent) As it calculates the first operand's power to the second operand, it is an exponent operator.
// (Floor division) It provides the quotient's floor value, which is obtained by dividing the two operands.
Comparison operator
Comparison operators mainly use for comparison purposes. Comparison operators compare the values of
the two operands and return a true or false Boolean value in accordance.
Operator Description
== If the value of two operands is equal, then the condition becomes true.
!= If the value of two operands is not equal, then the condition becomes true.
<= The condition is met if the first operand is smaller than or equal to the second operand.
>= The condition is met if the first operand is greater than or equal to the second operand.
> If the first operand is greater than the second operand, then the condition becomes true.
< If the first operand is less than the second operand, then the condition becomes true.
Assignment Operators
Using the assignment operators, the right expression's value is assigned to the left operand.
Operator Description
+= By multiplying the value of the right operand by the value of the left operand, the left operand receives a changed
value. For example, if a = 10, b = 20 => a+ = b will be equal to a = a+ b and therefore, a = 30.
-= It decreases the value of the left operand by the value of the right operand and assigns the modified value back to left
operand. For example, if a = 20, b = 10 => a- = b will be equal to a = a- b and therefore, a = 10.
*= It multiplies the value of the left operand by the value of the right operand and assigns the modified value back to then
the left operand. For example, if a = 10, b = 20 => a* = b will be equal to a = a* b and therefore, a = 200.
%= It divides the value of the left operand by the value of the right operand and assigns the reminder back to the left
operand. For example, if a = 20, b = 10 => a % = b will be equal to a = a % b and therefore, a = 0.
**= a**=b will be equal to a=a**b, for example, if a = 4, b =2, a**=b will assign 4**2 = 16 to a.
//= A//=b will be equal to a = a// b, for example, if a = 4, b = 3, a//=b will assign 4//3 = 1 to a.
Bitwise Operators
The two operands' values are processed bit by bit by the bitwise operators. The examples of Bitwise
operators are bitwise OR (|), bitwise AND (&), bitwise XOR (^), negation (~), Left shift (<<), and Right
shift (>>).
Operator Description
& (binary and) A 1 is copied to the result if both bits in two operands at the same location are 1. If not, 0 is
copied.
| (binary or) The resulting bit will be 0 if both the bits are zero; otherwise, the resulting bit will be 1.
^ (binary xor) If the two bits are different, the outcome bit will be 1, else it will be 0.
~ (negation) The operand's bits are calculated as their negations, so if one bit is 0, the next bit will be 1, and
vice versa.
<< (left shift) The number of bits in the right operand is multiplied by the leftward shift of the value of the left
operand.
>> (right shift) The left operand is moved right by the number of bits present in the right operand.
Logical Operators
The assessment of expressions to make decisions typically uses logical operators. The examples of logical
operators are and, or, and not. In the case of logical AND, if the first one is 0, it does not depend upon the
second one. In the case of logical OR, if the first one is 1, it does not depend on the second one.
Operator Description
and The condition will also be true if the expression is true. If the two expressions a and
b are the same, then a and b must both be true.
or The condition will be true if one of the phrases is true. If a and b are the two
expressions, then an or b must be true if and is true and b is false.
not If an expression a is true, then not (a) will be false and vice versa.
Membership Operators
The membership of a value inside a Python data structure can be verified using Python
membership operators. The result is true if the value is in the data structure; otherwise, it returns
false.
Operator Description
not in If the first operand is not present in the second operand, the evaluation is true
(list, tuple, or dictionary).
Identity Operators:
It is used to check reference variable pointing same or different object in
memory location.
Operator Description
user_name = "Alice"
account_balance = 1000.50
Avoiding Name Errors When Using Variables
Common Name Errors (Case Sensitivity, Reserved Keywords)
Case Sensitivity: As Python is case-sensitive, referencing a variable with the wrong case can
lead to NameError.
userAge = 25
print(userage) # NameError: name 'userage' is not defined
Reserved Keywords: Using Python's reserved keywords as variable names will result in a
SyntaxError.
Example:
if = 5 # SyntaxError: invalid syntax
variable_name = "value"
def my_function():
pass
class MyClass:
pass
MAX_RETRIES = 5
1. Input Statement
The input() function is used to take input from the user. It reads a line from
input, converts it into a string, and returns it.
name = input("Enter your name: ")
print(f"Hello, {name}!")
input("Enter your name: ") prompts the user to enter their name.
The entered value is stored in the name variable.
The print() statement then outputs a greeting.
Output Statement
The print() function is used to display output on the screen.
Basic Syntax:
print(object(s), sep=' ', end='\n', file=sys.stdout, flush=False)
import pytest
# Step 1: Write the test (initially will fail)
def test_is_even():
assert is_even(2) == True
assert is_even(3) == False
assert is_even(0) == True
# Step 3: Write the code
def is_even(n):
return n % 2 == 0
# Running the tests
if __name__ == "__main__":
pytest.main()
c. Integration Testing
Purpose: Integration tests check how different modules or components of your
application work together.
Tool: You can use unittest or more advanced tools like pytest for integration testing.
d. pytest
Usage: pytest is a popular testing framework that simplifies writing small tests and
scales to support complex functional testing.
Features: It has more advanced features like fixtures, parameterized testing, and
powerful assertions.
def add(a, b):
return a + b
def test_add():
assert add(2, 3) == 5
assert add(-1, 1) == 0
assert add(0, 0) == 0
# To run, simply execute `pytest` in the terminal
e. Continuous Integration (CI)
Purpose: CI tools automatically run your tests whenever changes are made to the
codebase.
Tools: Popular CI services like Travis CI, Jenkins, or GitHub Actions can be
integrated with your project to ensure that your tests are always run and the
codebase is stable.
#WAP in python to print first 20 natural numbers.
#WAP in python to print first 10 even numbers.
Introduction
Conditional statements (if, else, and elif) are fundamental programming
constructs that allow you to control the flow of your program based on
conditions that you specify.
They provide a way to make decisions in your program and execute different
code based on those decisions.
The main ones are if/else for making choices, loops like for/while for
repeating tasks, and keywords like break/continue to control the flow.
1. if Statement:
The `if` statement executes a block of code only if a specified condition is
true. If the condition evaluates to false, the code block is not executed. It has
the following
syntax:
if condition:
# statement to be executed if the condition is true
Example:
age = 10
if age >= 18:
print("You are an adult")
Write a program in python to check you are eligible for
voting .
Write a program in python to check your name is matched .
Write a program in python show message meow meow if
you enter Cat or CAT or cat.
Write a program in python to find factorial of input number.
2. if…else Statement:
The `if…else` statement allows you to execute the instructions if one block of
code condition is true, and another block runs when if the condition is false.
syntax:
if condition:
# statement to be executed if condition is true
else:
# statement to be executed if condition is false
Eg: name = "Alice"
if name == "Bob":
print("Hello Bob")
else:
print("Hello", name)
Write a program in python to a=int(input("Enter any number:"))
check you are eligible for voting or Is_perfect_Square=False
not . for i in range(1,a):
Write a program in python to if i==math.sqrt(a):
check your name is matched or not
Is_perfect_Square=True
Write a program in python show
message meow meow if you enter break
Cat or CAT or cat and show if Is_perfect_Square:
message Vau Vau for other case. print(f"{a} is perfect square")
Write a program in python to else:
check input number is perfect print(f"{a} is not perfect square")
square or not.
3. if…elif…else Statement: else:
The `if…elif…else` statement # code to be executed if all
allows you to check multiple
conditions and execute different conditions are false
blocks of code based on which Eg: score = 75
condition is true. if score >= 90:
syntax: print("Excellent!")
if condition1: elif score >= 80:
# code to be executed if condition1 print("Great job!")
is true else:
print("Keep practicing!")
elif condition2:
# code to be executed if condition2
is true
Write a program in python to print largest number among
three numbers.
Write a program in python to enter five subject marks and
calculate percentage, division and result.
Write a program in python to calculate Grade if you enter
Grade point.
Write a program in python to smallest number among three
numbers.
Write a program in python to check positive and negative
number or zero.
4. Nested if Statement: Example:
A nested `if` statement is an `if` age = int(input("Enter your age: "))
statement that is placed inside another citizen = input("Are you a citizen?
`if` statement. It allows you to check for (yes/no): ")
additional conditions based on the if age >= 18:
result of the outer `if` statement.
if citizen == "yes":
syntax:
print("You are eligible to vote.")
if condition1:
else:
if condition2:
print("You are not eligible to vote
# code to be executed if both because you are not a citizen.")
condition1 and condition2 are true
else:
print("You are not eligible to vote
because you are under 18.")
Match- Case option = int(input("Enter an
In Python, starting with version option (1, 2, or 3): "))
3.10, the match-case statement match option:
was introduced, providing a case 1:
structured way to handle print("You selected option 1.")
multiple conditions, similar to
case 2:
the switch-case construct found
in other programming print("You selected option 2.")
languages. case 3:
print("You selected option 3.")
case _:
print("Invalid option.")
Unit -4
Control Statements
Introduction
Control statements are like instructions that tell Python how to navigate through the code. They
help in making decisions and looping over tasks.
Control statements in Python are used to control the flow of execution in a program based on
certain conditions.
Loops are employed in Python to iterate over a section of code continually.
Control statements are designed to serve the purpose of modifying a loop's execution from its
default behaviour.
Based on a condition, control statements are applied to alter how the loop executes.
The if/else for making choices, loops like for/while for repeating tasks, and keywords like
break/continue to control the flow.
Looping Statement :
In Python, Looping are vital structures that enable the repetition of code execution,
either for a specific count or until a certain condition is fulfilled.
1. for loop:
Used to iterate over a sequence of elements, like lists, strings, tuples, or dictionaries.
Executes a block of code for each element in the sequence.
Syntax:
for element in sequence:
# code to execute for each element
Example:
for a in range(11):
print(a)
Write a program in python using for loop to print alphabets of word
“PYTHON”.
Write a program to count numbers of vowel in input string.
2. while loop:
Executes a block of code repeatedly as long as a specified condition is true.
Well-suited for situations where you don't know the exact number of iterations
beforehand.
Syntax:
while condition:
# code to execute as long as the condition is true
Example:
count = 0
while count < 5:
print(count)
count += 1
Write a program in python using while loop to print multiplication
table of input number.
Write a program in python to find reverse number of input number.
Write a program in python to check input number is palindrome or
not.
Assignment
Write a program in python to find reverse number of input string.
Write a program in python to check input string is palindrome or
not.
Write a program in python to check input number is Armstrong or
not?
Unconditional Statements: Continue Statement:
In Python, there exist three kinds of control The continue statement skips the rest of the code
statements: Break, Continue, and Pass. inside the loop for the current iteration and proceeds
to the next iteration of the loop.
These are control flow statements in Python that
allow you to modify the behaviour of loops and Example:
conditional statements. for i in range(10):
Break Statement: if i == 5:
The break statement in Python is used to exit a loop continue
i.e. it immediately terminates the loop when it is print(i)
encountered. This can be useful when you want to
stop the loop's execution based on a certain
condition.
Example:
for i in range(10):
if i == 5:
break
print(i)
Pass Statement:
The pass statement is a null operation; nothing happens when it is
executed. It is used as a placeholder when a statement is syntactically
required but you have no need for any code to execute.
Example:
for i in range(5):
if i == 3:
pass
else:
print(i)
1. Write a Python program that iterates through numbers 1 to 10. If a number is
divisible by 3, skip the rest of the loop's code using the continue statement. Stop the
loop entirely if a number is greater than or equal to 8 using the break statement.
2. Write a Python program that iterates through numbers from 1 to 10. If a number is
less than 6, print it. If a number equals 7, use the break statement to exit the loop.
Use the pass statement for numbers greater than 7 and print "Skipped" for those
numbers.
3. Write a Python program that uses a while loop to count from 1 to 20. If the current
count is divisible by 4, use the continue statement to skip the rest of the loop body
and move to the next iteration. Print the count value on each iteration.
1. for num in range(1, 11): elif num > 7:
if num % 3 == 0: print("Skipped“)
continue ………………………..
if num >= 8: 3. count = 1
break while count <= 20:
print(num) if count % 4 == 0:
………………………. continue
2. for num in range(1, 11): count += 1
if num < 6: print(count)
print(num) count += 1
elif num == 7:
break
Using if else as ternary:
The ternary operator in Python is a compact way of writing an if-else
statement. It’s used when you want to return two different values
based on the truth value of a condition.
Syntax:
value_if_true if condition else value_if_false
Example:
x = 10
y = 20
result = "x is greater" if x > y else "y is greater“
Print (result)
The else clause after a for or while loop:
In Python, the else clause after a for or while loop is an optional construct that provides a
way to execute a block of code after the loop completes normally, i.e., without
encountering a break statement.
for loops:
The else block will execute after the loop iterates over all the items in the iterable or
sequence.
# Syntax for 'for' loop with 'else' clause
for item in iterable:
# Code block inside the loop
else:
# Code block inside the loop
# Example with for loop
for i in range(5):
print(i)
else:
print("Loop completed successfully")
While loops:
The else block will execute after the loop exits normally (when the condition becomes false)
without encountering a break statement.
# Syntax for 'while' loop with 'else' clause
while condition:
# Code block inside the loop
else:
# Code block to execute after the loop completes
Example:
x=0
while x < 5:
print(x)
x += 1
else:
print("Loop completed successfully")
1. Write a program using a for loop to calculate the sum of the first 20 natural numbers.
2. Write a program that prints numbers from 10 down to 1 using a for loop.
3. Write a program that finds the sum of all even numbers between 1 and 50 using a for
loop.
4. Write a program that iterates through a list of numbers and prints the square of each
number using a for-in loop.
5. Write a program that iterates through a list of words and finds the longest word using a
for-in loop.
6. Write a program that checks if a particular element exists in a list using a for-in loop.
7. Write a program that iterates through a list of strings and concatenates them into a
single string using a for-in loop.
numbers = [1, 2, 3, 4, 5] if item == search_item:
for num in numbers: found = True
print(f"Square of {num} is {num ** 2}") break
----------------------------------- if found:
words = ["apple", "banana", "cherry", print("Item found!")
"watermelon"] else:
longest = "" print("Item not found.")
for word in words: -----------------------------------------------
if len(word) > len(longest): strings = ["Hello", "world", "Python", "is",
longest = word "great"]
print("The longest word is:", longest) result = ""
----------------------------------------- for s in strings:
items = [10, 20, 30, 40, 50] result += s + " "
search_item = int(input("Enter the item to print("Concatenated string:", result)
search: "))
found = False
for item in items:
Write a program that uses nested loops to print a pyramid pattern of stars.
Write a program that uses nested loops to print an inverted right triangle of numbers.
Write a program that prints multiplication tables for numbers 1 to 5 using nested loops.
Write a program that asks the user to enter a password and breaks the loop if the correct
password is entered.
While a program to print the following pattern.
1
12
123
1234
12345
rows = 5 else:
for i in range(1, rows + 1): print("Incorrect password, try again.")
print(' ' * (rows - i) + '*' * (2 * i - 1)) -----------------------------------------------------------
-------------------------------------------
rows = 5
for i in range(rows, 0, -1):
for j in range(1, i + 1):
print(j, end=" ")
print()
---------------------
correct_password = "secret"
while True:
password = input("Enter the password: ")
if password == correct_password:
print("Access granted")
break
While a program to print the following pattern.
1
22
333
4444
55555
While a program to print the following pattern.
*
**
***
****
*****
list1 = [12, 14, 16, 39, 40] list1 = [100, 200, 300, 400, 500]
# iterating print(600 in list1)
for i in list1: print(700 in list1)
print(i) print(1040 in list1)
print(300 in list1)
print(100 in list1)
print(500 in list1)
Adding Elements to the List
The append() function in Python can add a new item to the List.
my_list = []
my_list.append(1)
my_list.append(2)
my_list.append(3)
print(my_list)
Removing Elements from the List
The remove() function in Python can remove an element from the List.
list = [0,1,2,3,4]
print("printing original list: ");
for i in list:
print(i,end=" ")
list.remove(2)
print("\nprinting the list after the removal of first element...“,list)
popped_element = list.pop(3) #Remove value at position 3 from the list
del list[0] #Delete element at position 0 or first position.
for i in list:
print(i,end=" ")
Updating List Values
Due to their mutability and the slice and assignment operator's ability to update their values, lists are
Python's most adaptable data structure.
Python's append() and insert() methods can also add values to a list.
list = [1, 2, 3, 4, 5, 6]
print(list)
list[2] = 10
print(list)
# Adding multiple-element
list[1:3] = [89, 78]
print(list)
# It will add value at the end of the list
list[-1] = 25
print(list)
Python List Built-in Functions Max( )
Python provides the following built-in It returns the maximum element of the list
functions, which can be used with the lists. # maximum of the list
len() list1 = [103, 675, 321, 782, 200]
max() # large element in the list
min() print(max(list1))
len( ) Min( )
It is used to calculate the length of the list. It returns the minimum element of the list
# size of the list # minimum of the list
list1 = [12, 16, 18, 20, 39, 40] list1 = [103, 675, 321, 782, 200]
# finding length of the list # smallest element in the list
len(list1) print(min(list1))
sort() Method
In Python, you can sort a list permanently using the sort() method.
This modifies the list in place, meaning the original list is sorted and the changes are permanent.
Syntax:
list.sort(reverse=False)
Example1:
my_list = [3, 1, 4, 1, 5, 9]
my_list.sort()
print("List after sorting in ascending order:", my_list)
Example 2:
my_list = [3, 1, 4, 1, 5, 9]
# Sort the list in descending order
my_list.sort(reverse=True)
print("List after sorting in descending order:", my_list)
sorted() Function
The sorted() function in Python Example1:
allows you to sort a list temporarily, my_list = [3, 1, 4, 1, 5, 9]
meaning it returns a new sorted list but # Sort the list temporarily in ascending order
does not modify the original list. sorted_list = sorted(my_list)
This is useful when you want to keep print("Original list:", my_list)
the original list unchanged while still print("Temporarily sorted list:", sorted_list)
getting a sorted version of it.
Syntax: Example2:
my_list = [3, 1, 4, 1, 5, 9]
sorted(iterable, reverse=False)
sorted_list_desc = sorted(my_list, reverse=True)
print("Original list:", my_list)
print("Temporarily sorted list in descending order:",
sorted_list_desc)
List in Reverse Order
In Python, you can print a list in reverse order in several ways, depending on whether
you want to reverse the list temporarily or permanently.
# Permanently reverse the list
my_list = [1, 2, 3, 4, 5]
my_list.reverse()
print("List after permanent reversal:", my_list)
Python Fix List Index Out of Range using Try Except Block
If we expect that an index might be out of range, we can use a try-except block to handle the error
gracefully.
my_list = [1, 2, 3]
try:
print(my_list[3])
except IndexError:
print("Index is out of range")
Using the range() Function
The range() function in Python generates a sequence of numbers, but it doesn’t directly
produce a list.
To create a list of numbers from a range, you can pass the result of range() to the list() function.
Syntax:
range(start, stop, step)
Example 1:
# Create a list of numbers from 0 to 9
numbers = list(range(10))
print(numbers)
Example 2:
numbers = list(range(0, 10, 2))
print(numbers)
Indexing and Slicing:
Indexing
In Python, a list is an ordered collection of elements, and indexing refers to accessing
elements based on their position in the list.
Python uses zero-based indexing, meaning the first element is at index 0, the second
element is at index 1, and so on.
We can access element in a list in Two ways :
Accessing element by Positive Index Number
Accessing element by Negative Index Number
1. Accessing element by Positive Index Number
In this type of Indexing, we pass a Positive index(which we want to access)
in square brackets.
The index number starts from index number 0 (which denotes the first
element of a list).
list = [1,2,5,6,8,9,10,15]
print(list[0])
print(list[6])
2. Accessing element by Negative Index Number
In this type of Indexing, we pass the Negative index(which we want to access) in square
brackets.
Here the index number starts from index number -1 (which denotes the last element of
a list).
list = [1,2,5,6,8,9,10,15]
print(list[-1])
print(list[-5])
Slicing
Slicing in Python lists allows you to access a subsection (or "slice") of a list by specifying a range of
indices.
The general syntax for slicing is:
list[start : stop: step]
Where:
start (optional): The index at which the slice starts (inclusive).
stop: The index at which the slice stops (exclusive).
step (optional): The interval between elements in the slice.
Example 2:
fruits = ['apple', 'banana', 'cherry']
# Extend the list with characters from a string
fruits.extend('date')
print(fruits)
Questions For Practice:
1. Write a program that takes a list of numbers and finds both the largest and the smallest
elements in the list.
2. Given a list with potential duplicate values, write a program to remove the duplicates
while preserving the original order of the elements.
3. Write a program that checks if a given list is a palindrome (i.e., it reads the same
backward as forward).
4. Write a program to count how many even and odd numbers are in a list of integers.
5. Write a program to reverse a list and print the reversed list.
6. Write a program that calculates and prints the average of all the numbers in a list.
7. Write a program that asks the user for a number and checks if the number exists in a
predefined list.
Example 1: Example 2:
numbers = [3, 8, 2, 7, 4] numbers = [1, 2, 3, 2, 4, 1, 5]
largest = numbers[0] result = []
smallest = numbers[0] seen = set()
for num in numbers:
if num > largest: for num in numbers:
largest = num if num not in seen:
if num < smallest: result.append(num)
smallest = num seen.add(num)
print(f"Largest: {largest}, Smallest: {smallest}")
print("List without duplicates:", result)
Example 3 Example 4
numbers = [1, 2, 3, 2, 1] numbers = [1, 2, 3, 4, 5, 6]
is_palindrome = True even_count = 0
for i in range(len(numbers) // 2): odd_count = 0
if numbers[i] != numbers[-i-1]: for num in numbers:
is_palindrome = False if num % 2 == 0:
break even_count += 1
if is_palindrome: else:
print("The list is a palindrome") odd_count += 1
else: print(f"Even numbers: {even_count}, Odd
print("The list is not a palindrome") numbers: {odd_count}")
# Program to reverse a list and print #Program that asks the user for a
the reversed list: number and checks if the number
my_list = [1, 2, 3, 4, 5] exists in a predefined list:
# Using slicing to reverse the list predefined_list = [5, 10, 15, 20, 25]
reversed_list = my_list[::-1] user_input = int(input("Enter a number: "))
print("Original List:", my_list) if user_input in predefined_list:
print("Reversed List:", reversed_list) print(f"{user_input} exists in the list.")
#Program that calculates and prints the else:
average of all the numbers in a list: print(f"{user_input} does not exist in the list.")
numbers = [10, 20, 30, 40, 50]
average = sum(numbers) / len(numbers)
print("List of Numbers:", numbers)
print("Average of Numbers:", average)
9. Write a program to insert an element into a list at a specific index provided by the
user.
10. Write a program to remove a specific element from a list. The element to be removed
should be provided by the user.
11. Write a program that takes a list of numbers and prints the list sorted in ascending
order without using any built-in sort function.
12. Write a program that prints all elements in a list that are greater than a number
specified by the user.
13. Write a program to concatenate two lists and print the result.
14. Write a program to multiply every element in a list by a number (constant) provided
by the user.
Tuple
A tuple is a collection in Python that is ordered and immutable (i.e., once defined, you cannot
change its elements).
Tuples are similar to lists, but they use parentheses () instead of square brackets [].
Tuple packing
packed_tuple = (1, "apple", 3.14)
Tuple unpacking
a, b, c = packed_tuple
print(a, b, c)
Tuple Operations: 2. Slicing
Tuples in Python support various operations, You can extract a sub-part of a tuple using the
even though they are immutable. These slicing operation.
operations allow you to manipulate or query my_tuple = (1, 2, 3, 4, 5, 6)
tuples without modifying their structure slice_tuple = my_tuple[1:4]
1. Indexing print(slice_tuple)
You can access individual elements of a tuple 3. Concatenation:You can concatenate tuples
using their index. using the + operator.
my_tuple = (10, 20, 30, 40) new_tuple = my_tuple + (4, 5)
print(my_tuple[0]) print(new_tuple) # Output: (1, 2, 3, 4, 5)
print(my_tuple[-1]) 4. Repetition:You can repeat a tuple using the *
operator.
repeated_tuple = my_tuple * 2
print(repeated_tuple) # Output: (1, 2, 3, 1, 2, 3)
5. Membership (in, not in) my_tuple = (1, 2, 3, 4)
You can check if an item exists in a tuple using print(max(my_tuple)) # Output: 4
the in and not in operators. print(min(my_tuple)) # Output: 1
my_tuple = (1, 2, 3, 4) 8. Sum (sum())
print(2 in my_tuple) You can calculate the sum of all numeric
print(5 not in my_tuple) elements in a tuple using the sum() function.
6. Length (len()) my_tuple = (1, 2, 3, 4)
You can get the number of elements in a tuple print(sum(my_tuple))
using the len() function. 9. Nested Tuples
my_tuple = (1, 2, 3, 4) Tuples can contain other tuples as elements,
print(len(my_tuple)) # Output: 4 which is known as nesting.
7. Max (max()) and Min (min()) nested_tuple = (1, 2, (3, 4, 5), 6)
You can find the maximum and minimum values print(nested_tuple[2])
in a tuple of comparable elements (like numbers print(nested_tuple[2][1])
or strings).
10. Conversion (tuple())
You can convert other iterables like lists or strings into tuples using the tuple() function.
my_list = [1, 2, 3]
my_tuple = tuple(my_list)
print(my_tuple) # Output: (1, 2, 3)
my_string = "hello"
string_tuple = tuple(my_string)
print(string_tuple) # Output: ('h', 'e', 'l', 'l', 'o')
Tuple Methods: 2. index()
Tuples in Python have only two built-in The index() method returns the index of the
methods, as they are immutable and cannot be first occurrence of a specified value. If the
modified after creation. Here are the two value is not found, it raises a ValueError.
methods available for tuples: tuple.index(value)
1. count() Example:
The count() method returns the number of my_tuple = (1, 2, 3, 4, 5)
times a specified value appears in the tuple. index_of_three = my_tuple.index(3)
tuple.count(value) print(index_of_three) # Output: 2
Example:
my_t = (1, 2, 3, 2, 4, 2)
count_of_twos = my_t.count(2)
print(count_of_twos)
Unit-6
Dictionaries
Dictionaries are useful data structure for storing data in Python because they are capable of
imitating real-world data arrangements where a certain value exists for a given key.
The data is stored as key-value pairs using a Python dictionary.
This data structure is mutable
The components of dictionary were made using keys and values.
Keys must only have one component.
Values can be of any type, including integer, list, and tuple.
A dictionary is, in other words, a group of key-value pairs, where the values can be any Python
object. The keys, in contrast, are immutable Python objects, such as strings, tuples, or numbers.
Creating the Dictionary Example:
Curly brackets are the simplest way to Employee = {"Name": "Johnny", "Age": 32, "salar
generate a Python dictionary, although there y":26000,"Company":“BIT"}
are other approaches as well. print(type(Employee))
With many key-value pairs surrounded in print("printing Employee data .... ")
curly brackets and a colon separating each print(Employee)
key from its value, the dictionary can be
built. (:).
Syntax:
Dict = {"Name":“Ram", "Age": 25}
In the above dictionary Dict,The
keys Name and Age are the strings which comes
under the category of an immutable object.
Example 2:
# Creating an empty Dictionary # Creating a Dictionary with each item as a Pair
Dict = {}
print("Empty Dictionary: ") Dict = dict([(4, 'Rinku'), (2, Singh)])
print(Dict) print("\nDictionary with each item as a pair: "
)
# Creating a Dictionary with dict() method print(Dict)
Dict = dict({1: 'Hcl', 2: 'WIPRO', 3:'Facebook'}
print("\nCreate Dictionary by using dict()
: ")
print(Dict)
Accessing the dictionary values
To access data contained in lists and tuples, indexing has been studied.
The keys of the dictionary can be used to obtain the values because they are unique from one
another.
Example:
Employee = {"Name": "Dev", "Age": 20, "salary":45000,"Company":"WIPRO"}
print(type(Employee))
print("printing Employee data .... ")
print("Name : %s" %Employee["Name"])
print("Age : %d" %Employee["Age"])
print("Salary : %d" %Employee["salary"])
print("Company : %s" %Employee["Company"])
Adding Dictionary Values print("\nDictionary after adding 3 elements: ")
The dictionary is a mutable data type, and
utilising the right keys allows you to change its print(Dict)
values. # Adding set of values with a single Key
Dict[key] = value and the value can both be Dict['Emp_ages'] = 20, 33, 24
modified. An existing value can also be updated print("\nDictionary after adding 3 elements: ")
using the update() method.
Example:
print(Dict)
# Creating an empty Dictionary # Updating existing Key'sValue
Dict = {} Dict[3] = 'JavaTpoint'
print("Empty Dictionary: ")
print("\nUpdated key value: ")
print(Dict) print(Dict)
# Adding elements to dictionary one at a time
Dict[0] = ‘Pabitra'
Dict[2] = 'John'
Dict[3] = 'Rocky'
Example 2:
Employee = {"Name": "Dev", "Age": 20, "salary":45000,"Company":"WIPRO"}
print(type(Employee))
print("printing Employee data .... ")
print(Employee)
print("Enter the details of the new employee....");
Employee["Name"] = input("Name: ");
Employee["Age"] = int(input("Age: "));
Employee["salary"] = int(input("Salary: "));
Employee["Company"] = input("Company:");
print("printing the new data");
print(Employee)
Deleting Elements using del Keyword
The items of the dictionary can be deleted by using the del keyword as given below.
Example:
Employee = {"Name": "David", "Age": 30, "salary":55000,"Company":"WIPRO"}
print(type(Employee))
print("printing Employee data .... ")
print(Employee)
print("Deleting some of the employee data")
del Employee["Name"]
del Employee["Company"]
print("printing the modified information ")
print(Employee)
print("Deleting the dictionary: Employee");
del Employee
print("Lets try to print it again ");
print(Employee)
Deleting Elements using pop() Method
A dictionary is a group of key-value pairs in Python.You can retrieve, insert, and remove
items using this unordered, mutable data type by using their keys.
The pop() method is one of the ways to get rid of elements from a dictionary.
# Creating a Dictionary
Dict1 = {1: 'JavaTpoint', 2: 'Educational', 3: 'Website'}
# Deleting a key
# using pop() method
pop_key = Dict1.pop(2)
print(Dict1)
Iterating Dictionary: #for loop to print all the values of the dictionary
A dictionary can be iterated using for loop as Employee = {"Name": "John", "Age": 29, "salary"
given below :25000,"Company":"PRO"} for x in Employee:
Example:
# for loop to print all the keys of a dictionary print(Employee[x])
Employee = {"Name": "John", "Age": 29, "salary"
:25000,"Company":"PRO"} #for loop to print the items of the dictionary by usi
for x in Employee: ng items() method
print(x) Employee = {"Name": "John", "Age": 29, "salary"
:25000,"Company":"PRO"}
for x in Employee.items():
print(x)
Properties of Dictionary: Dynamic Size
Unordered Dictionaries are dynamic and can grow or shrink in size as
items are added or removed.
Dictionaries are unordered collections, meaning that the
order of items is not guaranteed. This means that items are Nested Dictionaries
not stored in the order you define them. Dictionaries can contain other dictionaries as values,
Mutable allowing you to create nested structures for complex data.
Dictionaries are mutable, which means you can add, remove, employees = {
or change key-value pairs after the dictionary has been "Employee1": {"Name": "Dev", "Age": 20},
created. "Employee2": {"Name": "Alex", "Age": 25}
Key-value pairs }
Dictionaries store data in key-value pairs, where each key is
unique within the dictionary. Keys are used as identifiers to
access values. No Duplicate Keys, but duplicate values allowed
Unique keys While each key must be unique, dictionaries allow duplicate
values.
Each key in a dictionary must be unique. If a duplicate key is
added, the last value assigned to that key will overwrite any Keys and values can be of different types
previous values. Both keys and values in a dictionary can be of any data type,
Efficient Data Retrieval and different pairs in the same dictionary can have different
types.
Dictionaries are implemented using hash tables, making data
retrieval by key very fast on average, regardless of the
dictionary’s size.
Built-in Dictionary Functions:
A function is a method that can be used on a construct to yield a value. Additionally, the construct is
unaltered. A few of the Python methods can be combined with a Python dictionary.
The built-in Python dictionary methods are listed below, along with a brief description.
len()
The dictionary's length is returned via the len() function in Python. The string is lengthened by one for
each key-value pair.
dict = {1:“Ram", 2:“Shyam", 3:“Sita", 4: "Bhim"}
len(dict)
any()
It is a built-in function that returns True if at least one element in an iterable is truthy; otherwise, it
returns False..
dict = {1: "Ayan", 2: "Bunny", 3: "Ram", 4: "Bheem"}
result=any({'':'','':'','3':''})
print(result)
all() sorting has no effect on the original Python
The all() function in Python is used to dictionary.
check if all elements in an iterable are dict = {7: "Ayan", 5: "Bunny", 8: "Ram", 1:
truthy. Unlike in any() method, all() only "Bheem"}
returns True if each of the dictionary's keys result = sorted(dict)
contain a True Boolean value. print(result) # Output: [1, 5, 7, 8]
dict = {1: "Ayan", 2: "Bunny", 3: "Ram", 4: #To print values
"Bheem"}
dict = {7: "Ayan", 5: "Bunny", 8: "Ram", 1:
result=all({1: '', 2: '', '': ''}) "Bheem"}
print(result) result = sorted(dict.values())
sorted() print(result) # Output: ['Ayan', 'Bheem', 'Bunny',
Like it does with lists and tuples, the 'Ram']
sorted() method returns an ordered series
of the dictionary's keys. The ascending
Built-in Dictionary methods Example:
Python has a set of built-in methods that # dictionary methods
you can use on dictionaries. The built-in dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook",
python dictionary methods along with 4: "Amazon", 5: "Flipkart"}
the description and Code as: # clear() method
clear() dict.clear()
The clear() method in Python is used
print(dict)
to remove all items from a dictionary,
effectively making it an empty
dictionary.
Syntax:
dict.clear()
copy()
The copy() method in Python is used to create a shallow copy of a dictionary.
A shallow copy means that the method creates a new dictionary with the same key-value pairs as
the original dictionary.
However, if the values in the dictionary are mutable objects (e.g., lists or other dictionaries),
changes to those objects will affect both the original and the copied dictionary.
Syntax:
new_dict = original_dict.copy()
# dictionary methods
dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}
# copy() method
dict_demo = dict.copy()
print(dict_demo)
pop()
The pop() method in Python is used to remove a key-value pair from a dictionary. It
returns the value associated with the specified key and removes that key-value pair from the
dictionary.
# dictionary methods
dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}
# pop() method
dict_demo = dict.copy()
x = dict_demo.pop(1)
print(x)
popitem() keys()
removes the most recent key-value It returns all the keys of the
pair entered dictionary.
# dictionary methods # dictionary methods
dict = {1: "Hcl", 2: "WIPRO", 3: "F dict = {1: "Hcl", 2: "WIPRO", 3: "Faceb
acebook", 4: "Amazon", 5: "Flipkar ook", 4: "Amazon", 5: "Flipkart"}
t“} # keys() method
# popitem() method print(dict.keys())
dict_demo.popitem()
print(dict_demo)
items() get()
It returns all the key-value pairs as a It is used to get the value specified
tuple. for the passed key.
# dictionary methods # dictionary methods
dict = {1: "Hcl", 2: "WIPRO", 3: "Faceb dict = {1: "Hcl", 2: "WIPRO", 3: "Faceb
ook", 4: "Amazon", 5: "Flipkart"} ook", 4: "Amazon", 5: "Flipkart"}
# items() method # get() method
print(dict_demo.items()) print(dict_demo.get(3))
update()
It mainly updates all the dictionary by adding the key-value pair of dict2 to this
dictionary.
# dictionary methods
dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}
# update() method
dict_demo.update({ 3: "TCS"})
print(dict_demo)
Nested Dictionary
A dictionary can contains dictionaries, this is called nested dictionaries.
Student={ “name”: “Ram Kumar”,
“Subjects”:{ “DBMS”=65, “Python”=75, “Probability”=54, “Discrete” =88} }
#Access data of DBMS
Print(Student[“Subjects”] [“DBMS”])
Print(list(Student.values())) #Print values in list
Pairs=list(Students.items())
Print(Pairs[0]) # print items
Write a Python script to merge two Python dictionaries.
# Create the first dictionary 'd1' with key-value pairs.
d1 = {'a': 100, 'b': 200}
# Create the second dictionary 'd2' with key-value pairs.
d2 = {'x': 300, 'y': 200}
# Create a new dictionary 'd' and initialize it as a copy of 'd1'.
d = d1.copy()
# Update the dictionary 'd' by adding key-value pairs from 'd2'.
d.update(d2)
# Print the dictionary 'd' after combining the key-value pairs from 'd1' and 'd2.
print(d)
Write a Python program to sum all the items in a dictionary.
# Create a dictionary 'my_dict' with key-value pairs.
my_dict = {'data1': 100, 'data2': -54, 'data3': 247}
# Use the 'sum' function to calculate the sum of all values in the 'my_dict' dictionary.
# 'my_dict.values()' extracts the values from the dictionary, and 'sum' calculates their sum.
result = sum(my_dict.values())
# Print the result, which is the sum of the values.
print(result)
Write a Python program to remove a key from a dictionary.
# Create a dictionary 'myDict' with key-value pairs.
myDict = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
# Print the original dictionary 'myDict'.
print(myDict)
# Check if the key 'a' exists in the 'myDict' dictionary.
if 'a' in myDict:
# If 'a' is in the dictionary, delete the key-value pair with the key 'a'.
del myDict['a']
# Print the updated dictionary 'myDict' after deleting the key 'a' (if it existed).
print(myDict)
Write a Python program to sort a given dictionary by key
# Create a dictionary 'color_dict' with color names as keys and their corresponding color codes in
hexadecimal format as values.
color_dict = {
'red': '#FF0000',
'green': '#008000',
'black': '#000000',
'white': '#FFFFFF'
}
for key in sorted(color_dict):
print("%s: %s" % (key, color_dict[key]))
Write a Python program to print a dictionary in table format.
my_dict = {'C1': [1, 2, 3], 'C2': [5, 6, 7], 'C3': [9, 10, 11]}
for row in zip(*([key] + (value) for key, value in sorted(my_dict.items()))):
print(*row)
Unit-7
Functions
In Python, a function is a block of code that performs a specific task.
It's a reusable piece of code that can be called from anywhere in your
program.
This promotes modularity, readability, and efficiency in your code.
Defining a Function
﴿ To define a function, you use the def keyword followed by the function name
and parentheses:
def function_name():
# Function body
Example: Parameters
def greet(name): They are placeholders for values that
#This function greets the person passed as a will be passed to the function when it's
parameter. called.
return f"Hello, {name}!" Within the function, they represent the
# Calling the function values that are passed in.
print(greet("Manisha")) Used to specify the type and number of
inputs a function expects.
In Python, information can be passed to
a function through arguments. The Arguments
function receives this information in its They are the actual values that are
parameters and can process or utilize assigned to the parameters.
it within its body. Provide the data that the function will
process.
Example:
def greet(name, age): # name and age are parameters
print("Hello,", name, "!You are", age, "years old.")
greet("Alice", 30) # "Alice" and 30 are arguments
def get_person_details():
name = input("Enter your name: ")
Returning a Tuples Returning a Lists
The most common way to return multiple We can also return multiple values in a list.
values is by using tuples. When you return def get_numbers():
multiple values separated by commas, n = int(input("Enter how many numbers you
Python packs them into a tuple. want to input: "))
def get_coordinates(): numbers = []
x = float(input("Enter X coordinate: ")) for _ in range(n):
y = float(input("EnterY coordinate: ")) number = int(input("Enter a number: "))
z = float(input("Enter Z coordinate: ")) numbers.append(number)
return (x, y, z) return numbers
coordinates = get_coordinates() numbers = get_numbers()
print("Coordinates as a tuple:", coordinates) print("List of numbers:", numbers)
Passing a List to a Function Example:
Lists are mutable, meaning they can be def modify_list(my_list):
changed in place. When you pass a list to a my_list.append(4)
function, the function receives a reference to my_list = [1, 2, 3]
the same list, allowing it to modify the
original list. modify_list(my_list)
In Python, lists are mutable objects, meaning
print(my_list) # Output: [1, 2, 3, 4]
they can be modified in-place. Example:
When you pass a list to a function, you're def print_items(items):
actually passing a reference to the same list for item in items:
object. print(item)
This means any modifications made to the list fruits = ["apple", "banana", "cherry"]
inside the function will be reflected in the print_items(fruits)
original list outside the function.
Modifying a List in a Function Preventing a Function from
Since lists are mutable, any changes made to a Modifying a List
list inside a function will affect the original list. If you want to prevent a function from
The append() operation modifies the original modifying the original list, you can create a
list. copy of the list before passing it to the function.
def add_item(items, new_item): This way, the function will work on a copy of
the list, leaving the original list unchanged.
items.append(new_item)
Using the copy() method
shopping_list = ["milk", "eggs"]
def modify_list(my_list):
add_item(shopping_list, "bread")
my_list.append(4)
print(shopping_list)
my_list = [1, 2, 3]
# Output: ['milk', 'eggs', 'bread']
new_list = my_list.copy()
modify_list(new_list)
print(my_list) # Output: [1, 2, 3]
print(new_list) # Output: [1, 2, 3, 4]
Using the [:] slice
def modify_list(my_list):
my_list.append(4)
my_list = [1, 2, 3]
new_list = my_list[:]
modify_list(new_list)
print(my_list) # Output: [1, 2, 3]
print(new_list) # Output: [1, 2, 3, 4]
Storing Functions in Modules in Example (math_operations.py):
Python def add(a, b):
Storing functions in modules allows you return a + b
to organize your code, improve def subtract(a, b):
reusability, and make large programs return a - b
more manageable.
def multiply(a, b):
A module is simply a Python file (.py)
return a * b
that contains definitions like functions,
classes, and variables. def divide(a, b):
Steps to Store Functions in a Module if b != 0:
Create a Python Module: return a / b
A module is just a file with a .py else:
extension. return "Division by zero is not allowed!"
Define your functions in the module.
Use the Module in Another Script: Benefits of Storing Functions in Modules
You can import the module into any other Reusability:
Python script and use its functions. Functions stored in a module can be reused
across multiple programs.
Example (main.py):
Organization:
import math_operations
Keeping functions in separate modules makes
print(math_operations.add(5, 3)) # Output: 8 your codebase easier to read and manage.
print(math_operations.subtract(5, 3)) # Output: 2 Encapsulation:
print(math_operations.multiply(5, 3)) # Output: Related functions can be grouped into specific
15 modules for better structure.
# def __display_balance(self):
print("Balance:", self.__balance)
b = BankAccount(1234567890, 5000)
# b.__display_balance()
Protected Access Modifier: print("Name:", self._name)
Class properties and methods with protected print("Age:", self._age)
access modifier can be accessed within the class Student(Person):
class and from the class that inherits the def __init__(self, name, age, roll_number):
protected class.
super().__init__(name, age)
In python, protected members and methods
self._roll_number = roll_number
are declared using single underscore(‘_’) as
prefix before their names. def display(self):
Example: self._display()
class Person: print("Roll Number:", self._roll_number)
def __init__(self, name, age): s = Student("John", 20, 123)
self._name = name s.display()
self._age = age
def _display(self):
Abstract Class:
An abstract class in Python is a class that cannot be instantiated on its own and is
typically used to define a common interface for its subclasses.
Abstract classes can include one or more abstract methods, which are methods
declared in the abstract class that must be implemented by any non-abstract subclass.
To create an abstract class in Python, you use the abc (Abstract Base Class) module.
Here's how you can define and use an abstract class:
Import the abc module: You need to import the ABC class and the abstractmethod
decorator from the abc module.
Define an abstract class: Create a class that inherits from ABC.
Define abstract methods: Use the @abstractmethod decorator to declare methods
that must be implemented in any subclass.
from abc import ABC,abstractmethod print("Mobile app is secured")
class BankApp(ABC): class WebApp(BankApp):
def Database(self): def Login_web(self):
print("Database successfully print("Sucessfully login")
created.") def Security(self):
@abstractmethod print("Web app is secured")
def Security(self): m=MoblieApp()
pass m.Mobile_login()
class MoblieApp(BankApp): w=WebApp()
def Mobile_login(self): w.Login_web()
print("Login to mobile app
successfully")
def Security(self):
Operator Overloading:
Operator overloading in Python allows you to define or change the behavior of operators (+, -, *, etc.)
for user-defined classes. This is done by defining special methods in your class that Python will call when
those operators are used.
Example:
class Point: p1 = Point(1, 2)
def __init__(self, x, y): p2 = Point(3, 4)
self.x = x
p3 = p1 + p2
self.y = y
def __add__(self, other): print(p3) # Output: Point(4, 6)
return Point(self.x + other.x, self.y + other.y) p4 = p1 - p2
def __sub__(self, other): print(p4) # Output: Point(-2, -2)
return Point(self.x - other.x, self.y - other.y) p5 = p1 * 3
def __mul__(self, scalar):
print(p5) # Output: Point(3, 6)
return Point(self.x * scalar, self.y * scalar)
def __eq__(self, other): print(p1 == p2) # Output: False
return self.x == other.x and self.y == other.y print(p1 == Point(1, 2)) # Output:
def __str__(self): True
return f"Point({self.x}, {self.y})"
Magic Methods: __sub__(self, other): Subtraction (-).
Magic methods in Python, also known as __mul__(self, other): Multiplication (*).
dunder (double underscore) methods, are __truediv__(self, other): True division (/).
special methods with double underscores at the __floordiv__(self, other): Floor division (//).
beginning and end of their names. These
methods allow you to define the behavior of __mod__(self, other): Modulus (%).
your objects for built-in operations like __pow__(self, other): Exponentiation (**).
arithmetic, comparison, string representation, __eq__(self, other): Equality (==).
and more. __ne__(self, other): Inequality (!=).
__init__(self, ...): Object initializer __lt__(self, other): Less than (<).
(constructor).
__le__(self, other): Less than or equal to
__repr__(self): Official string representation (<=).
of the object.
__gt__(self, other): Greater than (>).
__str__(self): Informal string representation
__ge__(self, other): Greater than or equal to
of the object.
(>=).
__add__(self, other): Addition (+).
__getattr__(self, name): Called when an attribute is not found.
__setattr__(self, name, value): Called when setting an attribute.
__delattr__(self, name): Called when deleting an attribute.
__len__(self): Called by len().
__getitem__(self, key): Called to get an item.
__setitem__(self, key, value): Called to set an item.
__delitem__(self, key): Called to delete an item.
__iter__(self): Called to get an iterator.
__enter__(self): Called when entering a with statement.
__exit__(self, exc_type, exc_value, traceback): Called when exiting a with statement.
Exception Handling: inside the finally block.
Exception handling in Python is a mechanism for Example:
responding to and managing errors or other try:
exceptional conditions that arise during the x = int(input("Enter a number: "))
execution of a program. Python uses try, except,
else, and finally blocks to handle exceptions result = 10 / x
gracefully. exceptValueError:
Basic Structure print("Invalid input. Please enter a valid number.")
try block: The code that might raise an exception except ZeroDivisionError:
is placed inside the try block. print("Division by zero is not allowed.")
except block: The code that handles the exception else:
is placed inside the except block. print(f"Result: {result}")
else block: The code that runs if no exception is finally:
raised is placed inside the else block.
print("Execution complete.")
finally block: The code that runs no matter what
(whether an exception is raised or not) is placed
Common types of Exceptions:
AttributeError: Raised when an attribute reference or assignment fails.
ImportError: Raised when an import statement fails to find the module definition or when a
from ... import fails.
IndexError: Raised when a sequence subscript is out of range.
KeyError: Raised when a dictionary key is not found.
NameError: Raised when a local or global name is not found.
TypeError: Raised when an operation or function is applied to an object of inappropriate type.
ZeroDivisionError: Raised when the second argument of a division or modulo operation is
zero.
Modules and Packages:
Modules:
The module is a simple Python file that contains collections of functions and global
variables and with having a .py extension file.
There are two types of modules in python.
Built in Modules : These modules are ready to import and use and ships with the
python interpreter. There is no need to install such modules explicitly.
External Modules: These modules are imported from a third party file or can be
installed using a package manager like pip or conda. Since this code is written by
someone else, we can install different versions of a same module with time.
Packages:
The package is a simple directory having collections of modules. This directory
contains Python modules and also having __init__.py file by which the interpreter
interprets it as a Package. The package is simply a namespace. The package also
contains sub-packages inside it.
Enumeration: class Color(Enum):
Enumeration, or enum, in Python is a way to RED = 1
define a set of named values. These values can GREEN = 2
represent a collection of constants and are BLUE = 3
useful for creating self-documenting code print(Color.RED)
with more readable and maintainable
print(Color.GREEN)
constants.
print(Color.BLUE)
Is a set of symbolic names(members) bound
to unique values. print(Color.RED.name)
The enum module, introduced in Python print(Color.RED.value)
3.4, provides a way to define and use for color in Color:
enumerations. print(color)
Example:
from enum import Enum
UNIT-9
FILE DIRECTORIES AND EXCEPTIONS
Files: File Handling:
Files are named locations on disk to store File handling is an essential aspect of
information. programming, allowing you to read from
They used to store data permanently. and write to files. Python provides built-in
functions and modules to make file
Data is stored in non-volatile memory.
handling easy and efficient.
We can retrieve data whenever required.
Python supports file handling and allows
There are two types of files: users to handle files i.e., to read and write
Text file : Store data in the form of files, along with many other file handling
characters. It is used to store data and options, to operate on files. The concept of
strings. file handling has stretched over various
Binary Files: Stores data in the form of other languages, but the implementation is
bytes. Eg. Audio, video, image, pdf etc. either complicated or lengthy, like other
concepts of Python, this concept here is also
easy and short.
Advantages of File Handling in Python:
Versatility: File handling in Python allows you to perform a wide range of
operations, such as creating, reading, writing, appending, renaming, and
deleting files.
Flexibility: File handling in Python is highly flexible, as it allows you to work
with different file types (e.g. text files, binary files, CSV files, etc.), and to
perform different operations on files (e.g. read, write, append, etc.).
User–friendly: Python provides a user-friendly interface for file handling,
making it easy to create, read, and manipulate files.
Cross-platform: Python file-handling functions work across different
platforms (e.g. Windows, Mac, Linux), allowing for seamless integration and
compatibility.
Disadvantages of File Handling in Python:
Error-prone: File handling operations in Python can be prone to errors, especially
if the code is not carefully written or if there are issues with the file system (e.g. file
permissions, file locks, etc.).
Security risks: File handling in Python can also pose security risks, especially if
the program accepts user input that can be used to access or modify sensitive files
on the system.
Complexity: File handling in Python can be complex, especially when working
with more advanced file formats or operations. Careful attention must be paid to the
code to ensure that files are handled properly and securely.
Performance: File handling operations in Python can be slower than other
programming languages, especially when dealing with large files or performing
complex operations.
Opening a file
Python provides inbuilt functions for creating, writing, and reading
files.
Opening a file refers to getting the file ready either for reading or for
writing. This can be done using the open() function.
This function returns a file object and takes two arguments, one that
accepts the file name and another that accepts the mode(Access Mode).
Syntax: File_object = open(“File_Name”, “Access_Mode”)
Access_Mode: Access modes govern the type of operations possible in the
opened file. The below table gives the list of all access mode available in
python
Operation Syntax Description
Read and Write r+ Open the file for reading and writing.
Open the file for reading and writing. Unlike “r+” is doesn’t
Write and Read w+
raise an I/O error if file doesn’t exist.
Open the file for writing and creates new file if it doesn’t
Append Only a exist. All additions are made at the end of the file and no
existing data can be modified.
Open the file for reading and writing and creates new file if it
Append and Read a+ doesn’t exist. All additions are made at the end of the file and
no existing data can be modified.
Example 1: Open and read a file using Python
The readlines() method read all the lines in one go and stored each line from the
text file as a single list item inside a list.
The readlines() method also added a newline character \n at the end of each line.
Read a Text File Using a for Loop in Python
An alternative way of reading a file line by line in Python is using
a for loop, which is the most Pythonic approach to reading a file.
import fileinput
for line in fileinput.input('large_file.txt'):
# Process the line
print(line.strip())
4. Memory Mapping:
For very large files, memory mapping can be more efficient.
It creates a memory map of the file, allowing you to access parts of the
file directly without reading the entire file into memory.
import mmap
with open('large_file.txt', 'r+b') as file:
mm = mmap.mmap(file.fileno(), 0)
# Process the memory map
print(mm[:10]) # Read the first 10 bytes
1. Renaming Files
To rename a file, use the os.rename() function.
Syntax:
os.rename(source, destination)
source: The current name/path of the file.
Example
import os
# Rename a file
old_name = "example.txt"
new_name = "renamed_example.txt"
os.rename(old_name, new_name)
print("File renamed successfully.")
2. Moving Files
To move a file, use the shutil.move() function from the shutil module.
Syntax:
shutil.move(source, destination)
source: The file path you want to move.
Example
import shutil
# Move a file
source = "renamed_example.txt"
destination = "new_folder/renamed_example.txt"
shutil.move(source, destination)
print("File moved successfully.")
3. Copying Files
To copy files, use the shutil.copy() or shutil.copy2() function.
shutil.copy() copies the file content and permissions.
Syntax:
shutil.copy(source, destination)
Example
import shutil
# Copy a file
source = "new_folder/renamed_example.txt"
destination = "copy_of_example.txt"
shutil.copy(source, destination)
print("File copied successfully.")
4. Removing Files
To delete (remove) a file, use the os.remove() function.
Syntax:
os.remove(file_path)
Example:
import os
# Remove a file
file_to_delete = "copy_of_example.txt"
os.remove(file_to_delete)
print("File removed successfully.")
Replace text in a file: # Python program to replace text in a
Replacing Text could be either file
erasing the entire content of the file with open("Sample.txt", "r+") as f:
and replacing it with new text or it f.truncate(0)
could mean modifying only specific s = input("Enter text to replace the
words or sentences within the existing contents:")
existing text.
f.write(s)
1. Removing all text and write new
print("Text successfully replaced")
text in the same file
In this method we replacing all the
text stored in the text file, for this, we
will open the file in reading and
writing mode and it will rewrite all
the text.
Using Replace function in for loop
The simple for loop is a conventional way to traverse through every line in
the given text file and find the line we want to replace. Then, the desired line
can be replaced by using the replace() function. Finally, the file is opened in
the write mode, and the replaced content is written in the given file.
with open("sample.txt","r") as f:
data=f.read()
x=input("Enter text you want to replace:")
y=input("Enter text you want to placed:")
new_data=data.replace(x,y)
print(new_data)
WAP using function that replace all occurrences of “java” with
“Python” in “sample.txt” file.
def replace():
with open("sample.txt","r") as f:
data=f.read()
x=input("Enter text you want to replace:")
y=input("Enter text you want to placed:")
new_data=data.replace(x,y)
print(new_data)
replace()
Searching text in file: with open("Sample.txt","r") as f:
word=input("Enter word to search:") while data:
with open("sample.txt","r") as f: data=f.readline()
data=f.read() if word in data:
if(data.find(word)!=-1): print(word ,"is found at
print("Found") line",line)
else: return
print("Not found") line +=1
#WAP find the the text you want return "Word is not found"
to search at which line. print(check_for_line())
def check_for_line():
word=input("Enter text you want
search:")
data=True
line=1
Error Handling in Python:
Exception handling in Python is a mechanism to handle runtime errors in a
program gracefully. Instead of terminating the program abruptly, Python allows
you to manage errors by catching and handling them using a structured
approach.
Error handling in Python is done using the try, except, else, and finally blocks.
This allows you to handle exceptions (errors) gracefully without crashing the
program.
Basic Syntax:
try:
# Code that might raise an exception
except ExceptionType:
# Code to handle the exception
else:
# Code that runs if no exception occurs (optional)
finally:
# Code that always runs (optional)
1. try and except Example:
The try block contains code that try:
might raise an exception. file = open(“sample_file.txt", "r")
The except block handles the error. except FileNotFoundError:
Example: print("Error: File not found.")
try:
x = 10 / 0 # This will raise a
ZeroDivisionError
except ZeroDivisionError:
print("Error: Cannot divide by zero.")
2. Catching Specific Exceptions
You can catch specific exceptions like
ZeroDivisionError,
FileNotFoundError, etc.
3. Catching Multiple Exceptions 4. Catching All Exceptions
You can handle multiple exception To catch any type of exception, use the
types in one try block. base Exception class.
try: try:
x = int("abc") # Raises ValueError x = 10 / 0
y = 10 / 0 # Raises except Exception as e: # Catches all
ZeroDivisionError exceptions
except ValueError: print(f"An error occurred: {e}")
print("Error: Invalid conversion to
integer.")
except ZeroDivisionError:
print("Error: Cannot divide by zero.")
5. else Block closing files.
The else block runs if no exceptions try:
occur. file = open("example.txt", "w")
try: file. write("Hello, World!")
x = 10 / 2 except Exception as e:
except ZeroDivisionError: print(f"Error: {e}")
print("Cannot divide by zero.") finally:
else: file.close()
print("Division successful:", x) print("File closed.")
6. finally Block
The finally block always executes,
regardless of whether an exception
occurs or not.
It's useful for cleanup tasks like
Exception Catching Multiple Exceptions
ArithmeticError try:
ZeroDivisionError my_list = [1, 2]
OverflowError
print(my_list[5]) # IndexError
ImportError x = 10 / 0 # ZeroDivisionError
IndexError
except (IndexError, ZeroDivisionError)
KeyError as e:
ValueError print("Caught an error:", e)
TypeError
FileNotFoundError
RuntimeError
Unit 10:
Machine Learning/Deep Learning Framework
Scikit-learn
Scikit-learn is a popular and powerful machine learning library in Python that
provides tools for developing, training, and evaluating machine learning models,
including classifiers.
It is built on foundational libraries such as NumPy, SciPy, and Matplotlib, making it
an essential toolkit for data scientists and machine learning practitioners.
Installation of Scikit- learn
The latest version of Scikit-learn is 1.1 and it requires Python 3.8 or newer.
Scikit-learn requires:
NumPy
SciPy as its dependencies.
Steps for Training and Evaluating .fit() method.
Classifiers Example: classifier.fit(X_train, y_train)
1. Dataset Preparation: 4. Evaluating the Classifier:
Use datasets from Scikit-learn’s built-in Predict on the test set using the .predict()
collection (e.g., Iris, digits) or import custom method.
datasets using libraries like Pandas. Use metrics like accuracy, precision, recall, F1-
Split the dataset into training and testing sets score, and confusion matrices to evaluate
using the train_test_split function. performance (from sklearn.metrics import
2. Choosing a Classifier: accuracy_score, classification_report).
Scikit-learn provides a variety of classifiers, 5. Cross-validation:
such as Logistic Regression, Support Vector Use cross-validation techniques
Machines (SVM), Decision Trees, and Random (cross_val_score) to validate the model across
Forests. multiple splits of the data.
Example: from sklearn.linear_model import
LogisticRegression
3. Training the Classifier:
Fit the model to the training data using the
Introduction to TensorFlow and Keras
What is TensorFlow?
TensorFlow is an open-source framework developed in late 2015 by Google for building
various machine learning and deep learning models. TensorFlow is free and open-source.
The main objective of using TensorFlow is to reduce the complexity of implementing
computations on large numerical data sets. In practice, these large computations can
manifest as training and inference with machine learning or deep learning models.
TensorFlow is an open-source, end-to-end machine learning framework developed by
Google.
It is widely used for building and deploying machine learning models, including deep
learning models like neural networks.
TensorFlow provides a flexible and efficient platform to perform computations and
manage large-scale machine learning tasks.
There are three main components to deploying models on mobile and IoT devices).
TensorFlow’s structure. Extensive Community Support:
preprocessing the data TensorFlow has an active community,
building the model comprehensive documentation, and a wealth of
tutorials and pre-built models.
training and estimating the model
Integration with Libraries:
Python is the most commonly used language It integrates well with Python's scientific
for machine learning and deep learning tasks. computing libraries (e.g., NumPy, Pandas),
TensorFlow's Python API provides a simple which simplifies data preprocessing and
and intuitive interface for building, training, analysis.
and deploying models. Flexibility:
Why Do We Use TensorFlow in Python? TensorFlow allows both low-level control (for
Ease of Use: custom operations) and high-level abstractions
TensorFlow has a Python-friendly syntax, (using Keras for fast prototyping).
making it easy for developers to build and train Production-Ready:
models. TensorFlow supports deployment in production
High Performance: environments, including web servers, mobile
TensorFlow is optimized for speed and can applications, and the cloud.
perform computations efficiently on CPUs,
GPUs, or TPUs.
Pre-built Tools:
TensorFlow includes tools like TensorBoard
(for visualization) and TensorFlow Lite (for
Example: Dense(10, activation='relu', input_shape=(X_train.shape[1],)), # Input layer
# Step 1: Import Libraries Dense(10, activation='relu'), # Hidden layer
from sklearn.datasets import load_iris Dense(3, activation='softmax') # Output layer for 3 classes
from sklearn.model_selection import train_test_split ])
from sklearn.preprocessing import OneHotEncoder
import tensorflow as tf # Step 5: Compile the Model
from tensorflow.keras.models import Sequential model.compile(optimizer='adam',
from tensorflow.keras.layers import Dense loss='categorical_crossentropy',
metrics=['accuracy'])
# Step 2: Load Dataset
iris = load_iris() # Step 6: Train the Model
X = iris.data # Features (sepal/petal length and width) model.fit(X_train, y_train, epochs=20, batch_size=8, verbose=1)
y = iris.target.reshape(-1, 1) # Labels (species)
# Step 7: Evaluate the Model
# Step 3: Preprocess Data loss, accuracy = model.evaluate(X_test, y_test, verbose=0)
# Convert labels to one-hot encoded format print(f"Test Accuracy: {accuracy:.2f}")
encoder = OneHotEncoder()
y = encoder.fit_transform(y).toarray() # Step 8: Make Predictions
predictions = model.predict(X_test)
# Split the dataset into training and testing sets print(f"Predictions (first 5):\n{predictions[:5]}")
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3,
random_state=42)