Python Notes
Python Notes
History of Python
Python laid its foundation in 1980s.
The implementation of Python was started in December 1989 by Guido Van Rossum at CWI
(Centrum Wiskunde & Informatica) in Netherland.
In February 1991, Guido Van Rossum published the labeled version 0.9.0 to alt.sources.
In 1994, Python 1.0 was released with new features like lambda, map, filter, and reduce.
In 2000, Python 2.0 was released with new features such as list comprehensions, garbage
collection, cycle detecting and Unicode support.
On December 3, 2008, Python 3.0 (also called "Py3K") was released. It was designed to
rectify the fundamental flaw of the language.
ABC programming language is said to be the predecessor of Python language, which was
capable of Exception Handling.
2
Python Programming Unit-1 Notes
Python can build a wide range of different data visualizations, like line and bar graphs, pie
charts, histograms, and 3D plots. Python also has a number of libraries that enable coders to write
programs for data analysis and machine learning more quickly and efficiently, like TensorFlow and
Keras.
2) Web development
Python is often used to develop the back end of a website or application—the parts that a user
doesn’t see. Python’s role in web development can include sending data to and from servers,
processing data and communicating with databases, URL routing, and ensuring security. Python offers
several frameworks for web development. Commonly used ones include Django and Flask.
3) Automation or scripting
If you find yourself performing a task over and over again, you could work more efficiently
by automating it with Python. Writing code used to build these automated processes is called
scripting. In the coding world, automation can be used to check for errors across multiple files,
convert files, execute simple math, and remove duplicates in data.
5) Everyday tasks
Python isn't only for programmers and data scientists. Learning Python can open new
possibilities for those in less data-heavy professions, like journalists, small business owners, or social
media marketers. Python can also enable non-programmer to simplify certain tasks in their lives.
Here are just a few of the tasks you could automate with Python:
Keep track of stock market or crypto prices
Send yourself a text reminder to carry an umbrella anytime it’s raining
Update your grocery shopping list
Renaming large batches of files
Converting text files to spreadsheets
Randomly assign chores to family members
Fill out online forms automatically
3
Python Programming Unit-1 Notes
Compiles the code into a byte code format which is a lower-level language understood by the
computers.
The Python Virtual Machine (PVM) perform over the instructions of low-level byte code to
run them one by one.
The Python script is saved with a .py extension which informs the computer that it is a Python
program script.
Python Installation
Unlike Windows, the Unix based operating systems such as Linux and Mac come with pre-
installed Python. Also, the way Python scripts are run in Windows and Unix operating systems
differ.
4
Python Programming Unit-1 Notes
a=1
b=3
if a > b:
print("a is Greater")
else:
print("b is Greater")
5
Python Programming Unit-1 Notes
On a Mac system, it is very straight-forward. All you need to do is open Launchpad and
search for Terminal, and in the terminal, type Python and boom, it will give you an output
with the Python version.
Like the Mac system, accessing terminal on a Linux system is also very easy. Right click on
the desktop and click Terminal and in terminal type Python and that's all!
2. Command Line –
We have to make python file first and save by .py extension. This file you can run in
command prompt by write python first and then your filename.
Create a file having extension .py
Write Python script in created file
To run a Python script store in a ‘.py’ file in command line, write ‘python’ keyword
before the file name in the command prompt.
python hello.py
Note: You can write your own file name in place of ‘hello.py’.
# File Name:- hello.py
# File Path:- C:\Users\Anonymous\Desktop\GfG\hello.py
print ("Hello World!")
6
Python Programming Unit-1 Notes
Example:-
>>> print('Hello, World!')
Hello, World!
>>> print(1)
1
>>> print(2.2)
2.2
>>> print('Abc@123')
Abc@123
type( ):- To find the type of given value type() function is used.
In python we don’t have to write int, float, char it will automatically understand the type of
given value. So, if we want to find particular type of given value, we can use the type function.
Variables
Variables are containers for storing data values.
Creating Variables
1. Python has no command for declaring a variable. We just have to write variable name
and assign the value in it.
2. A variable is created the moment you first assign a value to it.
Example:- Output:-
x=5
y = “LJ Polytechnic” 5
print(x) LJ Polytechnic
print(y)
7
Python Programming Unit-1 Notes
3. Variables do not need to be declared with any particular type, and can even change
type after they have been set. If we use the same name, the variable starts referring to
a new value and type.
Example:- Output:-
x=5
LJ Polytechnic
x = “LJ Polytechnic”
print(x)
4. Python allows assigning a single value to several variables simultaneously with “=”
operators.
Example:-
x = y = z = 100 Output:- 100
print(y)
8
Python Programming Unit-1 Notes
Keywords:-
and del from none true continue lambda
String:
Strings are arrays of bytes representing Unicode characters.
String data type is most important data type in python.
Python does not have a character data type, a single character is simply a string with a length
of 1.
String is not a small. It can also big as million characters.
Python has also built in functions and algorithms for string.
String is the combination of multiple characters.
String index is starting from 0.
Example:- Output:-
s = 'P' P
print(s) <class ‘str’>
type(s) Python
<class ‘str’>
language = 'Python'
print(language)
type(language)
9
Python Programming Unit-1 Notes
String:- P y t h o n
[-6] [-5] [-4] [-3] [-2] [-1]
Length of a string:
To find the length of the string len( ) function is used.
len() is a built-in function that returns the number of characters in a string:
Example:- Output:-
language = 'Python'
6
print( len(language))
To get the last letter of a string, you might be tempted to try something like this:
Because if you write simply length, then length will start from 0 so it can’t display last digit.
x = "Python"
length = len(x) n
y=x[length-1]
print(y)
String slices:
A segment of a string is called a slice. Selecting a slice is similar to selecting a character:
We can specify start, stop and step (optional) within the square brackets as:
string[start:stop:step]
start: It is the index from where the slice starts. The default value is 0.
stop: It is the index at which the slice stops. The character at this index is not included in the
slice. The default value is the length of the string.
step: It specifies the number of jumps to take while going from start to stop. It takes the
default value of 1.
10
Python Programming Unit-1 Notes
Example:-
s = 'Welcome to LJKU'
print(s[0:8])
print(s[11:16])
#if we can write same digit at both place then it will not give us any output
print(s[3:3])
print(s[ : :-2]) #it will first reverse the string and skip 1 character after reverse.
Output:-
Welcome
LJKU
Welcome to LJKU
Welcome to LJKU
Jelcome to LJKU
UKJL ot emocleW
Wloet JU
UJ teolW
String methods
Everything in Python is an object. A string is an object too. Python provides us with various methods
to call on the string object.
Note: Note that none of these methods alters the actual string. They instead return a copy of the
string. This copy is the manipulated version of the string.
11
Python Programming Unit-1 Notes
capitalize( )
This method is used to capitalize a string.
lower( )
This method converts all alphabetic characters to lowercase.
upper( )
This method converts all alphabetic characters to uppercase.
title( )
This method converts the first letter of each word to uppercase and remaining letters to
lowercase
swapcase([<chars>])
This method swaps case of all alphabetic characters.
rstrip( )
This method removes trailing characters from a string. Removes trailing whitespaces if you don’t
provide a <chars> argument.
strip( )
This method removes leading and trailing characters from a string. Removes leading and
trailing whitespaces if you don’t provide a <chars> argument
join(<iterable>)
This method returns the string concatenated with the elements of iterable.
>>>s=('We','are','coders')
>>>s1= '_'.join(s)
print(s1)
We_are_coders
split(sep=None, maxsplit=-1)
This method splits a string into a list of substrings based on sep. If you don’t pass a value to sep, it
splits based on whitespaces.
Strings can be concatenated (glued together) with the + operator, and repeated with *:
>>>3*'un'
'ununun'
>>>'Py''thon'
'Python'
>>>'Py'+'thon'
'Python'
Escape Characters
To insert characters that are illegal in a string, use an escape character. An escape character is a
backslash (\) followed by the character you want to insert.
14
Python Programming Unit-1 Notes
\\ Backslash \b Backspace
Numbers
There are three numeric types in Python:
int
float
complex
Variables of numeric types are created when you assign a value to them:
>>>x = 1 #int
>>> y = 2.8 #float
>>> z = 1j #complex
>>>print(type(x))
<class 'int'>
>>>print(type(y))
<class 'float'>
>>>print(type(z))
<class 'complex'>
Int
Integer is a whole number, positive or negative, without decimals, of unlimited length.
>>>x = 1
>>>y = 35656222554887711
>>>z = -3255522
>>>print(type(x))
<class 'int'>
>>>print(type(y))
<class 'int'>
>>>print(type(z)) 15
<class 'int'>
Python Programming Unit-1 Notes
Float
Float or "floating point number" is a number, positive or negative, containing one or more decimals.
Float can also be scientific numbers with an "e" to indicate the power of 10.
Complex
Complex numbers are written with a "j" as the imaginary part:
x = 3+5j
y = 5j
z = -5j <class 'complex'>
<class 'complex'>
print(type(x))
<class 'complex'>
print(type(y))
print(type(z))
Type Conversion
You can convert from one type to another with the int(), float(), and complex() methods
Example:-
x = 1 # int Output:-
y = 2.8 # float
z = 1j # complex
#convert from int to float:
a = float(x) 1.0
#convert from float to int: <class 'float'>
b = int(y) 2
#convert from int to complex: <class 'int'>
c = complex(x) (1+0j)
print(a) <class 'complex'>
print(type(a))
print(b)
print(type(b))
print(c) 16
print(type(c))
Python Programming Unit-1 Notes
Operators
Operators in general are used to perform operations on values and variables. These are
standard symbols used for the purpose of logical and arithmetic operations.
Arithmetic Operators
Arithmetic operators are used to performing mathematical operations like addition,
subtraction, multiplication, and division.
Example:- Output:-
a = 21
b = 10
c=0
c=a+b
print("Addition is:-",c)
c=a-b Addition is:- 31
print('Subtraction is:-',c) Subtraction is:- 11
c=a*b Multiplication is:- 210
print('Multiplication is:-',c) Division is:- 2.1
c=a/b Reminder of a/c is:- 1
print('Division is:-',c) result of p^q is:- 8
c=a%b result of a devide b is:- 2
print("Reminder of a/c is:-",c)
p=2
q=3
r =p**q
print("result of p^q is:-",r)
x = 11
y=5
17
z = a//b
print("result of a devide b is:-",z)
Python Programming Unit-1 Notes
Comparison Operators
Comparison of Relational operators compares the values. It either returns True or False
according to the condition.
> Greater than: True if the left operand is greater than x > y
the right
< Less than: True if the left operand is less than the x < y
right
<= Less than or equal to True if the left operand is less x <= y
than or equal to the right
Example:
>>># a == b is False
>>>print(a == b)
False
>>># a != b is True
>>>print(a != b)
True
18
Python Programming Unit-1 Notes
Logical Operators
Logical operators perform Logical AND, Logical OR, and Logical NOT operations. It is used
to combine conditional statements.
and Logical AND: True if both the operands are true x and y
Example: Output:
x=5
False
print(x>3 and x>10) #and
True
print (x>3 or x>10) #or
True
print(not(x > 3 and x > 10))
# returns False because not is used to reverse the result
Bitwise Operators
Bitwise operators act on bits and perform the bit-by-bit operations. These are used to operate on
binary numbers.
Operator Description Syntax
>> The left operands value is moved left by the number x>>
Bitwise right of bits specified by the right operand.
shift
19
Python Programming Unit-1 Notes
Example: Output:
Assignment Operators
Assignment operators are used to assigning values to the variables.
20
Python Programming Unit-1 Notes
Identity Operators
is and is not are the identity operators both are used to check if two values are located on
the same part of the memory. Two variables that are equal do not imply that they are identical.
Operator Description
>>> a = 10
>>> b = 20
>>> c = a
Membership Operators
in and not in are the membership operators; used to test whether a value or variable is in a
sequence.
Operator Description
Example:-
#membership_ex.py
x = 24
y = 20
list = [10, 20, 30, 40, 50]
if (x not in list):
print("x is NOT present in given list")
else:
print("x is present in given list")
if (y in list):
print("y is present in given list")
else:
print("y is NOT present in given list")
Output:-
22
Python Programming Unit-1 Notes
Operator Associativity
If an expression contains two or more operators with the same precedence then Operator
Associativity is used to determine. It can either be Left to Right or from Right to Left.
23
Python Programming Unit-2 Notes
Conditional execution
In order to write useful programs, we almost always need the ability to check conditions and
change the behaviour of the program accordingly. Conditional statements give us this ability.
if statement
The if statement is used to test a particular condition and if the condition is true, it executes a
block of code known as if-block. The condition of if statement can be any valid logical expression
which can be either evaluated to true or false.
if (condition):
#statement1
#extra statements....
#statement2
Example:-
i = 10
if (i>15):
print("10 is less than 15")
print("I am not in if")
I am not in if
As the condition present in the if statement is false. So, the block below the if statement is not
executed.
if-else
The if-else statement provides an else block combined with the if statement which is executed
in the false case of the condition.
If the condition is true, then the if-block is executed. Otherwise, the else-block is executed.
Python Programming Unit-2 Notes
if (condition):
# Executes this block if
# condition is true
else:
# Executes this block if
# condition is false
i = 20
if (i< 15):
print("I is smaller than 15")
print("I'm in if Block")
else:
print("I is greater than 15")
print("I'm in else Block")
print("I'm not in if and not in else Block")
I is greater than 15
I'm in else Block
I'm not in if and not in else Block
The block of code following the else statement is executed as the condition present in the if statement
is false after calling the statement which is not in block (without spaces).
Nested-if
if (condition1):
# Executes when condition1 is true
if (condition2):
# Executes when condition2 is true
# if Block is end here
# if Block is end here
Python Programming Unit-2 Notes
# Nested - if statement
# Will only be executed if statement above
# it is true
if (i< 12):
print("i is smaller than 12 too")
else:
print("i is greater than 15")
i is smaller than 15
i is smaller than 12 too
If-elif-else ladder
The if statements are executed from the top down. As soon as one of the conditions
controlling the if is true, the statement associated with that if is executed, and the rest of the ladder is
bypassed. If none of the conditions is true, then the final else statement will be executed.
if (condition):
statement
elif (condition):
statement
.
.
else:
statement
i = 15
if (i == 10):
print("i is 10")
elif (i == 15):
print("i is 15")
else:
print("i is not present")
i is 15
Python Programming Unit-2 Notes
Looping statements:
In general, statements are executed sequentially: The first statement in a function is executed
first, followed by the second, and so on. There may be a situation when you need to execute a block
of code several number of times.
Programming languages provide various control structures that allow for more complicated
execution paths.
A loop statement allows us to execute a statement or group of statements multiple times.
while loop
In python, while loop is used to execute a block of statements repeatedly until a given a condition is
satisfied. And when the condition becomes false, the line immediately after the loop in program is
executed.
while (expression) :
statement(s)
All the statements indented by the same number of character spaces after a programming construct
are considered to be part of a single block of code. Python uses indentation as its method of grouping
statements.
Hello World
Hello World
Hello World
As discussed above, while loop executes the block until a condition is satisfied. When the condition
becomes false, the statement immediately after the loop is executed.
The else clause is only executed when your while condition becomes false. If you break out of the
loop, or if an exception is raised, it won’t be executed.
Hello World
In Else Block
Python Programming Unit-2 Notes
for loop
For loops are used for sequential traversal. For example: traversing a list or string or array etc.
In Python, there is no C style for loop, i.e., for (i=0; i<n; i++). It can be used to iterate over a range
and iterators.
range() function
The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1
(by default), and stops before a specified number.
Parameter Description
n=4
for i in range(0, n):
print(i)
0
1
2
3
0 3 6 9 12 15 18 21 24 27
If a user wants to decrement, then the user needs steps to be a negative number. For example:
Python Programming Unit-2 Notes
25 23 21 19 17 15 13 11 9 7 5 3
ABC
BCD
CDE
Inside Else Block
Nested loops
Python programming language allows to use one loop inside another loop.
1
22
333
4444
Python Programming Unit-2 Notes
Current Letter : P
Current Letter : y
Current Letter : t
Current Letter : h
Current Letter : n
Break Statement: It brings control out of the loop for letter
Current Letter : P
Current Letter : y
Pass Statement: We use pass statement to write empty loops. Pass is also used for empty control
statement, function and classes.
# An empty loop
Last Letter : n
Python Programming Unit-2 Notes
Functions
Python Functions is a block of related statements designed to perform a computational,
logical, or evaluative task. The idea is to put some commonly or repeatedly done tasks together and
make a function so that instead of writing the same code again and again for different inputs, we can
do the function calls to reuse code contained in it over and over again.
Functions can be either built-in or user-defined. It helps the program to be concise, non-repetitive,
and organized.
def function_name(parameters):
statement(s)
return expression
Creating a function
We can create a Python function using the def keyword.
def fun():
print("Python Programming")
Calling a function
After creating a function we can call it by using the name of the function followed by
parenthesis containing parameters of that particular function.
def fun():
print("Python Programming")
Python Programming
Python Programming Unit-2 Notes
Types of Arguments
Python supports various types of arguments that can be passed at the time of the function call.
Let’s discuss each type in detail.
Default arguments
A default argument is a parameter that assumes a default value if a value is not provided in the
function call for that argument. The following example illustrates Default arguments.
x: 10
y: 50
Keyword arguments
The idea is to allow the caller to specify the argument name with values so that caller does not need
to remember the order of parameters.
# Keyword arguments
student(firstArg='Python', lastArg ='Practice')
student(lastArg ='Practice', firstArg='Python')
Python Practice
Python Practice
Python Programming Unit-3 Notes
Iterators
An iterator is an object that contains a countable number of values. It is an object that can be
iterated upon, meaning that you can traverse through all the values.
print("List Iteration")
l = ["ABC", "BCD", "CDE"]
for i in l:
print(i)
List Iteration
ABC
BCD
CDE
print("Tuple Iteration")
t = ("ABC", "BCD", "CDE")
for i in t:
print(i)
Tuple Iteration
ABC
BCD
CDE
print("String Iteration")
s = "ABCDE"
for i in s :
print(i)
String Iteration
A
B
C
D
E
1
Python Programming Unit-3 Notes
Python has four basic inbuilt data structures namely Lists, Tuple, Dictionary and Set.
List
Like a string, a list is a sequence of values. In a string, the values are characters; in a list, they can be
any type. The values in list are called elements or sometimes items.
There are several ways to create a new list; the simplest is to enclose the elements in square brackets
(“[” and “]”)
# Creating a List
List = [ ]
print("Blank List: ", List)
Blank List:
[]
List of numbers:
[10, 20, 30]
List Items:
Programming
Python
Multi-Dimensional List:
[['Programming', 'in'], ['Python']]
2
Python Programming Unit-3 Notes
A list may contain duplicate values with their distinct positions and hence, multiple distinct or duplicate
values can be passed as a sequence at the time of list creation.
# Creating a List with mixed type of values (Having numbers and strings)
Unlike strings, lists are mutable because you can change the order of items in a list or reassign an
item in a list. When the bracket operator appears on the left side of an assignment, it identifies
the element of the list that will be assigned.
Using len() function we can find the length (no. of elements in list) of list.
3
Python Programming Unit-3 Notes
List operation
a = [1, 2, 3]
b = [4, 5, 6]
c=a+b
print(c)
[1, 2, 3, 4, 5, 6]
a = [1]
a=a*3
print(a)
[1, 1, 1]
List slices
['b', 'c']
['a', 'b', 'c', 'd']
['d', 'e', 'f']
If you omit the first index, the slice starts at the beginning. If you omit the second, the slice
goes to the end. So, if you omit both, the slice is a copy of the whole list.
4
Python Programming Unit-3 Notes
A slice operator on the left side of an assignment can update multiple elements.
List methods
Python has a set of built-in methods that you can use on lists.
Method Description
extend() Add the elements of a list (or any iterable), to the end of the current list
index() Returns the index of the first element with the specified value
# append()
5
Python Programming Unit-3 Notes
# clear()
[]
# copy()
# count()
#extend()
fruits = ['apple', 'banana', 'cherry']
cars = ['Ford', 'BMW', 'Volvo']
fruits.extend(cars)
print(fruits)
#index()
6
Python Programming Unit-3 Notes
#insert()
#pop()
['apple', 'cherry']
#remove()
['apple', 'cherry']
#reverse()
#sort()
7
Python Programming Unit-3 Notes
Tuples
A tuple is a sequence of immutable (A tuple is a collection which is ordered and unchangeable) Python
objects. Tuples are sequences, just like lists. The differences between tuples and lists are, the tuples
cannot be changed unlike lists and tuples use parentheses, whereas lists use square brackets.
Creating a tuple is as simple as putting different comma-separated values. Optionally you can put these
comma-separated values between parentheses also. For example
# creating a tuple
tup1 = ();
To write a tuple containing a single value you have to include a comma, even though there is only one
value
tup1 = (50,);
Like string indices, tuple indices start at 0, and they can be sliced, concatenated, and so on.
Accessing Values in Tuples
To access values in tuple, use the square brackets for slicing along with the index or indices to obtain
value available at that index. For example
# accessing a tuple
tup1[0]: physics
tup2[1:5]: (2, 3, 4, 5)
8
Python Programming Unit-3 Notes
Updating Tuples
Tuples are immutable which means you cannot update or change the values of tuple elements. You
are able to take portions of existing tuples to create new tuples as the following example
demonstrates
# updating a tuple
# deleting a tuple
This produces the following result. Note an exception raised, this is because after del tup tuple does
not exist any more
9
Python Programming Unit-3 Notes
Tuple Operations
Tuples respond to the + and * operators much like strings; they mean concatenation and repetition here
too, except that the result is a new tuple, not a string
T=(1,2,3)
3 Length
print(len(T))
T=(1, 2, 3)+(4, 5, 6)
(1, 2, 3, 4, 5, 6) Concatenation
print(T)
T=('Hi!',)* 4
('Hi!', 'Hi!', 'Hi!', 'Hi!') Repetition
Print(T)
T=(1,2,3)
True Membership
Print(3 in (T))
for x in (1, 2, 3): 1
print(x) 2 Iteration
3
len() function
len() is one of the built-in functions in python. It returns the number of items in an object.
When the object is a string, the len() function returns the number of characters in the string.
10
Python Programming Unit-3 Notes
# len()
Dictionary
A dictionary is mutable and is another container type that can store any number of Python objects,
including other container types. Dictionaries consist of pairs (called items) of keys and their
corresponding values.
Python dictionaries are also known as associative arrays or hash tables. The general syntax of a
dictionary is as follows
d1 = { 'abc': 456 };
d2 = { 'abc': 123, 98.6: 37 };
Each key is separated from its value by a colon (:), the items are separated by commas, and the whole
thing is enclosed in curly braces. An empty dictionary without any items is written with just two curly
braces, like this: {}.
Keys are unique within a dictionary while values may not be. The values of a dictionary can be of any
type, but the keys must be of an immutable data type such as string s, numbers, or tuples.
Accessing Values in Dictionary
To access values in tuple, use the square brackets for slicing along with the index or indices to obtain
value available at that index. For example
# accessing a dictionary
Name: Zara
Age: 7
Class: First
11
Python Programming Unit-3 Notes
If we attempt to access a data item with a key, which is not part of the dictionary, we get an error as
follows
Updating Dictionary
You can update a dictionary by adding a new entry or item(i.e., a key-value pair), modifying an existing
entry, or deleting an existing entry as shown below in the simple example
# updating dictionary
d1 = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}; print
(d1)
d1['Age'] = 8; # update existing entry
d1['School'] = "LJP"; # Add new entry
print ("d1['Age']: ", d1['Age'])
print ("d1['School']: ", d1['School'])
print (d1)
# deleting dictionary
d1 = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};
print("Name:",d1['Name'])
del d1['Name']; # remove entry with key 'Name'
print(d1)
d1.clear(); # remove all entries in d1
print(d1)
del d1 ; # delete entire dictionary
print(d1)
12
Python Programming Unit-3 Notes
# clear()
Start Len: 2
End Len: 0
# copy()
# get()
Value: 7
Value: Never
None
13
Python Programming Unit-3 Notes
# items()
# keys()
#values()
# update()
14
Python Programming Unit-3 Notes
Set
Sets are used to store multiple items in a single variable. A set is a collection which is
unordered and unindexed. Sets are written with curly brackets.
# creating set
Note: Sets are unordered, so you cannot be sure in which order the items will appear.
# creating set
15
Python Programming Unit-3 Notes
Access Items
You cannot access items in a set by referring to an index or a key. But you can loop through the set
itemsusing a for loop, or ask if a specified value is present in a set, by using the in keyword.
cherry,banana,apple,
True
Add Items
Once a set is created, you cannot change its items, but you can add new items. To add one item to a
set usethe add() method.
To add items from another set into the current set, use the update() method.
16
Python Programming Unit-3 Notes
Remove Item
To remove an item in a set, use the remove(), or the discard() method.
{'cherry', 'banana'}
{'cherry', 'banana'}
17
Python Programming Unit-3 Notes
You can also use the pop() method to remove an item, but this method will remove the last item.
Rememberthat sets are unordered, so you will not know what item that gets removed. The return value
of the pop() method is the removed item.
cherry
{'banana', 'apple'}
set()
18
Python Programming Unit-3 Notes
Join Sets
There are several ways to join two or more sets in Python. You can use the union() method that returns
a new set containing all items from both sets, or the update() method that inserts all the items from
one set into another.
#union() method returns a new set with all items from both sets
Note: Both union() and update() will exclude any duplicate items.
19
Python Programming Unit-2 Notes
Python Classes/Objects
Python is an object-oriented programming language. Almost everything in Python is an
object, with its properties and methods. A Class is like an object constructor, or a "blueprint" for
creating objects.
Create a Class
To create a class, use the keyword class.
class MyClass:
x=5
Create Object
Now we can use the class named MyClass to create objects
p1 = MyClass()
print(p1.x)
class MyClass:
x=5
p1 = MyClass()
print(p1.x)
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person("John", 36)
print(p1.name)
print(p1.age)
John
36
class Person:
def myfunc(arg):
print("Hello my name is " + arg.name)
p1 = Person("John", 36)
p1.myfunc()
p1.age = 40
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def myfunc(self):
print("Hello my name is " + self.name)
p1 = Person("John", 36)
print(p1.age)
p1.age = 40
print(p1.age)
36
40
Hello my name is John
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def myfunc(self):
print("Hello my name is " + self.name)
p1 = Person("John", 36)
print(p1.age)
del p1.age
print(p1.age)
del p1
print (p1)
36
Inheritance
Inheritance is a way of creating a new class for using details of an existing class without modifying
it. The newly formed class is a derived class (or child class). Similarly, the existing class is a base
class (or parent class).
Inheritance is used as given below in Python:
# parent class
class Bird:
def __init__(self):
print("Bird is ready")
def who(self):
print("Bird")
def swim(self):
print("Swim faster")
# child class
class Penguin(Bird):
def __init__(self):
print("Penguin is ready")
# call super() function
super().__init__()
def who(self):
print("Penguin")
def run(self):
print("Run faster")
peggy = Penguin()
peggy.who()
peggy.swim()
peggy.run()
Penguin is ready
Bird is ready
Penguin
Swim faster
Run faster
Python Programming Unit-2 Notes
In the above program, we created two classes i.e. Bird (parent class) and Penguin (child class). The
child class inherits the functions of parent class. We can see this from the swim() method.
Again, the child class modified the behavior of the parent class. We can see this from
the whoisThis() method. Furthermore, we extend the functions of the parent class, by creating a
new run() method.
Additionally, we use the super() function inside the __init__() method. This allows us to run
the __init__() method of the parent class inside the child class.
Polymorphism
Polymorphism is an ability (in OOP) to use a common interface for multiple forms (data types).
Suppose, we need to color a shape, there are multiple shape options (rectangle, square, circle).
However we could use the same method to color any shape. This concept is called Polymorphism.
class Parrot:
def fly(self):
print("Parrot can fly")
def swim(self):
print("Parrot can't swim")
class Penguin:
def fly(self):
print("Penguin can't fly")
def swim(self):
print("Penguin can swim")
# common interface
def flying_test(bird):
bird.fly()
#instantiate objects
blu = Parrot()
peggy = Penguin()
In the above program, we defined two classes Parrot and Penguin. Each of them have a
common fly() method. However, their functions are different.
To use polymorphism, we created a common interface i.e flying_test() function that takes any object
and calls the object's fly() method. Thus, when we passed the blu and peggy objects in
the flying_test() function, it ran effectively.
Modules
In Python, a module is a self-contained Python file that contains Python statements and definitions,
like a file named GFG.py, can be considered as a module named GFG which can be imported with
the help of import statement. However, one might get confused about the difference between
modules and packages. A package is a collection of modules in directories that give structure and
hierarchy to the modules.
Creating Modules
A module is simply a Python file with a .py extension that can be imported inside another Python
program. The name of the Python file becomes the module name. The module contains definitions
and implementation of classes, variables, and functions that can be used inside another program.
# Factorial.py
def fact(n):
if n==0 or n==1:
return (1)
else:
return (n*fact(n-1))
#test.py
import Factorial
n=int(input(“Enter the value: “))
print(Factorial.fact(n))
Now enter the Python interpreter and import this module with the following command:
Python pip is the package manager for Python packages. We can use pip to install packages that do
not come with Python. The basic syntax of pip commands in command prompt is:
pip 'arguments'
Python pip comes pre-installed on 3.4 or older versions of Python. To check whether pip is installed
or not type the below command in the terminal.
pip --version
This command will tell the version of the pip if pip is already installed in the system.
We can install additional packages by using the Python pip install command. Let’s suppose we want
to install the numpy using pip. We can do it using the below command.
The Python pip list command displays a list of packages installed in the system.
pip list
Python Programming Unit-2 Notes
The pip uninstall command does not uninstall the package dependencies. If you want to remove the
dependencies as well then you can see the dependencies using the pip show command and remove
each package manually.
PyPI
The Python Package Index, abbreviated as PyPI, is the official repository of software for the Python
programming language. By default, pip — which is the most popular Python package manager —
uses PyPI as the source for retrieving package dependencies.
PyPI lets you find, install and even publish your Python packages so that they are widely available to
the public. More than 300,000 different packages are currently published in the index with more than
2,500,000 releases being distributed to users.
Python Programming Unit-5 Notes
Pathlib module in Python provides various classes representing file system paths with semantics
appropriate for different operating systems. This module comes under Python’s standard utility
modules.
Path class is a basic building block to work with files and directories.
Path(“C:\\Program Files\Microsoft”)
We can also create a Path object that represents a current directory like:
Path()
We can also get the home directory of current user using home method.
Path.home( )
path = Path(“D://testmodule/test.txt”)
path.exists()
We can also check if the path represents a file or not.
path.is_file()
Python Programming Unit-5 Notes
path.is_dir()
print(path.name)
print(path.stem)
print(path.suffix)
print(path.parent)
print(path.absolute())
path = Path(“test”)
path.mkdir(‘name’)
path.rmdir(‘name’)
path.rename(“abc”)
Now, to iterate through all the files and directories we can use the following code.
for p in path.iterdir():
print(p)
Python Programming Unit-5 Notes
Above code shows all the directories and files on the mentioned path. So, if we want to see just the
directories, we can use:
for p in path.iterdir():
if p.is_dir():
print(p)
This method has two limitations. It can not search by patterns and it can not search recursively. So, to
overcome this limitation, we can use glob method.
To see how we can work with files, let us refer to the file we want to work with using Path class
object.
path = Path(“D://testmodule/test.txt”)
path.exists()
path.rename(“init.txt”)
path.unlink()
print(path.stat())
print(path.read_text())
path.write_text(“Hello All”)
Python Programming Unit-5 Notes
CSV stands for Comma Separated Values which is a file that stores the values separated with
comma. They serve as simple means to store and transfer data.
import csv
We can open a csv file and write into it by using built in open function.
file = open(“data.csv”,”w”)
Now, this csv module has writer method to write content into csv file.
writer = csv.writer(file)
Now, we can use writer to write tabular data into csv file. For this, we need to use writerow method
to which we need to pass values in form of array.
write.writerow([“transaction_id”,”product_id”,”price”])
write.writerow([1000,1,5])
write.writerow([1001,2,15])
file.close()
Here, we have created three rows with three columns in a csv file.
Now, we can read the csv file using reader method. First, we need to open the file in read mode. For
that we do not require to pass the mode in second parameter. After opening the file, we can use
reader method to read the file. Once file has been read, we convert it into list using list method. And
then we can iterate through that list to read the content of csv file.
file = open(“data.csv”)
reader = csv.reader(file)
reader = list(reader)
print(row)
Python Programming Unit-5 Notes
There are two modules which we can use to work with date and time. time and datetime. time refers
to the current timestamp, which represents the number of seconds passed after the time started, which
is usually 1stJanuary, 1970.
import time
time1 = time.time()
curr = time.ctime(time1)
print(“current time”,curr)
Output:
This statement will print the number of seconds passed after the date and time mentioned above.
This method can be used to perform time calculations such as duration to perform some task.
To work with date and time, we can use datetime class of datetime module.
Now, we can create a datetime object by mentioning year, month and day. Optionally we can
mention hour, minutes and seconds too.
print(dt)
Output:
2022-12-25 00:00:00
We can also create a datetime object which represents the current date and time.
dt = datetime.now()
print(dt)
Output:
2022-11-23 09:32:02.429447
Python Programming Unit-5 Notes
While taking input from user or reading from s file we deal with strings. So, when we read date or
time from such sources, we need to convert this input to datetime object. We can use strptime
method for this purpose.
Let us assume that we received a date 2022/12/25 as a string input. To convert it to datetime object,
we need to specify which part of full date represents what. So, we can do that by writing:
dt = datetime.strptime("2022/12/25", "%Y/%m/%d")
print(dt)
Output:
2022-12-25 00:00:00
Where, %Y, %m and %d are directives to represent four-digit year, two-digit month and two-digit
date respectively.
We can use strftime method to do excat opposite, i.e. convert datetime object to string.
dt = datetime(2022,12,25)
print(dt.strftime("%Y/%m/%d"))
Output:
2022/12/25
Similarly, we can convert timestamp into datetime object using fromtimestamp() method.
import time
dt = datetime.fromtimestamp(time.time())
datetime object has properties like year and month which we can use to print year and month.
print(dt.year)
print(dt.month)
Output:
2022
11
Python Programming Unit-5 Notes
We can also compare two datetime objects to know which date is greater.
dt1 = datetime(2022,1,1)
dt2 = datetime(2022,12,25)