python final notes lw.docx
python final notes lw.docx
Teachers’ Manual
Python Programming(BCC 302/BCC402)
Prepared By:
Ankush Gupta
Mission of Institute
The mission of the institute is to educate young aspirants in various technical fields to fulfill
global requirements of human resources by providing sustainable quality education, training
and invigorating environment besides molding them into skilled competent and socially
responsible citizens who will lead the building of a powerful nation.
Course Outcome Statement
CO-PO Mapping:
CO-1 (Kx)
Introduction to Python: Python variables, Python basic Operators, Understanding python
blocks. Python Data Types, Declaring and using Numeric data types: int, float etc.
CO-2 (Kx)
Python Program Flow Control Conditional blocks: if, else and else if, Simple for loops in
python, For loop using ranges, string, list and dictionaries. Use of while loops in python,
Loop manipulation using pass, continue, break and else. Programming using Python
conditional and loop blocks.
CO-3 (Kx)
Python Complex data types: Using string data type and string operations, Defining list
and list slicing, Use of Tuple data type. String, List and Dictionary, Manipulations Building
blocks of python programs, string manipulation methods, List manipulation. Dictionary
manipulation, Programming using string, list and dictionary in-built functions. Python
Functions, Organizing python codes using functions.
CO-4 (Kx)
Python File Operations: Reading files, Writing files in python, Understanding read
functions, read(), readline(), readlines(). Understanding write functions, write() and
writelines() Manipulating file pointer using seek Programming, using file operations.
CO-5 (Kx)
Python packages: Simple programs using the built-in functions of packages matplotlib,
numpy, pandas etc. GUI Programming: Tkinter introduction, Tkinter and
Python Programming, Tk Widgets, Tkinter examples. Python programming with IDE.
Meerut Institute of Engineering & Technology, Meerut
Lesson Plan / Teaching Plan / Lecture Plan with Progress : B Tech - IV Semester : 2023-24
(Lectures)
Teacher Centric Approaches => TC-1 (Chalk and Talk); TC-2 (PPT); TC-3 (Video Lectures)
Learner (Student) Centric Approaches => LC-1 (Assignment); LC-2 (Mini Project); LC-3 (Quiz);
LC-4 (Seminar on recent trends); LC-5 (Group Task); Any other
Topics / lectures are arranged in sequence - same - as to be taught in the class. Maintain
data related to "Date" in its hard copy.
Introduction to Python
1 1 CO-1 TC-1 LC-1 T1/T2
and Python variables.
Understanding python
3 3 CO-1 TC-1 LC-1 T1/T2
blocks & Data Types.
Flow Control
5 5 CO-2 Conditional if, else and TC-1,TC-2 LC-1 T1/T2
else if
Manipulations Building
18 18 CO-3 TC-1,TC-2 LC-5 T1/T2/T3
blocks of programs.
File Operations:
21 21 CO-4 Reading and Writing TC-1,TC-2 LC-1 T1/T2/T3
Files.
Manipulating file
24 24 CO-4 pointer using seek TC-1,TC-2 LC-1 T1/T2/T3
Programming.
how to using file of
25 25 CO-4 TC-1,TC-2 LC-1 T1/T2
operations.
. Python programming
34 34 CO-4 TC-1,TC-2 LC-1 T1/T2
with IDE
Python Programming
35 35 CO-5 Practice
Question(Programs).
Python Programming
36 36 CO-5 Practice
Question(Programs).
Introduction to Python:
Python is a high-level, interpreted programming language known for its simplicity and
readability. Guido van Rossum created Python, and its first release was in 1991. Python is
designed to be easy to learn and use, emphasizing code readability and a clean syntax.
functional programming.
object-oriented, and
➢
Lecture-2 Python basic Operators and its Types.
Lecture 3 Understanding python blocks & Data Types.
Lecture-4 Declaring and using Numeric data types.
The numeric data type in Python represents the data that has a numeric value. A numeric value can be an integer, a
floating number, or even a complex number. These values are defined as Python int, Python float, and Python
complex classes in Python.
● Integers – This value is represented by int class. It contains positive or negative whole numbers (without
fractions or decimals). In Python, there is no limit to how long an integer value can be.
● Float – This value is represented by the float class. It is a real number with a floating-point
representation. It is specified by a decimal point. Optionally, the character e or E followed by a positive
or negative integer may be appended to specify scientific notation.
● Complex Numbers – A complex number is represented by a complex class. It is specified as (real part) +
(imaginary part)j. For example – 2+3j
a=5
b = 5.0
c = 2 + 4j
Output:
Type of a: <class 'int'>
Type of b: <class 'float'>
Type of c: <class 'complex'>
Discuss why python is an interpreted language ? Explain history and features of python .
Explain type conversion in python with an example.
Explain different types of operators in python. Also explain their precedence and associativity .
Discuss why Python is called a dynamic and strongly-typed language.
Which of the following statements will produce an error in python?
x,y,z= 1,2,3
s1 a,b=4,5,6
s2
u = 7,8,9
(list all the statements that have error)
UNIT-2
Lecture-5 Flow Control Conditional if, else and else if
In Python, flow control structures such as if, else, and elif (else if) are used to implement conditional logic. These
constructs allow you to control the flow of your program based on different conditions.
Let's discuss how to use them:
First and foremost, Control flow statements in Python are how you direct your programs to decide which parts of
code to run. By default, programs execute each line of code in sequence, with understanding how things are
proceeding.
What if you don't want to execute every single line of code? What if you have several answers, and the code must
choose which one to utilize based on the conditions? What if you require the software to continually utilize the
same code to perform the computations with slightly different inputs? What if you want to execute a few lines of
code repeatedly until the application fulfills a condition? It is when control flow enters the picture. Control flow
statements in Python direct the flow of your program's execution. It allows you to make decisions, repeat actions,
and handle different situations to make your code more dynamic and adaptable.
Conditional statements in Python are used to make decisions and execute different blocks of code based on specific
conditions. These conditions are defined using logical expressions that evaluate either True or False. Conditional
statements in Python control the flow of your program and enable it to respond dynamically to different situations.
1. if Statement:
The if statement is the most fundamental conditional statement in Python. It allows you to execute a block of code
only if a specified condition is true. If the condition evaluates to True, the code block is executed.
The if statement is used to execute a block of code only if a certain condition is true.
x = 10
f x > 5:
print("x is greater than 5")
# Output: x is greater than 5
2. else Statement: The else statement is used to execute a block of code if the condition specified in the if
statement is false.
y=3
if y > 5:
print("y is greater than 5")
else:
print("y is not greater than 5")
# Output: y is not greater than 5
3. elif Statement:
The elif (else if) statement is used when there are multiple conditions to check. It allows you to check additional
conditions if the previous ones are false.
z=0
if z > 0:
print("z is positive")
elif z < 0:
print("z is negative")
else:
print("z is zero")
# Output: z is zero
Lecture-6 Simple for loops, for loop using ranges.
Loops in Python
Iterative control statements in Python allow you to execute a block of code repeatedly. They perform repetitive
tasks, iterate over data structures, and handle various scenarios where actions need to be repeated.
The for loop iterates over a sequence (such as a list, tuple, string, or range) or any other iterable object. It executes a
block of code for each element in the sequence to perform actions on each element.
Code
Output:
code
I love apples.
I love bananas.
I love cherries.
In this example, the for loop iterates through the fruits list, and for each fruit, it executes the code block inside the
loop. This results in the message "I love [fruit]s." being printed for each item in the list.
code
word = "Python"
print(letter)
Output:
code
Here, the for loop iterates through the characters of the string "Python" and prints each character on a separate
line.
Python
code
Output:
code
The square of 1 is 1.
The square of 2 is 4.
The square of 3 is 9.
This example uses the range() function to generate a sequence of numbers from 1 to 5 (inclusive). The for loop then
iterates through this sequence, calculating and printing the square of each number.
The while loop in Python repeatedly executes a block of code as long as a specified condition remains true. It is
useful when you need to repeat an action until a certain condition is met.
Code
count = 1
count = 1
Output:
code
The count is 1.
The count is 2.
The count is 3.
The count is 4.
The count is 5.
In this example, the while loop continues to run as long as the condition (count <= 5) remains true.
code
password = "secret"
print("Access granted.")
mathematica
code
Access granted.
This example uses a while loop to repeatedly prompt the user for a password until they enter the correct password
("secret").
Code
counter = 0
counter = 1
Output:
code
Processing item 1
Processing item 2
Processing item 3
Here, the while loop is used to process items in a task. The loop continues until the counter reaches 3, at which
point it stops.
Lecture -7 String.
Python string is the collection of the characters surrounded by single quotes, double quotes, or triple quotes. The
computer does not understand the characters; internally, it stores manipulated character as the combination of the 0's
and 1's.
a string is a sequence of characters enclosed in single (' '), double (" "), or triple (''' ''' or """ """) quotes. Strings are
immutable, meaning their values cannot be changed after creation.
some key aspects of working with strings in Python:
● Creating Strings:
# Single quotes
single_quoted = 'Hello, Python!'
# Double quotes
double_quoted = "String in Python."
my_string = "Python"
# Accessing individual characters
first_char = my_string[0] # 'P'
last_char = my_string[-1] # 'n'
● String Slicing:
● String Concatenation:
string1 = "Hello"
string2 = "Python"
# Concatenating strings
concatenated = string1 + " " + string2 # 'Hello Python'
● String Methods:
Python provides various built-in string methods for manipulating and working with strings.
# Converting to lowercase
lowercased = my_string.lower() # ' hello, python! '
# Converting to uppercase
uppercased = my_string.upper() # ' HELLO, PYTHON! '
# Finding substring
index = my_string.find("Python") # 8
● String Formatting:
name = "Alice"
age = 30
● String Operations:
# String length
length = len(my_string) # 15
# Check if a substring is present
contains_python = "Python" in my_string # True
# Repeat a string
repeated_string = my_string * 3 # ' Hello, Python! Hello, Python! Hello, Python! '
● Escape Characters:
Lists:
A list is a versatile and mutable data structure in Python that can hold an ordered collection of items. Lists are
defined using square brackets [ ] and can contain elements of different data types.
● Creating Lists:
# Empty list
empty_list = []
● Modifying Lists:
# Modifying an element
fruits[0] = 'kiwi'
# Concatenating lists
more_fruits = ['pear', 'plum']
combined_list = fruits + more_fruits
Dictionaries:
A dictionary is an unordered collection of key-value pairs. It is defined using curly braces { } and colons : to separate
keys and values. Dictionaries are commonly used for data that needs to be looked up quickly.
● Creating Dictionaries:
# Empty dictionary
empty_dict = {}
In Python, a while loop is used to repeatedly execute a block of code as long as a specified condition is true. The loop
continues to execute until the condition becomes false. Let's discuss how to use while loops in Python:
● Infinite Loop:
if user_input.lower() == 'exit':
break # Exit the loop if 'exit' is entered
else:
print(f"You entered: {user_input}")
In this example, the else block is not executed because the loop is terminated by the break statement.
Lecture-10 Loop manipulation using pass continue, break and else.
In Python, loop manipulation statements like pass, continue, break, and else provide ways to control the flow of loops.
● pass Statement:
The pass statement is a no-operation statement that serves as a placeholder when syntactically some code is required,
but you don't want to execute any specific operation.
for i in range(5):
if i == 2:
else:
print(i)
# Output:
#0
#1
#3
#4
● continue Statement:
The continue statement is used to skip the rest of the code inside the loop for the current iteration and move to the
next iteration.
for i in range(5):
if i == 2:
continue # Skip printing when i is 2
print(i)
# Output:
#0
#1
#3
#4
break Statement:
The break statement is used to exit the loop prematurely. It terminates the loop when a specified condition is met.
for i in range(5):
if i == 3:
break # Exit the loop when i is 3
print(i)
# Output:
#0
#1
#2
The else clause in a loop is executed when the loop condition becomes False. However, if the loop is terminated by a
break statement, the else clause is skipped.
for i in range(5):
print(i)
else:
print("Loop finished.")
# Output:
#0
#1
#2
#3
#4
# Loop finished.
for i in range(5):
if i == 3:
break # Exit the loop when i is 3
print(i)
else:
print("Loop finished.")
# Output:
#0
#1
#2
Lecture-11 Condition and loop blocks in Program.
Condition Blocks:
Condition blocks are used to execute specific blocks of code based on whether a certain condition is true or false.
● if Statement:
x = 10
if x > 5:
print("x is greater than 5")
● else Statement:
y=3
if y > 5:
print("y is greater than 5")
else:
print("y is not greater than 5")
● elif Statement:
z=0
if z > 0:
print("z is positive")
elif z < 0:
print("z is negative")
else:
print("z is zero")
Loop Blocks:
Loop blocks are used for repeating a block of code multiple times.
for Loop:
fruits = ['apple', 'banana', 'orange']
for fruit in fruits:
print(fruit)
while Loop:
count = 0
You can also use conditionals within loops to create more complex control structures.
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
Nested Blocks:
You can nest conditionals and loops within each other for more intricate program logic.
for i in range(3):
if i == 0:
print("First iteration")
else:
print("Not the first iteration")
We can create a string by enclosing the characters in single-quotes or double- quotes. Python also
provides triple-quotes to represent the string, but it is generally used for multiline string or
docstrings.
Output –
Hello
Python
Hello
Python
Triple quotes are generally used for represent
the multiline or docstring
String Slicing
● In Python, the String Slicing method is used to access a range of characters in
the String. Slicing in a String is done by using a Slicing operator, i.e., a colon (:).
● One thing to keep in mind while using this method is that the string returned after
slicing includes the character at the start index but not the character at the last
index.
Reassigning Strings
As Python strings are immutable in nature, we cannot update the
existing string. We can only assign a completely new value to the variable with the same
name.
Example 1
Output:
A character of a string can be updated in Python by first converting the string into a Python
List and then updating the element in the list. As lists are mutable in nature, we can update
the character and then convert the list back into the String.
String2 = ''.join(list1)
print("\nUpdating character at 2nd Index: ") print(String2)
#Method 2
String3 = String1[0:2] + 'p' + String1[3:] print(String3)
Example 2
Output:
Deleting the String
As we know that strings are immutable. We cannot delete or remove the characters from
the string. But we can delete the entire string using the del keyword.
Output:
Output:
● Escape sequences start with a backslash and can be interpreted differently. If single
quotes are used to represent a string, then all the single quotes present in the string
must be escaped and the same is done for Double Quotes.
Example
String1= "C:\\Python\\Geeks\\" print(String1)
Formatting of Strings
Strings in Python can be formatted with the use of format( ) . Format method in String
contains curly braces {} as placeholders which can hold arguments according to position or
keyword to specify the order.
Output
● The list is a sequence data type which is used to store the collection
of data.
● In lists the comma (,)and the square brackets [enclose the List's items] serve
as separators.
● Lists need not be homogeneous always which makes it the most powerful
tool in Python.
● A single list may contain DataTypes like Integers, Strings, as well as Objects.
● Lists are mutable, and hence, they can be altered even after their creation.
A list may contain duplicate values with their distinct positions and hence, multiple distinct
or duplicate values can be passed as a sequence at the time of list creation.
Example-
List1=[“physics”, “Maths”,34,15.5]
List2=[2,3,5,10]
List Indexing and Splitting
The indexing procedure is carried out similarly to string processing. The slice operator [] can
be used to get to the List's components.
We can get the sub-list of the list using the following syntax.
o Within a start, the step is used to skip the nth element: stop.
Example-
List1=[0,1,2,3,4]
List1[1:3:1]= [1,2]
List = []
print("Initial blank List: ")
print(List)
List.append(1) List.append(2)
List.insert(2, 12)
List.extend([8, 'Geeks'])
print("List after performing Extend Operation: ") print(List)
Removing Elements from the List
Elements can be removed from the List by using the built-in remove() function but an
Error arises if the element doesn’t exist in the list.
List = [1, 2, 3, 4, 5, 6,
7, 8, 9, 10, 11, 12]
List.remove(5) List.remove(6)
List = [1, 2, 3, 4, 5]
List.pop()
print("List after popping an element: ")
print(List)
List.pop(2)
print("\nList after popping a specific element: ") print(List)
List out some in-built function in python List
Lecture-14 Python Tuple
Note: Creation of Python tuple without the use of parentheses is known as Tuple
Packing.
Note: We can change any python collection like (list, tuple, set) and string into other data
type like tuple, list and string. But cannot change into and float to any python collection.
For example: int cannot change into list or vice-versa.
Deleting a Tuple
Tuples are immutable and hence they do not allow deletion of a part of it. The entire tuple
gets deleted by the use of del() method.
The zip() is an inbuilt function in python. It takes items in sequence from a number of
collections to make a list of tuples, where each tuple contains one item from each collection.
The function is often used to group items from a list which has the same index.
Example:
A=[1,2,
3]
B=’XYZ’
Res=list(zip(A,B))# list of tuples print(Res)
Output:
Note: if the sequences are not of the same length then the result of zip() has the length of
the shorter sequence.
A=’abcd’
B=[1,2,3]
Res=list(zip(A,B))
print(Res)
Output:
[(‘a’,1),(‘b’,2),(‘c’,3)]
The * operator is used within the zip() function. The * operator unpacks a sequence into
positional arguments.
X=[(‘apple’,90000),(‘del’,60000),(‘hp’,50000)]
Laptop,prize=zip(*X)
print(Laptop)
print(prize)
Output:
(‘apple’,’del’,’hp’)
(90000,60000,50000)
Python program to find the maximum and minimum K elements in a tuple
Output
Lecture-15 String ManipulationMethods
endswith() Returns true if the string ends with the specified value
find() Searches the string for a specified value and returns the position of where it
was found
index() Searches the string for a specified value and returns the position of where it
was found
isalpha() Returns True if all characters in the string are in the alphabet
isascii() Returns True if all characters in the string are ascii characters
islower() Returns True if all characters in the string are lower case
split() Splits the string at the specified separator, and returns a list
startswith( Returns true if the string starts with the specified value
)
title() Converts the first character of each word to upper case
swapcase() Swaps cases, lower case becomes upper case and vice versa
2. WAP to accept a string & replace all spaces by # without using string method.
3. WAP to accept two strings and then display the common words
str1=input("Enter string1:")
str2=input("Enter string2:")
for i in str1.split():
if i in str2.s
Lecture-16 Python Set
set is an unordered collection of data items which does not contain duplicate values. Every
set element is unique and must be immutable (cannot be changed). However, a set itself is
mutable. Elements of set are enclosed inside a pair of curly brackets
{}.
We can add and remove items from the set. But cannot replace item as it does not support
indexing of data items.
Outpu
t:
apple
banan
a
cherry
NOTE: Lists cannot be added to a set as elements because Lists are not hashable whereas
Tuples can be added because tuples are immutable and hence Hashable.
● Elements can be removed from the Set by using the built-in remove()
function but a KeyError arises if the element doesn’t exist in the set.
S1={1,2,3,4,5}
S1.remove(2
) print(S1)
Output:
{1,3,4,5}
S1={1,2,3,4}
S2={1,2,3,4,5}
print(S1.issubset(S2))
Output:
True
print(S2.issuperset(S1))
Output:
True
>>> S1={1,2,3,4,5}
S2={5,6,7}
print(S1.union(S2)) # print(S1|S2) Output:
{1,2,3,4,5,6,7}
>>>
print(S1.intersection(S2)) # print(S2&S2)
Output:
{5}
>>>
Output:
{1,2,3,4,6,7}
● Dictionary in Python is a collection of keys values, used to store data values like a
map, which, unlike other data types which hold only a single value as an element.
● Each key is separated from its value by a colon (:), the items are separated by
commas, and the whole thing is enclosed in curly braces. An empty dictionary
without any items is written with just two curly braces, like this: {}.
● Keys are unique within a dictionary while values may not be. The values of a
dictionary can be of any type, but the keys must be of an immutable data type such
as strings, numbers, or tuples.
More than one entry per key is not allowed. Which means no duplicate key is allowed. When
duplicate keys are encountered during assignment, the last assignment wins.
Keys must be immutable. Which means you can use strings, numbers or tuples as dictionary
keys but something like ['key'] is not allowed.
In order to access the items of a dictionary refer to its key name. Key can be used inside
square brackets. . Following is a simple example −
dict['Name']:Zara dict['Age']: 7
There is also a method called get() that will also help in accessing the element from a
dictionary.This method accepts key as argument and returns the value.
Updating Dictionary
You can update a dictionary by adding a new entry or a key-value pair, modifying an existing
entry, or deleting an existing entry as shown below in the simple example −
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
The items of the dictionary can be deleted by using the del keyword
Output
Dictionary methods
Method Description
Q1. What do you mean by function? Give the syntax to define the function with an example.
Master code
s=0
Output:
Function calling is called driver code and function definition with block of statements is called master code
Q2. Differentiate between argument and parameter.
1. Formal parameter
2. Actual Parameter
Formal parameters are those written in function definition and actual
parameters are those written in function calling.
Formal parameters are called argument.
Arguments are the values that are passed to function definition.
Example:
Def fun(n1):
Print(n1)
a=10
fun(a)
here n1 is argument and a is parameter.
python. Ans:
def display(a='hello',b='world'): # you can have only default arguments
also print(a,b)
display()
Output:
hello world
print(d)
def display(a,b,c=10):
d=a+b+c
print(d)
display(2,
3)
Output:
15
def
display(*arg)
: for i in arg:
print(i)
display(‘hello’,’world’,’python’)
Output:
hello
world
pytho
Q5. Discuss return statement. Can we return more than one values with return
statement? Ans:
The Return Statement:The return statement is used to return a value from the function to a
calling function. It is also used to return from a function i.e. break out of the function.
Example:
square,cube=compute(2)
cube=lambda x:
x*x*x print(cube(2))
Output:
Note:
● The statement cube=lambda x: x*x*x creates a lambda function called cube, which
takes a single argument and returns the cube of a number.
variable. Ans:
1. Program to access a local variable outside a functions
def demo():
q=10
demo()
Output:
defined
2. Program to read global variable from a local scope
def demo():
print(s)
demo()
Output:
I love python
def demo():
print(s)
Output:
I love python
I love programming
Global statement is used to define a variable defined inside a function as a global variable. To
make local variable as global variable, use global keyword
Example:
a=20
def display():
global a
a=30
print(‘value of a is’,a)
display()
Output:
value of a is 30
Note:
Since the value of the global variable is changed within the function, the value
of ‘a’ outside the function will be the most recent value of ‘a’
def factorial(n):
return 1
return n * factorial(n-1)
print(factorial(5))
Output:
120
Note: Recursion ends when the number n reduces to 1. This is called base condition. Every
recursive function must have a base condition that stops the recursion or else the function
calls itself infinitely.
Ans:
def fibonacci(n):
return n
else:
return(fibonacci(n-1) +
fibonacci(n-2)) n = int(input("Enter
sequence:")
for i in range(n):
fibonacci(i),
Ans:
def gcd(a,b):
if(b==0):
return
else:
return gcd(b,a%b)
b=int(input("Enter second
number:")) GCD=gcd(a,b)
print(GCD)
Q10. Program to find the sum of elements in a list recursively.
Ans:
def sum_arr(arr,size):
if (size == 0):
return 0 else:
for i in range(0,n):
print(b)
Q11. Program to check whether a string is a palindrome or not using recursion. Ans:
def is_palindrome(s):
else:
if s[0] == s[-1]:
if(is_palindrome(a)==True):
Unit-4
Lecture21 :- File handling in Python
Introduction to File Handling
Python supports file handling and allows users to handle files i.e., to read and write files, along with many other file
handling options, to operate on files.
The concept of file handling has stretched over various other languages, but the implementation is either complicated
or lengthy, like other concepts of Python, this concept here is also easy and short. Python treats files differently as text
or binary and this is important. Each line of code includes a sequence of characters, and they form a text file. Each line
of a file is terminated with a special character, called the EOL or End of Line characters like comma {,} or newline
character. It ends the current line and tells the interpreter a new one has begun.
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.
Python provides built-in functions and methods to perform various file operations like reading, writing, and updating
files
Python File Open
Before performing any operation on the file like reading or writing, first, we have to open that file. For this, we should
use Python’s inbuilt function open() but at the time of opening, we have to specify the mode, which represents the
purpose of the opening file.
f = open(filename, mode)
Eg:- file = open('example.txt', 'r') # Opens the file in read mode
The mode argument is a string that specifies the mode in which the file is opened:
'r' for reading (default)
'w' for writing (creates a new file or truncates the file first)
'x' for exclusive creation (fails if the file already exists)
'a' for appending (creates a new file if it does not exist)
'b' for binary mode
't' for text mode (default)
'+' for updating (reading and writing)
r+: To read and write data into the file. The previous data in the file will be overridden.
w+: To write and read data. It will override existing data.
a+: To append and read data from the file. It won’t override existing data.
Lecture22:- Discussed about How use read functions like read(), readline(), readlines().
Reading from a File
Once the file is opened, you can read its content using methods like read(), readline(), or readlines():
# Read the entire file
content = file.read()
print(content)
Output:
Hello world
Welcome CSE
123 456
Q:- In this example, we will see how we can read a file using the with statement in Python.
# Python code to illustrate with()
with open("geeks.txt") as file:
data = file.read()
print(data)
Q:- Another way to read a file is to call a certain number of characters like in the following code the interpreter will
read the first five characters of stored data and return it as a string:
# Python code to illustrate read() mode character wise
file = open("geeks.txt", "r")
print (file.read(5))
Q:-We can also split lines while reading files in Python. The split() function splits the variable when space is
encountered. You can also split using any characters as you wish.
# Python code to illustrate split() function
with open("geeks.txt", "r") as file:
data = file.readlines()
for line in data:
word = line.split()
print (word)
OUTPUT:-
['Hello', 'world']
['CSE', ‘Welcome’]
['123', '456']
Lecture23 :- Writing files in Python
Writing to a File
To write to a file, you need to open it in a write ('w'), append ('a'), or update ('+') mode. Then, use the write() or
writelines() methods:
Syntax:-
file = open('example.txt', 'w') # Open the file in write mode
file.write('Hello, World!\n') # Write a string to the file
lines = ['First line.\n', 'Second line.\n']
file.writelines(lines) # Write a list of strings to the file
file.close()
Closing a File
It's important to close the file when you're done with it to free up system resources. Use the close() method:
file.close()
def read_file(filename):
try:
with open(filename, 'r') as f:
contents = f.read()
print(contents)
except IOError:
print("Error: could not read file " + filename)
def delete_file(filename):
try:
os.remove(filename)
print("File " + filename + " deleted successfully.")
except IOError:
print("Error: could not delete file " + filename)
if __name__ == '__main__':
filename = "example.txt"
new_filename = "new_example.txt"
create_file(filename)
read_file(filename)
append_file(filename, "This is some additional text.\n")
read_file(filename)
rename_file(filename, new_filename)
read_file(new_filename)
delete_file(new_filename)
Output:
1. offset: The number of bytes to move the file pointer. Positive values move the pointer forward, negative values
move it backward.
2. from_what: This argument specifies the reference point for the offset. It can take one of three values:
● 0 (default): The beginning of the file.
● 1: The current file position.
● 2: The end of the file.
Example:-
Example 1: Let’s suppose we have to read a file named “CSE.txt” which contains the following text:
"Code is like humor. When you have to explain it, it’s bad."
f = open("CSE.txt", "r")
print(f.readline())
f.close()
Output:
20
When you have to explain it, it’s bad.
Example 2: Seek() function with negative offset only works when file is opened in binary mode. Let’s suppose the
binary file contains the following text.
b'Code is like humor. When you have to explain it, its bad.'
f = open("data.txt", "rb")
f.close()
Output:
47
, its bad.
# Move the file pointer to the 10th byte from the beginning
file.seek(10)
# Move the file pointer 5 bytes backward from the current position
file.seek(-5, 1)
In this example:
The first seek(10) call moves the file pointer to the 10th byte from the beginning of the file.
The second seek(-5, 1) call moves the file pointer 5 bytes backward from the current position.
The third seek(0, 2) call moves the file pointer to the end of the file.
It's important to note that seeking beyond the end of the file when writing will cause the file to be extended with
null bytes up to the specified position. Therefore, you can seek beyond the end of the file when writing to append
data. However, seeking beyond the end of the file when reading will result in an error.
Lecture25:- File of Operations
Using a file of operations typically involves reading from or writing to a file that contains a series of instructions or data
manipulations. These operations can vary widely depending on the context, such as programming, data processing, or
system administration. Let's break down how to approach this in a few different scenarios:
2. Data Processing
In data processing, a file of operations might list data transformations or analyses to perform on a dataset. This could
involve:
Performing Operations:
For each operation, apply the corresponding data transformation. This might involve filtering data, performing
calculations, or aggregating information.
After performing an operation, you might need to write the result to a file or prepare it for the next operation.
3. System Administration
For system administration, a file of operations might contain a list of system commands or configuration changes to
apply to a server or network of computers.
Automating Tasks:
Use a scripting language suitable for system administration (such as Bash for Linux/Unix systems or PowerShell for
Windows).
Read each operation from the file and use the script to execute the corresponding system command or change the
system configuration.
General Tips
Error Handling: Always include error handling to manage unexpected or malformed operations gracefully.
Logging: Keep a log of operations performed and any errors or warnings generated. This is invaluable for debugging
and verifying that operations have been executed correctly.
Security: Be cautious when executing operations from a file, especially if the operations involve system commands or
could impact data integrity. Validate and sanitize the operations to prevent security vulnerabilities.
By breaking down the process into manageable steps and considering the context in which you're using the file of
operations, you can effectively implement and automate a wide range of tasks.
print,Hello World!
add,3,5
You want to read these operations and execute them. Let's assume add operation sums the numbers.
def handle_print(args):
print(*args)
def handle_add(args):
result = sum(map(int, args))
print(result)
2. Data Processing
Imagine you have a CSV file data.csv and an operations file data_operations.txt that contains operations like filter, >10
and average. For simplicity, let's handle a single operation: filtering values greater than 10.
Program:-
import pandas as pd
# Assuming a simple CSV file with one column of integers
df = pd.read_csv('data.csv')
3. System Administration
For system administration, let's automate the creation of backup files. Assume an operations file system_ops.txt with
content like backup,/path/to/file.
import shutil
import os
def backup_file(file_path):
if os.path.exists(file_path):
shutil.copy(file_path, f"{file_path}.backup")
print(f"Backup created for {file_path}")
else:
print(f"File does not exist: {file_path}")
1. Recursive Approach
The recursive approach directly implements the mathematical definition of the Fibonacci sequence. However, it's not
efficient for large numbers due to repeated calculations and a high recursive call stack usage.
def fibonacci_recursive(n):
if n <= 0:
return 0
elif n == 1:
return 1
else:
return fibonacci_recursive(n-1) + fibonacci_recursive(n-2)
# Example usage:
n = 10
print(f"The {n}th Fibonacci number (recursive) is: {fibonacci_recursive(n)}")
2. Iterative Approach
The iterative approach uses a loop to calculate the Fibonacci numbers up to n. This method is much more efficient
than recursion for large numbers.
def fibonacci_iterative(n):
a, b = 0, 1
for _ in range(n):
a, b = b, a + b
return a
# Example usage:
n = 10
print(f"The {n}th Fibonacci number (iterative) is: {fibonacci_iterative(n)}")
Lecture26:- Python Program(Matrix Addition)
return result_matrix
# Example usage
matrix1 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
matrix2 = [[9, 8, 7], [6, 5, 4], [3, 2, 1]]
print("Resultant Matrix:")
for row in add_matrices(matrix1, matrix2):
print(row)
Lecture26:- Python Program(Transpose Matrix of Program.)
Program:-
Transposing a matrix means flipping a matrix over its diagonal, turning the matrix's rows into columns and columns
into rows. This operation is common in mathematics and programming, especially in the context of linear algebra and
data manipulation.
Basic Python Loops: Good for educational purposes and environments where external dependencies are discouraged
or not allowed. However, manually coding the transpose operation can be error-prone for complex data structures.
Using NumPy: Offers a simple, efficient, and less error-prone method for transposing matrices. Highly recommended
for scientific computing, data analysis, and any application requiring manipulation of large numerical datasets.
def transpose_matrix(matrix):
# Initialize the transposed matrix with zeros
transposed = [[0 for _ in range(len(matrix))] for _ in range(len(matrix[0]))]
return transposed
# Example usage
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
transposed_matrix = transpose_matrix(matrix)
print("Original Matrix:")
for row in matrix:
print(row)
print("\nTransposed Matrix:")
for row in transposed_matrix:
print(row)
Lecture26:- Python Program (Identity Matrix)
def identity_matrix(n):
"""Create an n x n identity matrix."""
return [[1 if i == j else 0 for j in range(n)] for i in range(n)]
# Example usage
n=4
print("Identity Matrix of size", n)
for row in identity_matrix(n):
print(row)
Parameters:
number (int): The number for which the multiplication table is to be printed.
range_limit (int): The range up to which the table should be printed.
"""
for i in range(1, range_limit + 1):
print(f"{number} x {i} = {number * i}")
def main():
# Prompt the user for input
number = int(input("Enter the number for the multiplication table: "))
range_limit = int(input("Enter the range up to which to print the table: "))
if __name__ == "__main__":
main()
def is_leap_year(year):
"""
Returns True if the given year is a leap year, False otherwise.
"""
# Year is divisible by 4
if year % 4 == 0:
# Year is not divisible by 100 unless it's also divisible by 400
if year % 100 == 0:
if year % 400 == 0:
return True
else:
return False
else:
return True
else:
return False
def main():
year = int(input("Enter a year: "))
if is_leap_year(year):
print(f"{year} is a leap year.")
else:
print(f"{year} is not a leap year.")
if __name__ == "__main__":
main()
Python Program (Perfect Number)
A perfect number is a positive integer that is equal to the sum of its proper divisors, excluding itself. For example, 28 is
a perfect number because its divisors are 1, 2, 4, 7, and 14, and
1+2+4+7+14=28
Below is a Python program that checks if a given number is a perfect number. The program defines a function to
calculate the sum of divisors of a number and then checks if this sum equals the number itself.
def is_perfect_number(number):
if number < 1:
return False
sum_of_divisors = 0
# Check for divisors of the number
for possible_divisor in range(1, number):
if number % possible_divisor == 0:
sum_of_divisors += possible_divisor
# Compare the sum of divisors (excluding the number itself) to the number
return sum_of_divisors == number
def main():
number = int(input("Enter a number: "))
if is_perfect_number(number):
print(f"{number} is a perfect number.")
else:
print(f"{number} is not a perfect number.")
if __name__ == "__main__":
main()
An Armstrong number (also known as a narcissistic number) is a number that is equal to the sum of its own digits each
raised to the power of the number of digits. For example, 153 is an Armstrong number because it has 3 digits, and
13 +53+33 =153
To write a Python program that checks if a given number is an Armstrong number, you need to:
def is_armstrong_number(number):
# Convert the number to a string to easily iterate over its digits
str_number = str(number)
# Calculate the number of digits
num_digits = len(str_number)
# Calculate the sum of digits raised to the power of the number of digits
sum_of_powers = sum(int(digit) ** num_digits for digit in str_number)
def main():
number = int(input("Enter a number: "))
if is_armstrong_number(number):
print(f"{number} is an Armstrong number.")
else:
print(f"{number} is not an Armstrong number.")
if __name__ == "__main__":
main()
Write a python program to read the content of a file and then create a file COUNT.Txt to write the numbers of letters
and digits of the readed content from the given file .
Unit – 5
Lecture26(A):-Introduction to Python Packages
Python Packages
Python packages are a way of organizing and distributing Python code. They allow you to bundle multiple files or
modules into a single, importable package, making code reuse and distribution easier. Python packages can include
libraries, frameworks, or collections of modules that provide additional functionality or enable specific tasks. Here's an
overview of key concepts and steps related to Python packages:
Key Concepts
Module: A Python file containing Python definitions, statements, and functions. It's the smallest unit of code reuse in
Python.
Package: A way of collecting related modules together within a single tree-like hierarchy. Very complex packages may
include subpackages at various levels of the hierarchy.
Installing Packages
To install packages, you generally use pip, Python's package installer
Commonly Used Packages
Here are some widely used Python packages for various purposes:
NumPy: Numerical computing and array operations.
Pandas: Data analysis and manipulation.
Requests: HTTP requests for humans.
Matplotlib
Matplotlib is a popular Python library used for creating static, animated, and interactive visualizations in Python. It
provides a wide range of plotting tools and features for creating high-quality graphs, charts, and plots.
Here are some of the key components and functions provided by Matplotlib:
Key Components:
Figure: The entire window or page where the plots and charts are drawn.
Axes: The area where data is plotted. It includes the X-axis, Y-axis, and the plot itself.
Axis: The X-axis and Y-axis, which define the scale and limits of the plot.
Artist: Everything that is drawn on the figure (such as lines, text, shapes) is an artist.
Installation:-
python -m pip install -U matplotlib
Lecture26(B):- Matplotlib
Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data
visualization library built on NumPy arrays and designed to work with the broader SciPy stack. It was introduced by
John Hunter in 2002.
Types of Matplotlib
Matplotlib comes with a wide variety of plots. Plots help to understand trends, and patterns, and to make correlations.
They’re typically instruments for reasoning about quantitative information.
Some of the sample plots are covered here.
Matplotlib Line Plot
Matplotlib Bar Plot
Matplotlib Histograms Plot
Matplotlib Scatter Plot
Matplotlib Pie Charts
Matplotlib Area Plot
By importing the matplotlib module, defines x and y values for a plotPython, plots the data using the plot() function
and it helps to display the plot by using the show() function . The plot() creates a line plot by connecting the points
defined by x and y values.
Eg:-
# importing matplotlib module
from matplotlib import pyplot as plt
# x-axis values
x = [5, 2, 9, 4, 7]
# Y-axis values
y = [10, 5, 8, 4, 2]
# Function to plot
plt.plot(x, y)
# function to show the plot
plt.show()
2. Matplotlib Bar Plot
# Y-axis values
y = [10, 5, 8, 4, 2]
# x-axis values
x = [5, 2, 9, 4, 7]
# Y-axis values
y = [10, 5, 8, 4, 2]
# Data
x = [1, 2, 3, 4, 5]
y1, y2 = [10, 20, 15, 25, 30], [5, 15, 10, 20, 25]
# Area Chart
plt.fill_between(x, y1, y2, color='skyblue', alpha=0.4, label='Area 1-2')
plt.plot(x, y1, label='Line 1', marker='o')
plt.plot(x, y2, label='Line 2', marker='o')
Numpy:-
Features of NumPy
NumPy has various features including these important ones:
● A powerful N-dimensional array object
● Sophisticated (broadcasting) functions
● Tools for integrating C/C++ and Fortran code
● Useful linear algebra, Fourier transform, and random number capabilities
NumPy is used to work with arrays. The array object in NumPy is called ndarray.
We can create a NumPy ndarray object by using the array() function.
Eg:-
import numpy as np
To create an ndarray, we can pass a list, tuple or any array-like object into the array() method, and it will be converted
into an ndarray:
Dimensions in Arrays
NumPy arrays can have multiple dimensions, allowing users to store data in multilayered structures.
Dimensionalities of array:
Name Example
2-D Arrays
An array that has 1-D arrays as its elements is called a 2-D array.
Example:-
import numpy as np
print(arr)
3-D arrays
Example:-
import numpy as np
print(arr)
Lecture28: - Python Pandas
Introduction to Pandas
Pandas is a name from “Panel Data” and is a Python library used for data manipulation and analysis.
Pandas provides a convenient way to analyze and clean data. The Pandas library introduces two new data structures
to Python - Series and DataFrame, both of which are built on top of NumPy.
Install Pandas
To install pandas, you need Python and PIP installed in your system.
If you have Python and PIP installed already, you can install pandas by entering the following command in the
terminal:
pip install pandas
Import Pandas in Python We can import Pandas in Python using the import statement.
import pandas as pd
What can you do using Pandas?
Pandas are generally used for data science but have you wondered why? This is because pandas are used in
conjunction with other libraries that are used for data science. It is built on the top of the NumPy library which means
that a lot of structures of NumPy are used or replicated in Pandas. The data produced by Pandas are often used as
input for plotting functions of Matplotlib, statistical analysis in SciPy, and machine learning algorithms in Scikit-learn.
Here is a list of things that we can do using Pandas.
● Data set cleaning, merging, and joining.
● Easy handling of missing data (represented as NaN) in floating point as well as non-floating point data.
● Columns can be inserted and deleted from DataFrame and higher dimensional objects.
● Powerful group by functionality for performing split-apply-combine operations on data sets.
● Data Visulaization
Pandas Series
A Pandas Series is a one-dimensional labeled array capable of holding data of any type (integer, string, float, python
objects, etc.). The axis labels are collectively called indexes.
Pandas Series is nothing but a column in an Excel sheet. Labels need not be unique but must be a hashable type. The
object supports both integer and label-based indexing and provides a host of methods for performing operations
involving the index.
Example 1:
# import pandas as pd
import pandas as pd
# simple array
data = [1, 2, 3, 4]
ser = pd.Series(data)
print(ser)
Example 2:-
# import pandas as pd
import pandas as pd
# import numpy as np
import numpy as np
# simple array
data = np.array(['g','e','e','k','s'])
ser = pd.Series(data)
print(ser)
DataFrame
Pandas DataFrame is a two-dimensional data structure with labeled axes (rows and columns).
Creating Data Frame
In the real world, a Pandas DataFrame will be created by loading the datasets from existing storage, storage can be
SQL Database, CSV file, or an Excel file. Pandas DataFrame can be created from lists, dictionaries, and from a list of
dictionaries, etc.
Example:-
import pandas as pd
# list of strings
lst = ['Geeks', 'For', 'Geeks', 'is', 'portal', 'for', 'Geeks']
root.mainloop()
OUTPUT
Lecture30&31 :- Tkinter Introduction and programming
Tkinter
Python provides various options for developing graphical user interfaces (GUIs). Most important are listed below.
● Tkinter− Tkinter is the Python interface to the Tk GUI toolkit shipped with Python. We would look this
option in this chapter.
● wxPython− This is an open-source Python interface for wxWindow shttp://wxpython.org.
● JPython− JPython is a Python port for Java which gives Python scripts seamless access to Java class
libraries on the local machine http://www.jython.org
Tkinter Programming
Tkinter is the standard GUI library for Python. Python when combined with Tkinter provides a fast and easy way to
create GUI applications. Tkinter provides a powerful object-oriented interface to the Tk GUI toolkit.
Creating a GUI application using Tkinter is an easy task. All you need to do is perform the following steps .
● Import the Tkinter module.
● Create the GUI application main window.
● Add one or more of the above-mentioned widgets to the GUI application.
● Enter the main event loop to take action against each event triggered by the user.
Geometry Management
All Tkinter widgets have access to specific geometry management methods, which have the purpose of organizing
widgets throughout the parent widget area. Tkinter exposes the following geometry manager classes: pack, grid, and
place.
● The pack() Method− This geometry manager organizes widgets in blocks before placing them in the parent
widget.
● The grid() Method − This geometry manager organizes widgets in a table-like structure in the parent widget.
● The place() Method − This geometry manager organizes widgets by placing them in a specific position in the
parent widget (absolute positions).
WIDGETS
Label
ENTRY
● from tkinter import *
● top = Tk()
● L1 = Label(top, text = "User Name")
● L1.pack( side = LEFT)
● E1 = Entry(top, bd = 5)
● E1.pack(side = RIGHT)
● top.mainloop()
Output:
button
● # Code to demonstrate a button
● import Tkinter as tk
● root=tk.Tk()
● l=tk.Label(root,text="name",fg="red",bg="lightgreen")
● l.grid(row=0,column=0)
● e=tk.Entry(root)
● e.grid(row=0,column=1)
● b=tk.Button(root,text="click",fg="red",bg="blue")
● b.grid(row=1,column=1)
● root.mainloop()
OUTPUT
Lecture 32:&33 -Tkinter Widgets and its example
CheckButton
from tkinter import *
import tkinter
top = Tk()
CheckVar1 = IntVar()
CheckVar2 = IntVar()
def show():
print(CheckVar1.get())
print(CheckVar2.get())
C1.pack()
C2.pack()
B1.pack()
top.mainloop()
OUTPUT
MessageBox (Showinfo)
from tkinter import *
from tkinter import messagebox
top = Tk()
top.geometry("300x100")
def hello():
messagebox.showinfo("Say Hello", "Hello World")
Frame
from tkinter import *
root = Tk()
frame = Frame(root)
frame.pack()
bottomframe = Frame(root)
bottomframe.pack( side = BOTTOM )
redbutton = Button(frame, text = "Red", fg = "red")
redbutton.pack( side = LEFT)
greenbutton = Button(frame, text = "Brown", fg="brown")
greenbutton.pack( side = LEFT )
bluebutton = Button(frame, text = "Blue", fg = "blue")
bluebutton.pack( side = LEFT )
blackbutton = Button(bottomframe, text = "Black", fg = "black")
blackbutton.pack( side = BOTTOM)
root.mainloop()
OUTPUT:-
Important Ques-CO-5
Describe the need for catching exceptions using try and except statements.
What do you understand by module and package in Python.
Write a python program to plot the algebraic equation: 10x + 14.
What is a tkinter in Python and its advantages.
What are Widgets in Tkinter
Lecture34:- Programming Questions
Python Program to exchange the values of two numbers without using a temporary variable.
Python Program to take the temperature in Celsius and convert it to Fahrenheit.
Python Program to read two numbers and print their quotient and remainder.
Python Program to find the area of a triangle given all three sides.
Python Program to read height in centimeters and then convert the height to feet and inches
Python Program to compute simple interest given all the required values.
Python Program to check whether a given year is a leap year or not.
Python Program to take in the marks of 5 subjects and display the grade.
Python Program to check if a number is an Armstrong number.
Python Program to find the sum of digits in a number.
Python Program to print odd numbers within a given range.
Python Program to check whether a given number is a palindrome.
Python Program to print all numbers in a range divisible by a given number.
Python Program to read a number n and print an inverted star pattern of the desired size.
Python Program to find the sum of first N Natural Numbers.
Python Program to read a number n and print and compute the series “1+2+…+n=”.
Python Program to find the sum of series: 1 + 1/2 + 1/3 + ….. + 1/N.
Python Program to find the sum of series: 1 + x^2/2 + x^3/3 + … x^n/n.
Python Program to find the sum of series: 1 + 1/2 + 1/3 + ….. + 1/N.
Python program to find whether a number is a power of two.
Python Program to find the second largest number in a list.
Python Program to put the even and odd elements in a list into two different lists.
Python Program to merge two lists and sort it.
Python Program to find the second largest number in a list using bubble sort.
Python Program to find the intersection of two lists.
Python Program to sort a list of tuples in increasing order by the last element in each tuple.
Python Program to remove the duplicate items from a list.
Python Program to replace all occurrences of ‘a’ with ‘$’ in a string.
Python Program to detect if two strings are anagrams.
Python Program to count the number of vowels in a string.
Python Program to calculate the length of a string without using library functions.
Python Program to check if a string is a palindrome or not.
Python Program to check if a substring is present in a given string.
Python Program to add a key-value pair to a dictionary.
Python Program to concatenate two dictionaries into one dictionary.
Python Program to check if a given key exists in a dictionary or not.
Python Program to remove the given key from a dictionary.
Python Program to count the frequency of words appearing in a string using a dictionary.
Python Program to create a dictionary with key as first character and value as words starting with that
character.
Python Program to count the number of vowels present in a string using sets
Python Program to check common letters in the two input strings.
Python Program to display which letters are present in both the strings.
Python Program to find the fibonacci series using recursion.
Python Program to find the factorial of a number using recursion.
Python Program to find the GCD of two numbers using recursion.
Python Program to reverse a string using recursion.
Python Program to read the contents of a file.
Python Program to count the number of words in a text file.
Python Program to copy the contents of one file into another.
Python Program to append the contents of one file to another file.
Python Program to read a file and capitalize the first letter of every word in the file