0% found this document useful (0 votes)
21 views

Python CM

Uploaded by

Pavithra J
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views

Python CM

Uploaded by

Pavithra J
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 55

ATA CPT MDV

Contents
PYTHON INTRODUCTION .................................................................................. 2

VARIABLE DECLARATIONS ............................................................................... 4

Operators .................................................................................................................... 5

String ........................................................................................................................... 8

Array, List, Tuples ..................................................................................................... 9

Control flow ............................................................................................................. 16

FUNCTIONS: ........................................................................................................... 19

Text and Binary Files .............................................................................................. 22

Frozen Sets ................................................................................................................ 25

List comprehensions ............................................................................................... 26

Collection Modules................................................................................................. 27

OOPs (Object Oriented Programming) .............................................................. 29

Exception Handling ................................................................................................ 35

Modules and Packages ........................................................................................... 38

Decorators and Generators .................................................................................... 46

Coroutines and Asynchronous ............................................................................. 50

Multi Threading ...................................................................................................... 52

1
ATA CPT MDV

PYTHON INTRODUCTION
PYTHON is a cross-platform programming language, it runs on multiple platforms like
Windows, Mac OS X, Linux, Unix. It is free and open source.
PYTHON is a general-purpose interpreted, interactive, object-oriented and high-level
programming language.
It was created by Guido van Rossum during 1985-1990. Like ERl, Python source code is also
available under the GNU General Public License (GPL).
Python is designed to be highly readable. it uses English keywords frequently where as
other languages use punctuation, and it has fewer syntactical constructions than other
languages.
Python is Interpreted: Python is processed at runtime by the interpreter. you do not need to
compile your program before executing it. This is similar to PERL and PHP.
Python is Interactive: You can actually sit a Python prompt and interact with the interpreter
directly to write your programs.
Python is Object Oriented: Python supports Object-Oriented style or technique of
programming that encapsulates code within objects.
Python is a Beginner's Language: Python is a great language for the beginner-level
programmers and supports the development of a wide range of applications from simple
text processing to WWW browsers to games.

PYTHON FEATURES:
Easy to learn: Python has few keywords, simple structure and a clearly defined syntax. This
allows the student to pick up the language quickly.
Easy to read: Python code is more clearly defined and visible to the eyes.
Easy to maintain: Python's source code is fairly easy to maintain.
A broad standard library: Python's bulk of the library is very portable and cross-platform
compatible on UNIX, Windows, and Macintosh.
Interactive Mode: Python has support for an interactive mode which allows interactive
testing and debugging of snippets of code.

2
ATA CPT MDV

Portable: Python can run on a wide variety of hardware platforms and has the same
interface on all platforms.
Extendable: You can add low-level modules to the Python interpreter. These modules
enable programmers to add to or customize their tools to be more efficient.
GUI Programming: Python supports GUI applications can be created and ported to many
systems and is a cross platform.
There are various ways to start Python:
1. Immediate mode:
Typing Python in the command line will invoke the interpreter in interpreter in
immediate mode. We can directly type in Python expressions and press enter to get the
output.
>>>
2. Script mode:
This mode is used to execute Python program written in a file. Such a file is called a script.
Python scripts have the extension .py

KEYWORDS AND IDENTIFIERS


Identifiers are the set of valid strings which are allowed as names in a computer language.
VALID PYTHON IDENTIFIERS
* First character must be letter or underscore (_ )
* Any additional characters can be alphanumeric or underscore
* Case-sensitive
Main KEYWORDS
and elif global or
assert else if pass break
except import print exec
in raise continue finally
is return def for
lambda try del from
not while class

3
ATA CPT MDV

VARIABLE DECLARATIONS

Variable must be declared before they are used. once variable has been assigned users can
access it by the name.

for eg:
>>> x=10
>>>z='hello csc'
>>>x
10
>>>z
'hello csc'

PYTHON STATEMENT, INDENTATION AND COMMENTS:


Python statement:
Instructions that a python interpreter can execute are called statements.
Statement can be divided as two categories:
---> single line statement = #
eg:
>>>a=10
>>>b=20
>>>c=a+b
30
--->multiple statement = """
eg:
>>>a=1+2+3+ 4+5

PYTHON INDENTATION:
Most of the programming languages like c, c++, java use braces {} to define a block of code.
Python uses Indentation. i.e...( body of function, loop etc...)

PYTHON VARIABLES AND DATA TYPES:


=> By using assignment operator (=) to assign the variable.
eg:
a=8 --> integer type
b=8.4 -->floating type
c="csc" -- >string type

=>In Python MULTIPLE ASSINGNMENTS can be made in single statement.


eg:
a,b,c=3,2.5,"hello"
Multiple variables at once,
a=b=c=100 assigns the 100 to all three variables.
a=10,20,30 assigns as tuples.

4
ATA CPT MDV

Operators

Python operators are symbols or special characters that are used to perform various
operations on variables and values. They are an essential part of any programming
language, including Python, as they allow you to manipulate and work with data in
different ways. Python operators can be broadly categorized into several types based on
their functionality. Let's explore each type in detail:

1. Arithmetic Operators:
Arithmetic operators are used to perform mathematical operations on numerical values.
Python provides the following arithmetic operators:
+ (Addition): Adds two values together.
- (Subtraction): Subtracts the second value from the first.
* (Multiplication): Multiplies two values.
/ (Division): Divides the first value by the second (results in a float).
// (Floor Division): Divides the first value by the second, rounding down to the nearest
integer.
% (Modulus): Returns the remainder of the division between two values.
** (Exponentiation): Raises the first value to the power of the second.

2. Comparison Operators:
Comparison operators are used to compare two values and return a Boolean value (True or
False) based on the comparison result. Python provides the following comparison
operators:
== (Equal to)
!= (Not equal to)
< (Less than)
> (Greater than)
<= (Less than or equal to)
>= (Greater than or equal to)

3. Logical Operators:
Logical operators are used to combine multiple conditions and return a Boolean value.
Python provides the following logical operators:
and: Returns True if both conditions are True.
or: Returns True if at least one condition is True.
not: Returns the opposite Boolean value of the condition.

4. Assignment Operators:
Assignment operators are used to assign values to variables. They include a basic
assignment = as well as shorthand forms that combine an arithmetic operation with
assignment.
= (Assignment): Assigns the value on the right to the variable on the left.
+= (Add and Assign)

5
ATA CPT MDV

-= (Subtract and Assign)


*= (Multiply and Assign)
/= (Divide and Assign)
//= (Floor Divide and Assign)
%= (Modulus and Assign)
**= (Exponentiate and Assign)

5. Bitwise Operators:
Bitwise operators are used to manipulate individual bits of values at the binary level.
& (Bitwise AND)
| (Bitwise OR)
^ (Bitwise XOR)
~ (Bitwise NOT)
<< (Left Shift)
>> (Right Shift)

6. Membership Operators:
Membership operators are used to test whether a value exists within a sequence (like a
string, list, or tuple).
in: Returns True if the value is found in the sequence.
not in: Returns True if the value is not found in the sequence.

7. Identity Operators:
Identity operators are used to compare the memory location of two objects.
is: Returns True if both variables point to the same object.
is not: Returns True if both variables point to different objects.

These are the main Python operators. By using these operators effectively, users can write
powerful and expressive Python code.

Program 1 Arithmetic Operator


a=15
b=2
print ("a=", a)
print ("b=", b)
print ("A+B=", a+b)
print ("A-B=", a-b)
print ("A*B=", a*b)
print ("A/B=", a/b)
print ("A//B=", a//b)
print ("A%B=", a%b)
print ("A**B=", a**b)

6
ATA CPT MDV

Program 2 comparison operator


x=5
y=10
print ('x > y is ', x>y)
print ('x < y is ', x<y)
print ('x ==y is ', x==y)
print ('x >=y is ', x>=y)
print ('x <=y is ', x<=y)

Program 3 logical operator


x=10
y=5
print ('x and y is ', x and y)
print ('x or y is ', x or y)
print ('not x is ', not x)

Program 4 Assignment Operators


a = 10
b=5
c=a
print ("Value of c:", c)
b += a
print ("Value of b after +=:", b)
c -= a
print ("Value of c after -=:", c)
b *= a
print ("Value of b after *=:", b)
b /= a
print ("Value of b after /=:", b)
b //= 2
print ("Value of b after //=:", b)
b %= 3
print ("Value of b after %=:", b)
a **= 3
print ("Value of a after **=:", a)

Program 5 Bitwise Operators


a = 10 # 1010 in binary
b = 5 # 0101 in binary
result_and = a & b
print ("Bitwise AND:", result_and)
result_or = a | b
print ("Bitwise OR:", result_or)
result_xor = a ^ b
print ("Bitwise XOR:", result_xor)
result_not_a = ~a

7
ATA CPT MDV

result_not_b = ~b
print ("Bitwise NOT of a:", result_not_a)
print ("Bitwise NOT of b:", result_not_b)
result_left_shift = a << 1
print ("Left Shift of a:", result_left_shift)
result_right_shift = a >> 1
print ("Right Shift of a:", result_right_shift)

Program 6 membership operator


x='Hello python'
y={1:'a',2:'b'}
print ('H' in x)
print ('hello' not in x)
print (1 in y)
print ('a' in y)

Program 7 identity operator


x1 =5
y1 =5
x2= 'hello'
y2= 'hi'
x3= [ 1,2,3]
y3= [1,2,3]
print (x1 is not y1)
print (x2 is y2)
print (x3 is y3)

String
A string is a sequence of characters enclosed within either single (') or double (") quotation
marks. Strings are one of the fundamental data types in Python, and they are used to
represent text-based data. Strings are immutable where the contents cannot be changed
after creation.

String Function
str1="good evening "
str2=" WELCOME "
str3=" I Am A B.E Student"
a="1234"
sp=" "
print str1
print ("Capital of str1=",str1.capitalize())
print ("Center of str1=",str1.center(20,'*'))
print ("Count of e in str1=",str1.count('e'))
print ("Substring of str3=",str3.count("B.E",0,len(str3)))

8
ATA CPT MDV

print ("Substring of str3=",str3.find("B.E",0,len(str3)))


print ("Replace the B.E to ECE in str3=",str3.replace("B.E","E.C.E"))
print ("Is alpha or not in str1=",str1.isalpha())
print ("IS lower case str1=", str2.lower())
print ("IS upper case str2=", str1.upper())
print ("Space=",sp.isspace())
print ("Space=", str1.isspace())
print ("Length str1=", len(str1))
print ("Title of str3=", str3.istitle())
print ("Title of str2=", str2.istitle())
print ("Lstrip in str3=", str3.lstrip())
print ("Rstrip in str3=", str1.rstrip())
print ("strip in str3=", str2.strip())
print ("lower str2=", str2.lower())
print ("upper str1=", str1.upper())
print ("Swap str3=", str3.swapcase())
print ("split str3=", str3.split())
print ("Join str1 and str2=", str1.join(str2))
print (' '.join (['hai','welcome','to','csc']))

String Embedding
h1 = "CSC Computer Education"
h2 = "Medavakkam Branch"
msg = "Hi Welcome to {} and you have visited {}. ".format(h1, h2)
print(msg)

String Formatting
Python 3.6 introduced f-strings, a more concise way of formatting strings.
h1 = "CSC Computer Education"
h2 = "Medavakkam Branch"
msg = "Hi Welcome to {h1} and you have visited {h2}. "
print(msg)

Array, List, Tuples


Array
An array is a fixed-size, homogeneous collection of elements with the same data type. While
Python lists can store elements of different types, arrays are more memory-efficient and
offer faster access when dealing with large datasets.

Program 1. creating array


from array import *
print ("Array Elements are:")
a=array('i',[1,2,3,4,5,6,9,8,7,33,11,12])
print (a)

9
ATA CPT MDV

Program 2. print individual elements using indexes


print ("\n print particular element using index 2,5,-1:\n")
print a[2]
print a[5]
print a[-1]

Program 3. append value to array


Print ("\n Insert the array elements 13,14,15 in last position\n")
a.append(13)
print (a)
a.append(14)
print (a)
a.append(15)
print (a)

Program 4. insert the element to particular location


print ("\n Insert the element to particular location 0,9,10:\n")
a.insert(0,0)
print (a)
a.insert(9,16)
print (a)
a.insert(10,17)
print (a)

Program 5. extend the array elements


print ("\n Extending the array elements :\n")
b=array('i',[21,22,23,24,25])
print (b)
a.extend(b)
print (a)

Program 6. fromlist() method


Print ("\ncreate the array by using list by Fromlist():\n")
c= [100,200,300]
print ("The list element is:",c)
a.fromlist(c)
print (a)

Program 7. Remove () method


print("\n remove the element 300 from array:\n")
a.remove(300)
print (a)

10
ATA CPT MDV

Program 8. Remove last array element using pop()


from array import *
print ("character array elemtents:")
d=array('c',['a','b','c','d','e','f','g','h','i'])
print (d)
print ("\n Remove the last element using pop():")
d.pop()
print (d)
d.pop()
print (d)
d.pop()
print (d)

Program 9. fetch any element using index() method


a=array('i',[1,2,3,4,5,6,7,8,2,9,2,10,2,11])
print ("\n\nThe array elements are",a)
i1=a.index(1)
print (" Index of 1:",i1)
i2=a.index(3)
print (" Index of 3:",i2)
i3=a.index(11)
print (" Index of 11:",i3)

Program 10. reverse the array element


print (" \nArray Elements are:",a)
a.reverse()
print ("Reverse the array integer elements:",a)
d.reverse()
print ("Reverse the array characterelements:",d)

Program 11. number of occurrence


cnt=a.count(2)
print("\n\nnumber of occurence 2 in A array:")
print ("count of 2=",cnt)

Program 12. CONVERT ARRAY TO STRING


print ("\n\n convert the array element to string:")
s=array('c',['w','e','l','c','o','m','e'])
s.tostring()
print (s)

Program 13. convert array to list


print ("\n\nconverting Array element to list:")
f=a.tolist()
print (f)

11
ATA CPT MDV

Program 14. append a string fromstring()


Print ("\n\n Append a string to char array :")
d.reverse()
print (d)
d.fromstring(" alphabets")
print (d)

List
A list is a versatile and mutable collection of values. It is one of the most commonly used
data structures in Python. Lists are enclosed in square brackets [] and can contain elements
of different data types, including other lists.
Key characteristics
Mutable: You can modify, add, or remove elements after creating a list.
Ordered: Elements in a list have a specific order and can be accessed by their index.
Supports Duplicate Elements: A list can contain duplicate values.
Dynamic Size: You can change the size of a list by adding or removing elements.

Program 1. Creating List


fruits = ['apple', 'banana', 'orange']
fruits.append('grape')
fruits.insert(1, 'kiwi')
fruits.remove('banana')
print (fruits)

Program 2. Modifying and Extending


numbers = [1, 2, 3, 4, 5]
numbers[2] = 6
numbers.extend([7, 8, 9])
print("Modified and Extended List:", numbers)

Program 3. List Comprehensions


numbers = [1, 2, 3, 4, 5]
sq_num = [num ** 2 for num in numbers]
print("Squared Numbers:", sq_num)

Program 4. Iterating
courses = ["hdfd", "hdpd", "hdjd", "hdwd"]
print("Courses:")
for course in courses:
print(course)

Tuples
A tuple is similar to a list, but it is immutable, meaning its elements cannot be changed after
creation. Tuples are defined using parentheses (). They are often used to represent
collections of related data.

12
ATA CPT MDV

Key characteristics
Immutable: Once a tuple is created, its elements cannot be modified, added, or removed.
Ordered: Like lists, elements in a tuple are ordered and can be accessed by their index.
Supports Duplicate Elements: A tuple can contain duplicate values.
Used for Read-Only Data: Tuples are suitable for situations where data should not change.

Program 1. Accessing
courses = ("hdfd", "hdpd", "hdjd", "hdwd")
print ("First course:", courses [0])
print ("Last course:", courses [-1])
print ("Second and third courses:", courses [1:3])

Program 2. Unpacking
Course = ("HDFD", 30000, "C C++ Java Python")
crs, fees, syll = Course
print ("Course:", crs)
print ("Fees:", fees)
print ("Syllabus:", syll)

Program 3. Concatenating
tuple1 = (1, 2, 3)
tuple2 = (4, 5, 6)
print (tuple1)
print (tuple2)
c_t = tuple1 + tuple2
print ("Concatenated Tuple:", c_t)

Program 4. Iterating
courses = ("hdfd", "hdpd", "hdjd", "hdwd")
print("Courses:")
for course in courses:
print(course)

Dictionary
A dictionary is a versatile and powerful data structure that stores key-value pairs.
Dictionaries are also known as associative arrays or hash maps in other programming
languages. They are enclosed in curly braces {} and consist of comma-separated key-value
pairs. Each key in a dictionary is unique and maps to a specific value.

dicts={}
print dicts

Program 1. Integer Key values


dict1={1:"one",2:"two",3:"Three"}
print dict1

13
ATA CPT MDV

Program 2. Mixed Key values


dict2={"Name":"RCS","Course":"Ethical Hacking","timing":"Evening"}
print (dict2)
print dict2.get('Name')
print dict1.get(1)
print (dict2['Course'])
dict2['timing']="morning"#alter the values
print (dict2)
dict2['fees']=10000 #to add a new item
print (dict2)
print("The values are:" , dict2.values())
dict3={11:"a",12:"b",13:"c"}
print (dict3)
dict3.pop (12)
print (dict3)
dict3.popitem()
print (dict3)
dict3.clear()
print (dict3)
dict3={11:"a",12:"b",13:"c",14:"d"}
print (dict3)
del dict3[13]
print (dict3)
del dict3
print (dict3)

Program 3. Manipulation
dict2={"Name":"RCS","Course":"Big Data","timing":"Evening"}
dict1={2:"a",1:"b",5:"bb"}
print (dict2)
print (dict2.keys())
print (dict2.values())
print (dict2.items())
print (sorted(dict2))
print (sorted(dict1))
print (len(dict2))

Program 4. Iterating
book_prices = {
"Python Crash Course": 25,
"Deep Learning": 40,
"Algorithms Unlocked": 30
}
print("Book Prices:")
for book, price in book_prices.items():
print(f"{book}: ${price}")

14
ATA CPT MDV

print("\nAvailable Books:")
for book in book_prices.keys():
print(book)
print("\nBook Prices:")
for price in book_prices.values():
print(f"${price}")

Sets
A set is an unordered collection of unique elements. Sets are defined by enclosing a comma-
separated sequence of values within curly braces {}, or you can use the built-in set()
constructor. Sets can only contain unique elements. Duplicates are automatically removed.
Program 1
ms= {1, 2, 3, 3, 4}
print(ms)

Program 2. checking element


ms = {1, 2, 3, 4}
print(2 in ms)

Program 3. Adding and removing elements


ms = {1, 2, 3}
ms.add(4)
print(ms)
ms.update({5, 6})
print(ms)
ms.remove(2)
print(ms)
ms.discard(5)
print(ms)

Program 4. Set Operations


a={1,2,3,4,50,45}
print (a)
b={5,6,7,8,1,2,3,4}
print (b)
print ("union of a& b:", a|b)
print ("union of a & b by function:",a.union(b))
print ("union of a & b by union function:",b.union(a))
print ("Intersection of a & b:",a &b)
print ("Intersection of a & b by function:",a.intersection(b))
print ("Set Difference in a & b:",a-b)
print ("Set Difference in a & b:",b-a)
print ("Set Difference in a & b:",a.difference(b))
print ("Set Symmetric Difference in a & b:",a^b)
print ("Set Symmetric Difference in a & b:",a.symmetric_difference(b))

15
ATA CPT MDV

Control flow
Control flow refers to the order in which statements are executed in a program. Python
provides several control flow structures that allow users to use the code based on
conditions, loops, and Break and continue statements.
Conditional Statements (if, elif, else):
This allow users to execute different blocks of code based on conditions are true or false.
Program 1. if
a=int(input("Enter the value for a:"))
b=int(input("Enter the value for b:"))
if a>b:
print("A is greater")
if b>a:
print("B is greater")

Program 2. if else
a=int(input("enter a number"))
if a>=0:
print("positive")
else:
print("negative")

Program 3. elif(Multiple if)


a=input("Enter the value for a:")
b=input("Enter the value for b:")
c=input("Enter the value for c:")
if a>b and a>c:
print("A is greater")
elif b>c:
print("B is greater")
else:
print("C is greater")

Program 4. elif
mark=int(input("Enter ur mark:"))
if mark>90 and mark<=100:
print("O grade")
elif mark>80 and mark<=90:
print("A grade")
elif mark>70 and mark<=80:
print("B grade")
elif mark>60 and mark<=70:
print("C grade")
elif mark>40 and mark<=60:
print("D Grade")
else:
print("Fail")

16
ATA CPT MDV

Program 5. Nested if
num=input("Enter the value for number:")
if(num>=0):
if(num==0):
print("number is Zero")
else:
print("Positive number")
else:
print("Negative number")

Loops (for, while): Loops allows to repeatedly execute a block of code. Python provides
two types of loops which are for and while. The for loop iterates over a sequence and
executes a block of code for each item in the sequence.
Program 6. for
for i in 'Computer':
print (i)

Program 7. for else


digits={1,2,3,4,5,6,7,8}
for i in digits:
print(i)
else:
print("End of for loop")
print("no numbers left")

Program 8. for range


for i in range(0,30,5):
print(i)

Program9. for range


num=[1,2,3,4,5,6,7,8,9,10]
for i in range(len(num)):
print(num)

Program 10. while


i=0
while i<=10:
print(i)
i=i+1

Program 11. while else


i=1
while i<=5:
print(i)
i=i+1
else:
print("End of the loop")
17
ATA CPT MDV

Program 12. while True


total = 0
while True:
num = int(input("Enter a number (enter 0 to stop): "))
if num == 0:
break
total += num
print("Sum of numbers:", total)

Program 13
correct_password = "asdf1234"
while True:
password = input("Enter the password: ")
if password == correct_password:
print("Access granted!")
break
else:
print("Incorrect password. Try again.")

Program 14
import random
target_number = random.randint(1, 100)
attempts = 0
while True:
guess = int(input("Guess a number between 1 and 100: "))
attempts += 1
if guess < target_number:
print("Too low!")
elif guess > target_number:
print("Too high!")
else:
print (f"Congratulations! You guessed the number {target_number} in {attempts}
attempts.")
break

Break and Continue: Within loops, users can use the break statement to exit the loop
prematurely and the continue statement to skip the current iteration and move to next.
Program 15. break
digits=[1,2,3,4,5,6,7,8,9,10]
for i in digits:
print(i)
if i==5:
print ("Break the loop")
break
else:
print ("items left")

18
ATA CPT MDV

Program 16. continue


digits=[1,2,3,4,5,6,7,8,9,10]
for i in digits:
print(i)
if i==5:
print ("unbreak the loop")
continue
else:
print ("No items left")

Program 17
for val in "computer":
if val=="u":
continue
print(val)
print ("End of loop")

Program 18. pass


for i in range (1,10,2):
pass
print(i)

FUNCTIONS:
Function is a group of related statements that performs a specific task.
A Function can be divided into the following into two types:
1.Built- in Functions - Functions that are built into python.
2.User Defined Functions - Functions defined by the users themselves.
Program 1
def csc ():
print ('hi welcome to CSC Computer Education, Medavakkam Branch')
csc ()

Program 2 passing 1 argument


def square(a):
c=a*a
return(c)
print ("The square of a is:", square (10))
d=square(10)
print d

Program 3 passing 2 arguments


def greater(a,b):
if(a>b):
print" A is greater"
else:

19
ATA CPT MDV

print "B is greater"


x=int(input("Enter a value:"))
y=int(input("Enter b value:"))
greater(x,y)

Program 4. Actual and Formal Arguments


def avg(n1,n2,n3):
return(n1+n2+n3)/3.0
print("Average of the student")
res=avg(10,10,10)
print res
print ("\n Enter three values:")
m1=int(input())
m2=int(input())
m3=int(input())
res1=avg(m1,m2,m3)
print res1

A recursive function in Python is a function that calls itself as part of its own execution. It's
a powerful programming technique used to solve problems that can be broken down into
smaller, similar subproblems. Recursive functions are especially useful for tasks like
traversing data structures (e.g., trees, graphs), generating permutations or combinations,
and solving problems

Program 5. Recursive function Factorial


def fact(x):
if x==1:
return 1
else:
return(x*fact(x-1))
num=5
a=fact(num)
print ("The factorial value is:", a)

Program 6. Recursive function Fibanocci


def fibonacci(n):
if n <= 0:
return 0
elif n == 1:
return 1
else:
return fibonacci (n - 1) + fibonacci (n - 2)
n = 10
result = fibonacci(n)
print (f"The {n}th Fibonacci number is {result}")

20
ATA CPT MDV

Program 6. Recursive Power Calculation


def power (x, n):
if n == 0:
return 1
else:
return x * power (x, n - 1)
base = 2
exponent = 5
result = power (base, exponent)
print(f"{base}^{exponent} = {result}")

Scope
Scope refers to the region in user code where a particular variable is accessible and can be
used. The concept of scope helps determine where user can access a variable and whether
changes to the variable within a certain part of the code will affect its value elsewhere.
Python has several levels of scope, including global scope, local scope, and nested scope.

Global Scope:
Variables defined in the outermost level of a Python program or module have global scope.
These variables can be accessed from anywhere within the code, including inside functions
and classes. However, to modify a global variable within a function, user need to explicitly
declare it as global using the global keyword.

Program 7. Global Scope


global_var = 10
def modify_global():
global global_var
global_var = 20
modify_global()
print(global_var)

Local Scope:
Variables defined within a function have local scope. They are accessible only within the
function where they are defined. Local variables are created when the function is called and
destroyed when the function exits. They don't interfere with variables of the same name in
other functions.

Program 8. Local Scope


def some_function():
local_var = 5
print(local_var)
some_function() # Output: 5
# The following line would result in an error since local_var is not defined in this scope.
# print(local_var)

21
ATA CPT MDV

Nested Scope:
When user have functions defined within other functions, user create nested scopes. Each
inner function has access to its own local variables, as well as variables in its containing
function(s) and global variables.

Program 9. Nested Scope


global_var = 10
def outer_function():
outer_var = 20
def inner_function():
inner_var = 30
print(global_var, outer_var, inner_var)
inner_function()
outer_function() # Output: 10 20 30

Built-in Scope:
Python also has a built-in scope that contains all the names of Python's built-in functions,
like print(), len(), and range().

Local scope is the innermost scope, containing local variables.


Enclosing scope refers to the scope of the containing function (for nested functions).
Global scope contains variables defined at the module level.
Built-in scope contains Python's built-in functions.
Python's scoping rules ensure that variables are resolved based on this hierarchy. If a
variable is not found in the current scope, Python searches in outer scopes following the
LEGB order.

Text and Binary Files


Text files
File is a named location on disk to store related information. File is used to manage the large
volume of data. We want to read from or write to a file we need to open it first. Close the
file after finishing.
Python file operations takes place in the following order
1.Open a file.
2.Read or write (perform operation).
3.Close the file.

Program 1
Tfile=open("samp.txt","w")
Tfile.write("hai\n")
Tfile.write("welcome\n")
Tfile.write("to\n")
Tfile.write("python program\n")
Tfile.close()

22
ATA CPT MDV

print ("\n"*20)
Tfile=open("samp.txt","r")
for line in Tfile:
print (line)
Tfile.tell()
print (Tfile)
Tfile.seek(6)
print (Tfile)
print(Tfile.read())
Tfile.close()

Program 2
Tfile=open("samp.txt","r")
x=Tfile.readlines()
print (x)
'''x1=Tfile.readline()
print (x1)
x1=Tfile.readline()
print (x1)
Tfile.close()

Program 3
T=open("sample.txt","w")
T.writelines("hai\n welcome\n to \n csc\n computer\n center")
T.write("\nHello!.......")
T.close()
T=open("sample.txt","r")
a=T.readlines()
print (a)
b=T.read()
print (b)
T.close()

Program 4
Tfile=open("samp.txt","write")
Tfile.write("hii\n")
Tfile.write("Welcome to\n")
Tfile.write("CSC Computer Education\n")
Tfile.write("Medavakkam Branch\n")
Tfile.close()
Tfile=open("samp.txt","read")
for line in Tfile:
print (line)
Tfile.tell()
print (Tfile)

23
ATA CPT MDV

Tfile.seek(2)
print (Tfile)
print (Tfile.read())
Tfile.close()

Program 5
tfile=open("details.txt","w")
a=raw_input("enter a name:")
tfile.write(a)
print (a)
tfile.close()

Binary files
Binary files refer to files that store data in a format that is not human-readable, as opposed
to text files, which store data in a plain text format. Binary files can store a wide range of
data types, including images, audio, video, executables, and serialized objects. These files
contain a sequence of bytes that represent the data, and their content is not meant to be
interpreted as text.

Program 6
def decimal_to_hex(decimal_value):
hex_digits = "0123456789ABCDEF"
hexadecimal = ""
while decimal_value > 0:
remainder = decimal_value % 16
hexadecimal = hex_digits[remainder] + hexadecimal
decimal_value = decimal_value // 16
return hexadecimal
decimal_value = 65
hex_value = decimal_to_hex(decimal_value)
print(hex_value)

Program 7. Writing a Binary file


with open("binary_data.bin", "wb") as binary_file:
binary_data = b'\x43\x53\x43' # Binary representation of "CSC"
binary_file.write(binary_data)
print("Binary data written to binary_data.bin")

Program 8. Reading from Binary file


with open("binary_data.bin", "rb") as binary_file:
binary_data = binary_file.read()
text_data = binary_data.decode("utf-8")
print("Read binary data:", text_data)

24
ATA CPT MDV

Program 9. Copying image files using Binary


source_file = "tm.jpg"
destination_file = "tmcp.jpg"
with open(source_file, "rb") as source, open(destination_file, "wb") as destination:
binary_data = source.read()
destination.write(binary_data)
print("Binary file copied from", source_file, "to", destination_file)

Program 10. Copying image files using Binary


with open("binary_data.bin", "ab") as binary_file:
binary_data = b'\x43\x45' # Binary representation of "CE"
binary_file.write(binary_data)
print("Binary data appended to binary_data.bin")

Program 11. Converting Audio file to Binary file


def mp3_to_binary(mp3_filename, binary_filename):
try:
with open(mp3_filename, 'rb') as mp3_file, open(binary_filename, 'wb') as binary_file:
binary_file.write(mp3_file.read())
print(f"MP3 file '{mp3_filename}' converted to binary as '{binary_filename}'.")
except FileNotFoundError:
print(f"File '{mp3_filename}' not found.")
mp3_filename = 'alv.mp3'
binary_filename = 'op1.bin'
reconverted_mp3_filename = 'reconverted.mp3'
mp3_to_binary(mp3_filename, binary_filename)

Program 12. Converting Binary file to Audio file


def binary_to_mp3(binary_filename, mp3_filename):
try:
with open(binary_filename, 'rb') as binary_file, open(mp3_filename, 'wb') as mp3_file:
mp3_file.write(binary_file.read())
print(f"Binary file '{binary_filename}' converted to MP3 as '{mp3_filename}'.")
except FileNotFoundError:
print(f"File '{binary_filename}' not found.")
mp3_filename = 'alv.mp3'
binary_filename = 'op1.bin'
reconverted_mp3_filename = 'recon1.mp3'
binary_to_mp3(binary_filename, reconverted_mp3_filename)

Frozen Sets
Frozensets
A frozenset is an immutable version of a set. Once a frozenset is created, its elements
cannot be modified, added, or removed. Frozensets are useful when you need a collection
of unique elements that you don't intend to modify. Frozensets are immutable, meaning
users can't change their contents after creation.

25
ATA CPT MDV

Frozenset Syntax
frozen_fruits = frozenset(['apple', 'banana', 'orange'])

Program 1. Frozenset Operations


frozen_set1 = frozenset({1, 2, 3})
frozen_set2 = frozenset({3, 4, 5})
union_frozen = frozen_set1.union(frozen_set2)
intersection_frozen = frozen_set1.intersection(frozen_set2)

When to Use Sets vs. Frozensets:


Use a set when you want to store a dynamic collection of unique elements and need the
flexibility to modify the collection.
Use a frozenset when you want an immutable collection of unique elements that will not
change during its lifetime.
Sets and frozensets are valuable data structures in Python for handling collections of items
without duplicates, and they are especially useful when you need to perform set-based
operations like unions and intersections.

List comprehensions
List comprehensions are a concise and powerful way to create lists in Python. They allow
users to create new lists by performing operations on existing lists.
new_list = [expression for item in iterable if condition]
expression: The operation you want to perform on each item.
item: The variable that represents each element in the iterable.
iterable: The source of data (list, tuple, etc.).
condition (optional): A filter that determines whether the item should be included in the
new list.

Program 1: Generating Squares of Numbers


squares = []
for num in range(1, 6):
squares.append(num ** 2)
print(squares)

List comprehension Method


squares_comp = [num ** 2 for num in range(1, 6)]
print(squares_comp)

Program 2: Filtering Odd Numbers


numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
odd_numbers = []
for num in numbers:
if num % 2 != 0:
odd_numbers.append(num)

26
ATA CPT MDV

print(odd_numbers)

List comprehension Method


odd_numbers_comp = [num for num in numbers if num % 2 != 0]
print(odd_numbers_comp)

Program 3: Flattening a 2D List


matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flattened = []
for row in matrix:
for num in row:
flattened.append(num)
print(flattened)

List comprehension Method


flattened_comp = [num for row in matrix for num in row]
print(flattened_comp)

Program 4: Filtering and Mapping


numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
even_squared = []
for num in numbers:
if num % 2 == 0:
even_squared.append(num ** 2)
print(even_squared)

List comprehension Method


even_squared_comp = [num ** 2 for num in numbers if num % 2 == 0]
print(even_squared_comp)

These are different applications of list comprehensions: generating transformed lists,


filtering elements, flattening nested lists, and combining filtering with mapping.

Collection Modules
The collections module in Python provides specialized data structures that are alternatives
to the built-in data types. These data structures offer additional functionalities and can be
quite handy in various programming scenarios.
Counter
The Counter class is used to count the occurrences of elements in a collection.

Program 1
from collections import Counter
text = "CSC Computer Education, Medavakkam Branch"
char_count = Counter(text)
print(char_count)

27
ATA CPT MDV

Program 2
from collections import Counter
word_list = ["apple", "banana", "apple", "cherry", "banana", "apple"]
word_count = Counter(word_list)
print(word_count)

defaultdict
The defaultdict class is a dictionary subclass that provides a default value for keys that
don't exist in the dictionary.

Program 3
from collections import defaultdict
num_dict = defaultdict(int)
numbers = [1, 2, 3, 4, 2, 3, 4, 5]
for num in numbers:
num_dict[num] += 1
print(num_dict)

Program 4
from collections import defaultdict
fruit_dict = defaultdict(list)
fruit_list = [("apple", "red"), ("banana", "yellow"), ("cherry", "red"), ("apple", "green")]
for fruit, color in fruit_list:
fruit_dict[fruit].append(color)
print(fruit_dict)

OrderedDict
The OrderedDict class is a dictionary subclass that maintains the order of items based on
insertion.

Program 5
from collections import OrderedDict
ordered_dict = OrderedDict()
ordered_dict["one"] = 1
ordered_dict["three"] = 3
ordered_dict["two"] = 2
print(ordered_dict)
for key, value in ordered_dict.items():
print(key, value)

Program 6. Counting Most Common Elements


from collections import Counter
text = "programming is fun and programming is useful"
word_count = Counter(text.split())
most_common = word_count.most_common(2) # Get the 2 most common words
print(most_common)
28
ATA CPT MDV

Program 7. Grouping Elements by Length


from collections import defaultdict
words = ["apple", "banana", "cherry", "pear", "grape"]
length_groups = defaultdict(list)
for word in words:
length_groups[len(word)].append(word)
print(length_groups)

Program 8. Creating an Ordered Frequency Dictionary


from collections import OrderedDict, Counter
text = "hello world"
char_count = Counter(text)
ordered_count = OrderedDict(char_count.most_common())
print(ordered_count)

These programs tell the usage of the collections module's Counter, defaultdict, and
OrderedDict classes for various tasks, including counting elements, grouping by
characteristics, and maintaining order.

OOPs (Object Oriented Programming)

Object-Oriented Programming (OOP) is a programming paradigm that organizes code


around the concept of objects, which are instances of classes. It provides a way to structure
and design code by modeling real-world entities as objects with attributes (data) and
methods (functions). Python is a popular programming language that supports OOP
principles, and understanding OOP is essential for writing clean, organized, and modular
code.
Class
A class is a blueprint or template for creating objects. It defines the attributes and methods
that the objects of that class will have. Classes act as a container for attributes (also known
as instance variables) and methods (functions that operate on the instance).
Object
An object is an instance of a class. It represents a specific entity or concept in the real world
and contains the data (attributes) and behaviors (methods) defined by the class.
Encapsulation
Encapsulation is the concept of bundling data (attributes) and methods (functions) that
operate on that data within a single unit (object). It restricts direct access to internal details
of an object and promotes data hiding, preventing unintended manipulation.
Abstraction
Abstraction involves creating a simplified representation of an object that hides complex
implementation details. It allows you to focus on the essential aspects of an object while
ignoring unnecessary complexities.

29
ATA CPT MDV

Inheritance
Inheritance is a mechanism that allows a new class (subclass or derived class) to inherit
attributes and methods from an existing class (superclass or base class). It promotes code
reuse and supports the creation of more specialized classes based on a general class.
Polymorphism
Polymorphism allows objects of different classes to be treated as objects of a common base
class. It enables methods to be defined in a way that they can operate on objects of different
classes, providing flexibility and extensibility.

Program 1 Class
class Course:
def __init__(self, crs, drtn):
self.crs = crs
self.drtn = drtn
def crs_cov(self):
pass
# Inheritance
class Adpp(Course):
def crs_cov(self):
return "C,C++, Python"
class Adjp(Course):
def crs_cov(self):
return "C,C++,Java,HTML"
# Creating objects
pp = Adpp("Python", "Developer")
jp = Adjp("Java", "Programmer")
# Polymorphism
def cc(course):
return course.crs_cov()
print(cc(pp))
print(cc(jp))

We define a base class Course with attributes Course and duration.


We create two subclasses Adpp and Adjp that inherit from Course and override the Course
Coverage method.
We create objects dog and cat, which are instances of the Dog and Cat classes, respectively.
We demonstrate polymorphism by passing different objects to the Course coverage
function, which invokes the appropriate course method based on the object's class.
In real-world applications, OOP can greatly improve code organization, maintainability,
and extensibility. It's worth exploring more advanced topics like constructors, destructors,
class methods, instance methods, class variables, and access modifiers to deepen your
understanding of OOP in Python.

30
ATA CPT MDV

Program 2. Class
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
def display(self):
print(f"Name: {self.name}, Age: {self.age}")
student1 = Student("RCS", 22)
student1.display()

Program 3. Object
class Car:
def __init__(self, make, model):
self.make = make
self.model = model
car1 = Car("Maruthi", "Wagon R")
print(car1.make)
print(car1.model)

Program 4. Encapsulation
class BankAccount:
def __init__(self, balance):
self._balance = balance # Protected attribute
def deposit(self, amount):
if amount > 0:
self._balance += amount
def withdraw(self, amount):
if 0 < amount <= self._balance:
self._balance -= amount
def get_balance(self):
return self._balance
account = BankAccount(1000)
account.withdraw(500)
print(account.get_balance())

Program 5. Abstraction
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
pass
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14 * self.radius * self.radius

31
ATA CPT MDV

circle = Circle(8)
print(circle.area())

Program 6. Inheritance
class Vehicle:
def __init__(self, make, model):
self.make = make
self.model = model
class Car(Vehicle):
def __init__(self, make, model, mirror):
super().__init__(make, model)
self.mirror = mirror
car = Car("Maruthi", "Wagon R", 4)
print(car.make)
print(car.mirror)

Program 7
class person:
def disp(self):
print("\n Welcome to CSC Computer Education")
print("\n Medavakkam Branch")
p=person()
p.disp()

Program 8
class ebbill:
def calc(self):
print("\n\n \t ELECTRICITY BILL")
print("\n \t ************************")
a=int(input("Enter the reading:"))
if(a<=100):
print("UR reading is lessthan 100 ,\n so no need to pay the bill amont")
elif(a>=101 and a<=200):
c=a*5;
print("The amount=",c)
elif(a>=201 and a<=300):
c=a*6;
print("The amount=",c)
elif(a>=301 and a<=400):
c=a*7;
print("The amount=",c)
elif(a>=401 and a<=500):
c=a*8;
print("The amount=",c)
elif(a>=500 and a<=600):
c=a*9;

32
ATA CPT MDV

print("The amount=",c)
else:
c=a*10;
print ("The amount =",c)
print("********Thank you*********")
e=ebbill()
e.calc()

Program 9
class Courses:
def prog(self):
print("Programming")
print("\n 1.HDFD")
print("\n 2.HDJD")
print("\n 3.WD")
print("\n 4.ADPP")
print("\n 5.ADJP")

def acc(self):
print("\n Accounting")
print("\n 1.DCAT")
print("\n 2.DA")
print("\n 3.Adv Excel")
print("\n 4.Tally")
print("\n 5.Power BI")
print("\n 6.Tableau")

def mm(self):
print("\n MultiMedia")
print("\n 1.2D")
print("\n 2.3D")
print("\n 3.GD")
print("\n 4.VE")
print("\n 5.VFx")

c = Courses()
print("Enter any number between 1 to 3:")
a = int(input("Enter the number:"))
if a == 1:
c.prog()
elif a == 2:
c.acc()
elif a == 3:
c.mm()
else:
print("No such Courses are available")

33
ATA CPT MDV

print("\n\n \t Thank you")


print("\n\n \t Visit Again!.....")
print("\n *******************************")

Program 10. Constructor


class person:
def __init__(self,name):
self.name=name

def welcome(self):
print ("Hello",self.name)
print("Welcome to CSC Computer Education")
print("Medavakkam Branch")
sname=input("Enter ur name:")
p=person(sname)
p.welcome()

Program 11. Constructor Overload


class person:
def __init__(self,x=1,y=2):
self.a=x
self.b=y
def calc(self):
print "X value is:%d, y value is:%d"%(self.a,self.b)
p = person(2,3)
p1 = person(10)
p2 = person(20)
p.calc()
p1.calc()
p2.calc()

Program 12. Constructor Overload


class num:
def __init__(self,x=1,y=2):
self.cx=x
self.cy=y
def callme(self):
print("x value=%d,y value=%d",(self.cx,self.cy))
b1=num(10)
b2=num(20,30) # constructor overloading
b3=num()
b1.callme()
b2.callme()
b3.callme()

34
ATA CPT MDV

Destructor
Destructors are used to delete the memory which are created by constructor.
del__()- used to destructor

Program 13. Destructor


class samp:
def __init__(self,x,y):
self.x=x
self.y=y
def __del__(self):
print("\n\n An object removed from the memory")
def disp(self):
print("\n x value={} , y value={}".format(self.x,self.y))
s1=samp(2,4)
s2=samp(4,5)
s3=samp(10,20)
s4=samp(11,21)

s1.disp()
s2.disp()
s3.disp()
s4.disp()
del s1
del s2
del s3

Exception Handling
Exception handling in Python allows users to gracefully handle errors or exceptional
situations that may occur during the execution of the program. These errors, also known as
exceptions, can range from simple errors like dividing by zero to more complex issues like
file not found errors. By using exception handling, users can prevent the programs from
crashing and provide meaningful feedback to them about what went wrong.

Basic Exception Handling


Python provides a try-except block for handling exceptions. The general syntax is as
follows:
Basic exception handling
try:
num = int(input("Enter a number: "))
result = 10 / num
print("Result:", result)
except ZeroDivisionError:
print("Cannot divide by zero.")
except ValueError:
print("Invalid input. Please enter a valid number.")

35
ATA CPT MDV

Handling Multiple Exceptions


try:
# Code that might raise exceptions
# ...
except (ExceptionType1, ExceptionType2) as e:
# Code to handle the exceptions
# ...

Handling All Exceptions


try:
# Code that might raise exceptions
# ...
except:
# Code to handle any exception
# ...

Using else and finally


The else block is executed if no exception occurs in the try block.
The finally block is always executed, whether an exception occurred or not.
try:
# Code that might raise an exception
# ...
except ExceptionType:
# Code to handle the exception
# ...
else:
# Code to execute if no exception occurred
# ...
finally:
# Code that always executes
# ...

Raising Exceptions
def calculate_age(year_of_birth):
current_year = 2023
age = current_year - year_of_birth
if age < 0:
raise ValueError("Invalid year of birth")
return age
try:
age = calculate_age(2050)
except ValueError as e:
print("Error:", e)

36
ATA CPT MDV

Custom Exception Classes


class MyCustomError(Exception):
pass
try:
# Code that might raise MyCustomError
# ...
raise MyCustomError("This is a custom error")
except MyCustomError as e:
print("Custom error occurred:", e)
Exception handling is a crucial aspect of writing robust and reliable code. By anticipating
potential errors and handling them appropriately users can avoid unexpected issues.

Program 1 ValueError
try:
num = int(input("Enter a number: "))
print("You entered:", num)
except ValueError:
print("Invalid input. Please enter a valid number.")

Program 2 ZeroDivisionError
try:
num = int(input("Enter a number: "))
result = 10 / num
print("Result:", result)
except ZeroDivisionError:
print("Cannot divide by zero.")
except ValueError:
print("Invalid input. Please enter a valid number.")

Program 3 IndexError
try:
my_list = [1, 2, 3]
index = int(input("Enter an index: "))
print("Value at index:", my_list[index])
except IndexError:
print("Index out of range.")
except ValueError:
print("Invalid input. Please enter a valid index.")

Program 4 KeyError
try:
my_dict = {"key1": "value1", "key2": "value2"}
key = input("Enter a key: ")
print("Value:", my_dict[key])
except KeyError:
print("Key not found.")

37
ATA CPT MDV

Program 5 FileNotFoundError
try:
file_name = input("Enter file name: ")
with open(file_name, "r") as file:
content = file.read()
print("File content:", content)
except FileNotFoundError:
print("File not found.")

Program 6 KeyboardInterrupt
try:
while True:
pass
except KeyboardInterrupt:
print("\nProgram terminated by user.")

Program 7 Custom Exception


class NegativeNumberError(Exception):
pass
try:
num = int(input("Enter a positive number: "))
if num < 0:
raise NegativeNumberError("Negative number not allowed")
print("You entered:", num)
except NegativeNumberError as e:
print("Error:", e)
except ValueError:
print("Invalid input. Please enter a valid number.")

Modules and Packages


Modules refer to a file containing python statements and definitions. They are used to break
down large programs into small manageable and organised files. We can import the
definitions inside a module to another module or the interactive interpreter in Python.

Program 1. Math
import math
print ("The Value of pi is:",math.pi)

Program 2
import math
r=input("enter the radius value:")
area=math.pi*r*r;
print ("\n Area of Circle is:",area)

38
ATA CPT MDV

Program 3. Renaming
import math as m
print ("\n The root of 3 is:",m.sqrt(3))
print ("\n The root of 2 is:",m.sqrt(2))
print ("\n The root of 5 is:",m.sqrt(5))
print ("\n The factorial is:",m.factorial(5))

Program 4. Importing Specific Function


from math import pi
print "The pi value is: ",pi

Program 5
import math
print ("The power of 2 is:",math.pow(2,3))
print("\n Sin value is:",math.sin(90))
print("\n Cos value is:",math.cos(180))
print("\n square root value is",math.sqrt(9))
print("\n Exponential value is:",math.exp(3))
print("\n The ceiling value is :",math.ceil(4.1222))
print("\n The ceiling value is :",math.floor(4.789))

Program 6. Random
import random
random_number = random.randint(1, 100)
print ("Random number:", random_number)

Program 7. Random Shuffling


import random
my_list = [1, 2, 3, 4, 5]
random.shuffle(my_list)
print ("Shuffled list:", my_list)
Program 8. Random Choice
import random
course = ["HDFD", "HDJD", "HDWD", "ADPP", "ADJP","HDCAP","HDCAT", "CCAE"]
random_course = random.choice(course)
print ("Randomly selected Course:", random_course)

Program 9. Date and Time


import datetime
current_datetime = datetime.datetime.now()
print ("Current Date and Time:", current_datetime)

Program 10. Date Formatting


import datetime
current_date = datetime.date.today()
formatted_date = current_date.strftime("%d-%m-%Y")
print ("Formatted Date:", formatted_date)
39
ATA CPT MDV

Program 11. Date Difference


import datetime
date1 = datetime.date(2023, 9, 1)
date2 = datetime.date(2023, 9, 10)
date_difference = date2 - date1
print ("Date Difference:", date_difference.days, "days")

Program 12. Date Adding


import datetime
current_date = datetime.date.today()
days_to_add = 12
new_date = current_date + datetime.timedelta(days=days_to_add)
print ("Original Date:", current_date)
print ("New Date after Adding", days_to_add, "Days:", new_date)

Program 13. OS Listing Files in a Specified Directory


import os
directory_path = "D:/songs"
files_and_directories = os.listdir(directory_path)
for item in files_and_directories:
print(item)

Program 14. OS Creating a New Directory


import os
new_directory = "D:/Rcs"
os.mkdir(new_directory)
print ("New directory created:", new_directory)

Program 15. OS Checking a Specific File


import os
path_to_check = "d:/a.mp3"
if os.path.exists(path_to_check):
print(path_to_check, "exists.")
else:
print(path_to_check, "does not exist.")

Program 16. OS Deleting a File


import os
file_to_delete = "D:/Rcs/a.mp3"
if os.path.exists(file_to_delete):
os.remove(file_to_delete)
print ("File deleted:", file_to_delete)
else:
print ("File does not exist:", file_to_delete)

40
ATA CPT MDV

Program 17. Shutil Copying a File


import shutil
source_file = 'ccc.mp3'
destination_file = 'D:/Rcs'
try:
shutil.copy(source_file, destination_file)
print(f"{source_file} has been copied to {destination_file}.")
except FileNotFoundError as e:
print(f"File not found: {e}")
except shutil.SameFileError as e:
print(f"Source and destination are the same file: {e}")
except Exception as e:
print(f"Error while copying file: {e}")

Program 18. Shutil Moving a File


import shutil
source_file = 'employees.zip'
destination_file = 'D:/Rcs'
try:
shutil.move(source_file, destination_file)
print(f"{source_file} has been moved to {destination_file}.")
except FileNotFoundError as e:
print(f"File not found: {e}")
except shutil.Error as e:
print(f"Error while moving file: {e}")

Program 19. Shutil Copying all Files from Directory and Pasting in a new Directory
import shutil
source_directory = 'd:/Rcs'
destination_directory = 'd:/Rcs1'
try:
shutil.copytree(source_directory, destination_directory)
print(f"{source_directory} and its contents have been copied to {destination_directory}.")
except FileNotFoundError as e:
print(f"Directory not found: {e}")
except shutil.Error as e:
print(f"Error while copying directory: {e}")

Program 20. Shutil Deleting a Directory


import shutil
directory_to_delete = 'd:/rcs1'
try:
shutil.rmtree(directory_to_delete)
print(f"Directory '{directory_to_delete}' and its contents have been deleted.")
except FileNotFoundError as e:
print(f"Directory not found: {e}")

41
ATA CPT MDV

except PermissionError as e:
print(f"Permission denied: {e}")
except Exception as e:
print(f"Error while deleting directory: {e}")

Program 21. CSV Reading a CSV File


import csv
with open('employ.csv', 'r') as file:
csv_reader = csv.reader(file)
for row in csv_reader:
print(row)

Program 22. CSV writing data into a CSV File


import csv
data = [
['Name', 'Age', 'Dept', 'Dsgn', 'Salary'],
['LL', 24, 'Accnts', 'Clerk', 20000],
['MM', 26, 'Accnts', 'Clerk', 20000],
['NN', 25, 'Admin', 'Clerk', 19000]
]
with open('employ1.csv', 'w', newline='') as file:
csv_writer = csv.writer(file)
csv_writer.writerows(data)

Program 23. CSV Reading CSV File with DictReader


import csv
with open('employ.csv', 'r') as file:
csv_reader = csv.DictReader(file)
for row in csv_reader:
print(row['Name'], row['Age'], row['Dept'], row['Dsgn'], row['Salary'])

Program 24. CSV writing data into a CSV File with DictWriter
import csv
data = [
{'Name': 'OO', 'Age': 25, 'Dept': 'Mrktng'},
{'Name': 'PP', 'Age': 30, 'Dept': 'Mrktng'},
{'Name': 'QQ', 'Age': 32, 'Dept': 'Mrktng'},
{'Name': 'RR', 'Age': 28, 'Dept': 'Mrktng'},
{'Name': 'SS', 'Age': 22, 'Dept': 'Mrktng'}
]
with open('employ2.csv', 'w', newline='') as file:
fieldnames = ['Name', 'Age', 'Dept']
csv_writer = csv.DictWriter(file, fieldnames=fieldnames)
csv_writer.writeheader()
csv_writer.writerows(data)

42
ATA CPT MDV

Program 25. CSV Appending data into a CSV File


import csv
new_data = [
['LL', 35,'Mrktng','SE',25000],
['MM', 22,'Mrktng','Amngr',30000],
]
existing_csv_filename = 'employ.csv'
with open(existing_csv_filename, 'a', newline='') as file:
csv_writer = csv.writer(file)
csv_writer.writerows(new_data)
print(f'Data has been appended to "{existing_csv_filename}".')

Program 26. CSV Appending data into a CSV File


import csv
new_data = [
['NN', 25,'Admin','BDE',25000],
['OO', 27,'Admin','BDE',25000],
]
existing_csv_filename = 'employ.csv'
existing_data = []
with open(existing_csv_filename, 'r') as file:
csv_reader = csv.reader(file)
for row in csv_reader:
existing_data.append(row)
existing_data.extend(new_data)
with open(existing_csv_filename, 'w', newline='') as file:
csv_writer = csv.writer(file)
csv_writer.writerows(existing_data)
print(f'Data has been appended to "{existing_csv_filename}".')

Program 27. Time Sleeping Time


import time
print("Sleeping for 15 seconds...")
time.sleep(15)
print("Done sleeping!")

Program 28. Time Measuring Time


import time
start_time = time.time()
for _ in range(500000):
pass
end_time = time.time()
elapsed_time = end_time - start_time
print("Elapsed Time:", elapsed_time, "seconds")

43
ATA CPT MDV

Program 29. Time Converting to TimeStamp


import time
date_time = time.struct_time((2023, 9, 3, 7, 0, 0, 0, 0, 0))
timestamp = time.mktime(date_time)
print("Timestamp:", int(timestamp))

Program 30. Time Converting TimeStamp to Date & Time


import time
timestamp = 1630656000
formatted_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(timestamp))
print("Formatted Time:", formatted_time)

Program 31. Time Finding Remaining Days


import time
current_date = time.localtime()
future_date = time.strptime("2024-1-1", "%Y-%m-%d")
days_until_future = (time.mktime(future_date) - time.mktime(current_date))/(60 * 60 * 24)
print("Days until January 1, 2024:", int(days_until_future))

Program 32. Gzip Compressing File


import gzip
input_file = 'employ1.csv'
output_file = 'employ1.csv.gz'
with open(input_file, 'rb') as f_in, gzip.open(output_file, 'wb') as f_out:
f_out.writelines(f_in)
print(f'File "{input_file}" has been compressed to "{output_file}".')

Program 33. Gzip Decompressing File


import gzip
input_file = 'employ1.csv.gz'
output_file = 'employ1.csv'
with gzip.open(input_file, 'rb') as f_in, open(output_file, 'wb') as f_out:
f_out.write(f_in.read())
print(f'File "{input_file}" has been decompressed to "{output_file}".')

Program 34. Zip Creating a Zip Archive


import zipfile
files_to_zip = ['employ1.csv', 'employ2.csv', 'employ3.csv']
zip_filename = 'employees.zip'
with zipfile.ZipFile(zip_filename, 'w') as zipf:
for file in files_to_zip:
zipf.write(file)
print(f'Zip archive "{zip_filename}" has been created.')

Program 35. Zip Extracting Files from a Zip Archive


import zipfile
zip_filename = 'employees.zip'
44
ATA CPT MDV

extract_dir = 'extracted_files/'
with zipfile.ZipFile(zip_filename, 'r') as zipf:
zipf.extractall(extract_dir)
print(f'Files from "{zip_filename}" have been extracted to "{extract_dir}".')

Program 36. Zip Adding files to a Zip Archive


import zipfile
existing_zip_filename = 'employees.zip'
files_to_add = ['aaa.py', 'bbb.py', 'ccc.mp3', 'ccc.py']
with zipfile.ZipFile(existing_zip_filename, 'a') as zipf:
for file in files_to_add:
zipf.write(file)
print(f'File(s) have been added to "{existing_zip_filename}".')

Creating own packages


Python allows users to organize related modules and classes into a hierarchical structure.
This promotes code reusability, maintainability, and separation of concerns. A package is
essentially a directory containing multiple Python module files (.py files) and an optional
special file called __init__.py.
1. Choose a Directory Structure
If a user wants to create a package called "my_package" that contains multiple modules.
my_package/
├── __init__.py
├── module1.py
├── module2.py
2. Create the __init__.py File
This file initializes the package and can contain package-level attributes, functions, or even
import statements that user want to make available when the package is imported.
3. Create Module Files
Inside the package directory, create the module files (module1.py and module2.py in this
example) that contain the classes, functions, and variables user want to include in their
package.
4. Writing Code
module1.py
def greet(name):
return f"Hello, {name} Welcome to ATA!"
class MyClass:
def __init__(self, value):
self.value = value

def get_value(self):
return self.value

module2.py
def calculate_square(number):
return number ** 2

45
ATA CPT MDV

def calculate_cube(number):
return number ** 3
5. Using the Package:
Now, user can use the package and its modules in other parts of the code:
import my_package.module1 as mod1
import my_package.module2 as mod2
print(mod1.greet("Rcs")) # Output: "Hello, RCS Welcome to ATA!"

obj = mod1.MyClass(42)
print(obj.get_value()) # Output: 42

print(mod2.calculate_square(5)) # Output: 25
print(mod2.calculate_cube(3)) # Output: 27

6. Distributing and Installing user Package


If user want to distribute user package to others or make it installable via pip, user can
create a setup.py script and package it as a distribution package.

from setuptools import setup, find_packages


setup(
name='my_package',
version='0.1',
packages=find_packages(),
install_requires=[],
description='My Own package',
author='RCSKaran', author_email='[email protected]',)
After creating the setup.py script, user can create a distribution package using the
command.
python setup.py sdist
This will create a dist directory containing user package distribution files.
7. Installing the Package
user can then install the package using pip:
pip install dist/my_package-0.1.tar.gz

Decorators and Generators


Decorators
Decorators are a powerful concept in Python that allow you to modify or extend the
behavior of functions or methods without changing their code. Decorators are often used to
add functionality, such as logging, authentication, or measuring execution time, to
functions in a clean and reusable manner.
Decorator is a function that takes another function as its argument, adds some functionality,
and then returns the original or modified function. The syntax uses the @ symbol followed
by the decorator function name above the function to be decorated.

46
ATA CPT MDV

Program 1. Simple Decorator


def simple_decorator(func):
def wrapper():
print("Before function is called")
func()
print("After function is called")
return wrapper
@simple_decorator
def hello():
print("Hello, Welcome to CSC")
hello()

Program 2. Decorator with Arguments


def decorator_with_args(arg):
def actual_decorator(func):
def wrapper(*args, **kwargs):
print("Welcome to CSC", arg)
func(*args, **kwargs)
return wrapper
return actual_decorator
@decorator_with_args("Medavakkam Branch")
def greet(name):
print(f"Hello, {name}!")
greet("RCS")

Program 3. Measuring Execution Time


import time
def time_it(func):
def wrapper(*args, **kwargs):
start_time = time.time()
result = func(*args, **kwargs)
end_time = time.time()
print(f"Execution time: {end_time - start_time:.4f} seconds")
return result
return wrapper
@time_it
def slow_function():
time.sleep(2)
print("Function executed")
slow_function()

Program 4. Authentication Decorator


authenticated = False
def authentication_required(func):
def wrapper(*args, **kwargs):
if authenticated:

47
ATA CPT MDV

func(*args, **kwargs)
else:
print("Authentication required")
return wrapper
@authentication_required
def sensitive_operation():
print("Hi Welcome to CSC Computer Education Medavakkam Branch")
sensitive_operation()
authenticated = True
sensitive_operation()

Program 5. Chaining Multiple Decorators


def uppercase_decorator(func):
def wrapper(*args, **kwargs):
result = func(*args, **kwargs)
return result.upper()
return wrapper
def exclamation_decorator(func):
def wrapper(*args, **kwargs):
result = func(*args, **kwargs)
return result + "!"
return wrapper
@exclamation_decorator
@uppercase_decorator
def greet(name):
return f"Hello, {name}"
result = greet("RCSKaran")
print(result)

Decorators are a versatile tool in Python for adding behavior to functions in a modular
and reusable way. They're used extensively in frameworks and libraries to enhance the
capabilities of functions and methods without modifying their code directly.

Generators
Generators in Python are a type of iterable that allow user to iterate over a potentially
infinite sequence of values without the need to store them all in memory. Generators are
particularly useful when dealing with large datasets or when user want to generate values
on-the-fly. They are implemented using functions and the yield keyword.
When user create a generator, user define a function that uses the yield keyword to yield
values one at a time. When the generator function is called, it doesn't execute the code
immediately; instead, it returns a generator object. Each time user iterate over the generator,
the function's code is executed until it reaches a yield statement. The yielded value is then
returned to the caller, and the function's state is saved. The next time user iterate over the
generator, execution resumes from where it left off, continuing until the next yield or until
the function completes.

48
ATA CPT MDV

Advantages of Generators
Memory Efficiency: Generators produce values on-the-fly and don't store them in memory,
making them memory-efficient for large datasets or infinite sequences.
Lazy Evaluation: Values are generated only when needed, reducing unnecessary
computations.
Iterability: Generators are iterable, so user can use them in for loops, list comprehensions,
and other iterable contexts.
Infinite Sequences: Generators can represent infinite sequences, like the Fibonacci series,
without running into memory issues.

Creating Generators
def square_generator(limit):
for i in range(limit):
yield i * i
squares = square_generator(5)
for square in squares:
print(square)

Generator Expressions
Similar to list comprehensions, user can create generator expressions using parentheses.
Generator expressions are memory-efficient and can be used to produce values on-the-fly.
squares = (x * x for x in range(5))
for square in squares:
print(square)

Infinite Generators
Generators can be used to create infinite sequences, like the Fibonacci series.
def fibonacci_generator():
a, b = 0, 1
while True:
yield a
a, b = b, a + b
fibonacci = fibonacci_generator()
for _ in range(10):
print(next(fibonacci))

Generators are a powerful tool for handling sequences of values efficiently. They allow user
to work with data without the need to load it all into memory at once. Generators are widely
used for reading large files, processing streams of data, and handling infinite sequences.

Program 1 Generating Prime Numbers


def is_prime(num):
if num <= 1:
return False
for i in range(2, int(num**0.5) + 1):
if num % i == 0:

49
ATA CPT MDV

return False
return True
def prime_generator():
num = 2
while True:
if is_prime(num):
yield num
num += 1
primes = prime_generator()
for _ in range(10):
print(next(primes))

Program 2 File line generator


def read_file_line_by_line(file_path):
with open(file_path, 'r') as file:
for line in file:
yield line.strip()
file_path = 'sample.txt'
lines_generator = read_file_line_by_line(file_path)
for line in lines_generator:
print(line)

Coroutines and Asynchronous


Coroutines
Coroutines are a type of function that allow user to pause their execution, yield a value, and
later resume from where they left off. They are designed to be cooperative and enable
asynchronous programming, which is particularly useful when dealing with I/O-bound
operations.

Asynchronous Programming
Asynchronous programming is a programming paradigm that enables the execution of
tasks concurrently without blocking the main thread. It's especially beneficial for I/O-
bound operations, like network requests or file I/O, where the program can perform other
tasks while waiting for the I/O operations to complete.
Python provides the asyncio library for asynchronous programming, which utilizes
coroutines to achieve asynchronous behavior.

Program 1. Basic Coroutine


def simple_coroutine():
print("Coroutine has started")
x = yield
print("Received:", x)
coroutine = simple_coroutine()
next(coroutine) # Start the coroutine
coroutine.send(42) # Send a value to the coroutine

50
ATA CPT MDV

Program 2. Asynchronous Coroutine


import asyncio
async def async_coroutine():
print("Coroutine has started")
await asyncio.sleep(2) # Simulate an I/O operation
print("Coroutine has completed")
async def main():
await asyncio.gather(
async_coroutine(),
async_coroutine(),
)
asyncio.run(main())

Program 3. Asynchronous HTTP Requests


import aiohttp
import asyncio
async def fetch_url(url):
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
return await response.text()
async def main():
urls = ['https://www.youtube.com', 'https://www.google.com']
tasks = [fetch_url(url) for url in urls]
results = await asyncio.gather(*tasks)
for url, content in zip(urls, results):
print(f"{url}: {len(content)} bytes")
asyncio.run(main())

Program 4. Asynchronous File I/O


import asyncio
async def write_to_file(filename, content):
with open(filename, 'w') as file:
await asyncio.to_thread(file.write, content)
async def main():
content = "Hello, Welcome to CSC Computer Education"
await write_to_file("op.txt", content)
asyncio.run(main())

Coroutines enable asynchronous programming by allowing tasks to be paused and


resumed, while the asyncio library provides the tools to run and manage asynchronous
tasks concurrently. Asynchronous programming is particularly useful for tasks that involve
waiting for I/O operations, making user applications more efficient and responsive.

51
ATA CPT MDV

Multi Threading
Multithreading in Python allows users to run multiple threads smaller units of a program
concurrently within a single process. Each thread can execute different tasks, making it
possible to perform multiple operations simultaneously and efficiently utilize multi-core
processors. Python provides a built-in module called threading to work with threads.

To start a thread, call the start() method on the thread object. This will initiate the execution
of the target function concurrently.
Threads execute concurrently and independently. Each thread runs its target function
separately.
When multiple threads access shared resources concurrently, synchronization is required
to prevent race conditions and ensure data consistency. Python provides mechanisms like
locks (threading.Lock) and semaphores (threading.Semaphore) to achieve thread
synchronization.
Threads can terminate naturally when their target function completes. Use the join() method
to wait for a thread to finish execution before moving on to other tasks.

Threads can communicate with each other using various mechanisms, such as
threading.Event, threading.Condition, and threading.Queue.

Global Interpreter Lock


Python has a Global Interpreter Lock (GIL) that allows only one thread to execute Python
bytecode at a time. This means when using multithreading, CPU-bound tasks may not see
a significant performance improvement due to the GIL. However, for I/O-bound tasks,
multithreading can still be beneficial.

Program 1 Lock Method


import threading
shared_counter = 0
lock = threading.Lock()
def increment_counter():
global shared_counter
for _ in range(1000000):
with lock:
shared_counter += 1
thread1 = threading.Thread(target=increment_counter)
thread2 = threading.Thread(target=increment_counter)
thread3 = threading.Thread(target=increment_counter)
thread1.start()
thread2.start()
thread3.start()
thread1.join()
thread2.join()
thread3.join()
print("Shared Counter:", shared_counter)

52
ATA CPT MDV

Program 2 Semaphore Method


import threading
semaphore = threading.Semaphore(value=2)
def print_message(thread_id, message):
with semaphore:
print(f"Thread {thread_id}: {message}")
def worker_thread(thread_id):
print_message(thread_id, "Working...")
print_message(thread_id, "Finished work")
thread1 = threading.Thread(target=worker_thread, args=(1,))
thread2 = threading.Thread(target=worker_thread, args=(2,))
thread3 = threading.Thread(target=worker_thread, args=(3,))
thread1.start()
thread2.start()
thread3.start()
thread1.join()
thread2.join()
thread3.join()
print("All threads have finished.")

Program 3. Thread Communication using Event Method


import threading
import time
def thread1_func(event):
print("Thread 1 is waiting for the event to start.")
event.wait()
print("Thread 1 has started.")
time.sleep(2)
print("Thread 1 is done.")
event.clear()
def thread2_func(event):
print("Thread 2 is waiting for Thread 1 to signal.")
event.wait()
print("Thread 2 has received the signal from Thread 1 and started.")
time.sleep(1)
print("Thread 2 is done.")
event = threading.Event()
thread1 = threading.Thread(target=thread1_func, args=(event,))
thread2 = threading.Thread(target=thread2_func, args=(event,))
thread1.start()
thread2.start()
time.sleep(1)
event.set()
thread1.join()
thread2.join()
print("Both threads have finished.")

53
ATA CPT MDV

Program 4. Thread Communication using Condition Method


import threading
def print_even_numbers(condition):
for i in range(2, 11, 2):
with condition:
print(f"Even Thread: {i}")
condition.notify()
condition.wait()
def print_odd_numbers(condition):
for i in range(1, 10, 2):
with condition:
print(f"Odd Thread: {i}")
condition.notify()
condition.wait()
condition = threading.Condition()
even_thread = threading.Thread(target=print_even_numbers, args=(condition,))
odd_thread = threading.Thread(target=print_odd_numbers, args=(condition,))
even_thread.start()
odd_thread.start()
even_thread.join()
odd_thread.join()
print("Both threads have finished.")

Program 5. CPU-Bound Task


import threading
def fibonacci(n):
if n <= 1:
return n
else:
return fibonacci(n - 1) + fibonacci(n - 2)
def calculate_fibonacci():
result = fibonacci(35)
print(f"Fibonacci result: {result}")
thread1 = threading.Thread(target=calculate_fibonacci)
thread2 = threading.Thread(target=calculate_fibonacci)
thread1.start()
thread2.start()
thread1.join()
thread2.join()
print("Both threads have finished.")

Program 6. I/O-Bound Task


import threading
import requests
def download_page(url):

54
ATA CPT MDV

response = requests.get(url)
print(f"Downloaded {len(response.content)} bytes from {url}")
urls = ["https://www.example.com", "https://www.example.org"]
thread1 = threading.Thread(target=download_page, args=(urls[0],))
thread2 = threading.Thread(target=download_page, args=(urls[1],))
thread1.start()
thread2.start()
thread1.join()
thread2.join()
print("Both threads have finished downloading.")

55

You might also like