Python Notes
Python Notes
Dear Students,
Please be informed that the notes provided by the institute
offer a concise presentation of the syllabus. While these notes
are helpful for an overview and quick revision, We would
strongly suggest that you refer to the prescribed textbooks /
Reference book for a comprehensive understanding and
thorough preparation of all exams and writing in the
examination.
Best regards,
LJ Polytechnic.
પ્રિય પ્રિદ્યાર્થીઓ,
એલજે પોક્ષલટેકપ્રનક.
Python Programming Unit-1 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.
1
Python Programming Unit-1 Notes
interpreted, and hence need to be compiled first to run them. There is no need to compile
Python because it is processed at runtime by the interpreter.
• Portable
Python is portable in the sense that the same code can be used on different machines.
Suppose you write a Python code on a Mac. If you want to run it on Windows or Linux later,
you don’t have to make any changes to it.
• Object-Oriented and Procedure-Oriented
A programming language is object-oriented if it focuses design around data and objects,
rather than functions and logic. On the contrary, a programming language is procedure-
oriented if it focuses more on functions (code that can be reused). One of the critical Python
features is that it supports both object-oriented and procedure-oriented programming.
• Extensible
A programming language is said to be extensible if it can be extended to other languages.
Python code can also be written in other languages like C++, making it a highly extensible
language.
• Expressive Language
Python can perform complex tasks using a few lines of code. A simple example, the hello
world program you simply type print ("Hello World"). It will take only one line to execute,
while Java or C takes multiple lines.
• Support for GUI
One of the key aspects of any programming language is support for GUI or Graphical
User Interface. A user can easily interact with the software using a GUI. Python offers
various toolkits, such as Tkinter, wxPython and JPython, which allows for GUI's easy and
fast development.
• Dynamically Typed
Many programming languages need to declare the type of the variable before runtime.
With Python, the type of the variable can be decided during runtime. This makes Python a
dynamically typed language.
• High-level Language
Python is a high-level programming language because programmers don’t need to
remember the system architecture, nor do they have to manage the memory. This makes it
super programmer-friendly and is one of the key features of Python.
3
Python Programming Unit-1 Notes
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.
Note: For all users, especially Windows OS users, it is highly recommended that you install
Anaconda, which can be downloaded from https://www.anaconda.com/
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’.
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
Example:
>>> type ('Hello, World!')
<class 'str'>
>>> type (1)
<class 'int'>
>>> type (2.2)
<class 'float'>
>>> print (''Abc@123'')
<class 'str'>
7
Python Programming Unit-1 Notes
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)
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
x = “LJ Polytechnic” LJ Polytechnic
print(x)
4. Python allows assigning a single value to several variables simultaneously with “=”
operators.
Example: Output:
x = y = z = 100
100
print(y)
Keywords:
The interpreter uses keywords to recognize the structure of the program, and they cannot be used
as variable names. Python reserves 35 keywords:
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 datatype, 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.
9
Python Programming Unit-1 Notes
Example: Output:
s = 'P'
print(s)
type(s) P
<class ‘str’>
language = 'Python' Python
print(language) <class ‘str’>
type(language)
String Indexing:
[0] [1] [2] [3] [4] [5]
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:
• 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.
Example: Output:
x = "Python"
length = len(x)
y=x[length-1] n
print(y)
10
Python Programming Unit-1 Notes
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.
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 11
UJ teolW
Python Programming Unit-1 Notes
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.
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.
12
Python Programming Unit-1 Notes
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.
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.
String Concatenation
Strings can be concatenated (glued together) with the + operator, and repeated with *:
>>>3*'un'
'ununun'
>>>'Py''thon'
'Python'
>>>'Py'+'thon'
'Python'
14
Python Programming Unit-1 Notes
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.
\\ 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)) 15
<class 'complex'>
Python Programming Unit-1 Notes
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))
<class 'int'>
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))
16
Python Programming Unit-1 Notes
Type Conversion
You can convert from one type to another with the int(), float(), and complex() methods.
Example: Output:
x = 1 # int
y = 2.8 # float
z = 1j # complex
a = float(x) # convert from int to float 1.0
b = int(y) #convert from float to int <class 'float'>
c = complex(x) #convert from int to complex 2
print(a) <class 'int'>
print(type(a)) (1+0j)
print(b) <class 'complex'>
print(type(b))
print(c)
print(type(c))
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.
17
Python Programming Unit-1 Notes
Example: Output:
a = 21
b = 10
c=0
c=a+b
print("Addition is:", c)
c=a-b
print('Subtraction is:', c)
c=a*b Addition is: 31
print('Multiplication is:', c) Subtraction is: 11
c=a/b Multiplication is: 210
print('Division is:', c) Division is: 2.1
c=a%b Reminder of a/c is: 1
print("Reminder of a/c is:", c) result of p^q is: 8
p=2 result of a divide b is: 2
q=3
r =p**q
print("result of p^q is:", r)
x = 11
y=5
z = a//b
print("result of a divide b is:", z)
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 the x > y
right
< Less than: True if the left operand is less than the right x<y
>= Greater than or equal to True if the left operand is greater x >= y
than or equal to the right
<= Less than or equal to True if the left operand is less than or x <= y
equal to the right
18
Python Programming Unit-1 Notes
Example:
>>> # Examples of Relational Operators
>>> a, b = 13, 33
>>> # a == b is False
>>> print(a == b)
False
>>> # a != b is True
>>> print(a != b)
True
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
print(x>3 and x>10) #and False
print (x>3 or x>10) #or True
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 of bits x>>
Bitwise right specified by the right operand.
shift
<< The left operands value is moved right by the number of bits x<<
Bitwise left specified by the right operand.
shift
Example: Output:
Assignment Operators
Assignment operators are used to assigning values to the variables.
+= Add AND: Add right-side operand with left side operand and then assign to a +=b
left operand a=a+b
-= Subtract AND: Subtract right operand from left operand and then assign to a -=b
left operand a=a - b
*= Multiply AND: Multiply right operand with left operand and then assign to a *=b
left operand a=a * b
/= Divide AND: Divide left operand with right operand and then assign to left a /=b
operand a=a / b
%= Modulus AND: Takes modulus using left and right operands and assign the a %=b
result to left operand a=a % b
//= Divide(floor) AND: Divide left operand with right operand and then assign a /=b
the value(floor) to left operand a=a // b
**= Exponent AND: Calculate exponent(raise power) value using operands and a **=b
assign value to left operand a=a ** b
&= Performs Bitwise AND on operands and assign value to left operand a &=b
a=a&b
^= Performs Bitwise XOR on operands and assign value to left operand a ^=b
a=a ^ b
>>= Performs Bitwise right shift on operands and assign value to left operand a >>=b
a=a>>b
<<= Performs Bitwise left shift on operands and assign value to left operand a <<=b
a=a<<b
21
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
>>> print (a is not b)
True
>>> print (a is c)
True
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: Output:
#membership_ex.py
x = 24
y = 20
list = [10, 20, 30, 40, 50]
if (y in list):
print("y is present in given list")
else: 22
print("y is NOT present in given list")
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 block")
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
A nested if is an if statement that is the target of another if statement. Nested if statements
mean an if statement inside another if statement. Python allows us to nest if statements within if
statements. i.e., we can place an if statement inside another if statement.
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.
for variable_name in range (start, stop, step):
statement(s)
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
Python Programming Unit-2 Notes
If a user wants to decrement, then the user needs steps to be a negative number. For example:
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 given condition.
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.
The syntax of the user-defined fuction is given below.
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
def local():
s="Python local variable"
print(s)
local()
def local():
s="Python local variable"
print("Inside: ", s)
local()
print("Outside: ", s)
Global variables in Python are outside any function and accessible throughout the
program.
i.e., inside and outside of every function.
def glob():
print("Inside: ", s)
s="Python global variable"
glob()
print("Outside: ", s)
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.
Python Programming Unit-2 Notes
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
Built-in function:
Function Description
len() Returns the number of items in an object
lambda() It can take any number of arguments, but can only have one expression.
Python Programming Unit-2 Notes
#len()
x = (3,12,9,6,15)
print (''length of x: '', len(x))
y = (''Hello'', ''How'', ''Happy'')
print (''length of y: '', len(y))
z = (''Hello'')
print (''length of z: '', len(z))
length of x: 5
length of y: 3
length of z: 5
#min()
x = min (3,12,9,6,15)
print (''minimum value: '', x)
y = min (''Ujjain'', ''Ahmedabad'', ''Mumbai'', ''Surat'')
print (''minimum value: '', y)
minimum value: 3
minimum value: Ahmedabad
#max()
x = max (3,12,9,6,15)
print (''maximum value: '', x)
y = max (''Hello'', ''How'', ''Happy'')
print (''maximum value: '', y)
maximum value: 15
maximum value: How
pow() function:
It returns the value of x to the power of y. [xy]. If a third parameter is present, it returns x to
the power of y, modulus z.
pow (x, y, z)
Parameters Description
x A number, the base
# pow()
x = pow(2, 3)
print ("power of 2 raise to 3: ", x)
x = pow(2, 3, 3)
print ("power of 2 raise to 3, modulus 3: ", x)
power of 2 raise to 3: 8
power of 2 raise to 3, modulus 3: 2
lambda() function:
A lambda function is a small anonymous function. It can take any number of arguments,
but can only have one expression. Anonymous function are not defined using def keyword rather
they are defined using lambda keyword.
# lambda()
x = lambda a : a + 10
print("addition:", x(5))
z=lambda p, q : p * q + p / p
print("operation:", z(2, 2))
addition: 15
multiplication: 20
operation: 5.0
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
[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
a = [1, 2, 3]
b=a
print (a is b)
b[1] = 4
print("list of a:", a)
print("list of b:", b)
True
list of a: [1, 4, 3]
list of b: [1, 4, 3]
Cloning a list, creates a copy of the original list. The new list can be changed without
changing the original.
slicing Technique copy() method
a = [1, 2, 3] a = [1, 2, 3]
b = a[:] b = a.copy()
print ("original list of a:", a) print ("original list of a:", a)
print ("original list of b:", b) print ("original list of b:", b)
a[0] = 10 b[0] = 10
print ("updated list of a:", a) print ("updated list of a:", a)
print ("updated list of b:", b) print ("updated list of b:", b)
8
Python Programming Unit-3 Notes
Tuples
A tuple is a sequence of immutable (A tuple is a collection which is ordered and
unchangeable) Pythonobjects. 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
thesecomma-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.
Nested Tuples
A tuple written inside another tuple is nested tuple.
#nested tuple
1
2500
((1, 'abc', 2000), (2, 'xyz', 2500))
9
Python Programming Unit-3 Notes
# accessing a tuple
tup1[0]: physics
tup2[1:5]: (2, 3, 4, 5)
Updating Tuples
Tuples are immutable which means you cannot update or change the values of tuple
elements. Youare able to take portions of existing tuples to create new tuples as the following
example demonstrates
# updating a tuple
10
Python Programming Unit-3 Notes
# deleting a tuple
This produces the following result. Note an exception raised, this is because after del tup tuple
does not exist any more
Tuple Operations
Tuples respond to the + and * operators much like strings; they mean concatenation and
repetition heretoo, 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))
1
for x in (1, 2, 3):
2 Iteration
print(x)
3
11
Python Programming Unit-3 Notes
Tuple methods
Python has a set of built-in methods that you can use on tuples.
Method Description
index() Returns the index of the first element with the specified value
num = (1, 2, 2, 3, 1, 2, 5)
num1 = num.count(2)
num2 = num.index(2)
print("count of 2:", num1)
print("index of 2:", num2)
count of 2: 3
index of 2: 1
12
Python Programming Unit-3 Notes
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 wholething is enclosed in curly braces. An empty dictionary without any items is written
with just two curlybraces, like this: {}.
Keys are unique within a dictionary while values may not be. The values of a dictionary
can be of anytype, 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 obtainvalue available at that index. For example
# accessing a dictionary
Name: Zara
Age: 7
Class: First
If we attempt to access a data item with a key, which is not part of the dictionary, we get an
error as follows
13
Python Programming Unit-3 Notes
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 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)
Name: Zara
{'Age': 7, 'Class': 'First'}
{}
Traceback (most recent call last):
File "D:/LJ/Python/Code/LJ/Chapter 3/testing.py", line 9, in
<module>
print(d1)
NameError: name 'd1' is not defined
14
Python Programming Unit-3 Notes
# clear()
Start Len: 2
End Len: 0
# pop()
# copy()
15
Python Programming Unit-3 Notes
# get()
Value: 7
Value: Never
None
{'Name': 'Zara', 'Age': 7}
# setdefault()
# items()
# keys()
16
Python Programming Unit-3 Notes
#values()
# update()
#fromkeys
seq = 1, 2, 3
value = "new"
d1 = dict.fromkeys(seq)
d2 = dict.fromkeys(seq, value)
print("Without 2nd parameter:", d1)
print("With 2nd parameter:", d2)
17
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
18
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
Method Description
s1.add(item) To add one item to a set
s1.remove(item) To remove an item in a set
s1.discard(item) Removes the specified item from the set
s1.pop() Removes a random item from the set
s1.clear() Removes all elements in a set
s1.update(s2) Updates the current set, by adding items from another set
s1.union(s2) Returns a new set containing all items from both sets
Return a set that contains the items that exist in both s1 and
s1.intersection(s2)
s2
s1.intersection_update(s2) Remove the items that is not present in both s1 and s2
Return a set that contains the items that only exist in s1,
s1.difference(s2)
and not in s2
Remove the items that exists in both sets and store unique
s1.difference_update(s2)
one.
19
Python Programming Unit-3 Notes
{'cherry', 'banana'}
{'cherry', 'banana'}
apple
{'banana', 'cherry'}
20
Python Programming Unit-3 Notes
set()
#union() method returns a new set with all items from both sets
s1 = {"a", "b","c"}
s2 = {1, 2, 3}
s3 = s1.union(s2)
print(s3)
Note: Both union() and update() will exclude any duplicate items.
#intersection() method returns set that contains the items that exist in both s1 and s2
{'a'}
21
Python Programming Unit-3 Notes
#difference() method return a set that contains the items that only exist in s1, and not in s2
{'b'}
#difference_update() method remove the items that exists in both sets and store unique one.
22
Python Programming Unit-3 Notes
23
Python Programming Unit-4 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)
p1.myfunc()
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-4 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 who() 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.
def fact(n):
if n==0 or n==1:
return (1)
else:
return (n * fact(n-1))
import Factorial_module
n = int(input("Enter the value: "))
print(Factorial_module.fact(n))
Now enter the Python interpreter and import this module with the following command:
Python pip (Preferred Installer Program) 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-4 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”)
import os
os.mkdir(‘name’)
os.rename(“name”, “rename”)
os.rmdir(‘name’)
Now, to iterate through all the files and directories we can use the following code.
Python Programming Unit-5 Notes
print(item) print(item)
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 cannot search by patterns and it cannot 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”)
print(path.stat())
path.write_text(“Hello All”)
print(path.read_text())
path.unlink()
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.
content = 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.
content.writerow([“transaction_id”,”product_id”,”price”])
content.writerow([1000,1,5])
content.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”)
read1 = csv.reader(file)
Python Programming Unit-5 Notes
read2 = list(read)
print(row)
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)
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.
Output:
We can also create a datetime object which represents the current date and time.
dt = datetime.now()
Output:
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")
Output:
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.datetime(2022,12,25)
Output:
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.
Python Programming Unit-5 Notes
Output:
We can also compare two datetime objects to know which date is greater.
dt1 = datetime.datetime(2022,1,1)
dt2 = datetime.datetime(2022,12,25)