Python CM
Python CM
Contents
PYTHON INTRODUCTION .................................................................................. 2
Operators .................................................................................................................... 5
String ........................................................................................................................... 8
FUNCTIONS: ........................................................................................................... 19
Collection Modules................................................................................................. 27
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
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 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...)
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
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.
6
ATA CPT MDV
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)
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
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)
9
ATA CPT MDV
10
ATA CPT MDV
11
ATA CPT MDV
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 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
13
ATA CPT MDV
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)
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 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 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 17
for val in "computer":
if val=="u":
continue
print(val)
print ("End of loop")
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 ()
19
ATA CPT MDV
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
20
ATA CPT MDV
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.
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.
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.
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().
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)
24
ATA CPT MDV
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'])
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.
26
ATA CPT MDV
print(odd_numbers)
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)
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.
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))
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
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()
34
ATA CPT MDV
Destructor
Destructors are used to delete the memory which are created by constructor.
del__()- used to destructor
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.
35
ATA CPT MDV
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
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 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 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)
40
ATA CPT MDV
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}")
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 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
43
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}".')
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
46
ATA CPT MDV
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()
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.
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))
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.
50
ATA CPT MDV
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.
52
ATA CPT MDV
53
ATA CPT MDV
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