0% found this document useful (0 votes)
7 views67 pages

Python Notes

Python is an open-source, high-level programming language known for its simplicity and versatility, supporting both object-oriented and procedure-oriented programming. It has a rich history dating back to the late 1980s and offers features like an extensive standard library, portability, and dynamic typing. Python is widely used in various domains including web development, data analysis, automation, and software testing.

Uploaded by

Owais Khan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
7 views67 pages

Python Notes

Python is an open-source, high-level programming language known for its simplicity and versatility, supporting both object-oriented and procedure-oriented programming. It has a rich history dating back to the late 1980s and offers features like an extensive standard library, portability, and dynamic typing. Python is widely used in various domains including web development, data analysis, automation, and software testing.

Uploaded by

Owais Khan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 67

Python Programming Unit-1 Notes

CHAPTER 1- Python Introduction


What is Python?
 Python is an open source, dynamic, high-level and interpreted programming language. It
supports Object Oriented programming approach to develop applications. It is simple and
easy to learn and provides lots of high-level data structures.
 It is a general-purpose language; it means that it can be used to create a variety of different
programs and isn’t specialized for any specific problems.

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.

Python Features and Advantages:


 Easy to Code and Easy to Read
Python is easy to learn as compared to other programming languages. Its syntax is
straight forward and much the same as the English language. There is no use of the
semicolon or curly-bracket.
 Free and Open-Source
Python is developed under an OSI-approved open-source license. Hence, it is
completely free to use, even for commercial purposes. It doesn't cost anything to
download Python or to include it in your application.
 Robust Standard Library
Python has an extensive standard library available for anyone to use. This means that
programmers don’t have to write their code for every single thing unlike other
programming languages. There are libraries for image manipulation, databases, unit-
testing, expressions and a lot of other functionalities.
 Interpreted
When a programming language is interpreted, it means that the source code is
executed line by line, and not all at once. Programming languages such as C++ or Java
are not interpreted, and hence need to be compiled first to run them. There is no need to
1
Python Programming Unit-1 Notes

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.

What is use of Python?


Python is commonly used for developing websites and software, task automation, data
analysis, and data visualization.

What can we do with Python?

1) Data analysis and machine learning


Python has become a staple in data science, allowing data analysts and other
professionals to use the language to conduct complex statistical calculations, create data visualizations,
build machine learning algorithms, manipulate and analyze data, and complete other data-related tasks.

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.

4) Software testing and prototyping


In software development, Python can aid in tasks like build control, bug tracking, and testing.
With Python, software developers can automate testing for new products or features. Some
Python tools used for software testing include Green and Requestium.

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

Python interpreter, extension & implementations


Computers cannot understand code in the way humans write it and hence, you need an
interpreter between the computer and the human written code. The job of the interpreter is to convert
the code into a format that computers can then understand and process.

The interpreter processes the code in the following ways:


 Processes the Python script in a sequence.

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.

Installing Python on Windows takes a series of few easy steps.

Step 1 − Select Version of Python to Install


Python has various versions available with differences between the syntax and working of
different versions of the language. We need to choose the version which we want to use or need.

Step 2 − Download Python Executable Installer


On the web browser, in the official site of python www.python.org ,move to the Download
for Windows section.
All the available versions of Python will be listed. Select the version required by you and
click on Download.

Step 3 − Run Executable Installer


Run the installer. The installation process will take few minutes to complete.

Step 4 − Verify Python is installed on Windows


To ensure if python is successfully installed on your system.
Follow the given steps −
 Open the command prompt.
 Type ‘python’ and press enter.
 The version of the python which you have installed will be displayed if the python is
successfully installed on your windows.

Step 5 − Verify Pip was installed


Pip is a powerful package management system for Python software packages. Thus, make sure that
you have it installed.
To verify if pip was installed, follow the given steps −
 Open the command prompt.
 Enter pip –V to check if pip was installed.
 The following output appears if pip is installed successfully.
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/

4
Python Programming Unit-1 Notes

Python Program Execution

List out Different ways to run Python Script


Here are the ways with which we can run a Python script.
1. Interactive Mode –
We have to write code in command prompt line by line.
To enter in an interactive mode, you will have to open Command Prompt on your windows
machine and type ‘python’ and press Enter.

Run the following line one by one in the interactive mode:

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

3. Text Editor (Example:-Notepad++, VS Code, etc..)


4. IDE (Examples :- IDLE, Spyder, Atom, PyCharm, etc..)

Values and types:-


A value is one of the basic things a program works with, like a letter or a number.
A value may be characters i.e. ‘Hello, World!’ or a number like 1, 2.2, 0.9 etc.

To print the value print() function is used.

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.

Example:- >>> type('Hello, World!')


<class 'str'>
>>> type(1)
<class 'int'>
>>> type(2.2)
<class 'float'>
>>> print(''Abc@123'')
<class 'str'>

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)

5. Assigning different values to multiple variables:


Python allows adding different values in a single line with “,”operators.
Example:-
a, b, c = 1, 2.2, 'ABC' Output:-
print(a) 1
print(b) 2.2
print(c) ABC

6. How does + operator work with variables?


Example:- Output:-
a = 10
30
b = 20
LJKU
print(a+b)
x = 'LJ'
y = 'KU'
print(x+y)

Can + Operator work with different type variable?


No it can throw an error.
Example:- Output:-
a = 10 TypeError: unsupported operand
b = 'LJ' type(s) for +: 'int' and 'str'
print(a+b)

8
Python Programming Unit-1 Notes

Rules for creating variables in Python:


1. A variable name must start with a letter or the underscore character.
2. A variable name cannot start with a number.
3. A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9,
and _).
4. Variable names are case-sensitive (name, Name and NAME are three different variables).
5. The reserved words (keywords) cannot be used to naming the variable.
The interpreter uses keywords to recognize the structure of the program, and they cannot be used
as variable names. Python reserves 35 keywords:

Keywords:-
and del from none true continue lambda

as elif global nonlocal try def is

assert else if not while finally return

break except in or with for async

class false import pass yield raise wait

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

[0] [1] [2] [3] [4] [5]

String:- P y t h o n
[-6] [-5] [-4] [-3] [-2] [-1]

 Square brackets can be used to access elements of the string.


Example:- Output:-
language = 'Python'
letter = language[1] y
print(letter) P
n
print(language[0]) TypeError: string indices must be
print(language[-1]) integers
print(language[1.5])

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])

#bydefault starting index is "0" and middle index in "lenght of string"


print(s[:])
print(s[0:])

#if we can write same digit at both place then it will not give us any output
print(s[3:3])

#Replace any latter with any index of given string.


r = 'J' + s[1:]
print(r)

#if we write -1 at step place it will give output as reverse of string


print(s[ : :-1])

#For step jumping


print(s[0: :2])#it will give output as skip 1 character from starting of string

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.

>>>s = 'heLlo pYthOn'


>>> s2 = s.capitalize()
>>> print(s2)
Hello python

lower( )
This method converts all alphabetic characters to lowercase.

>>>s = 'heLlo pYthOn'


>>> s2 = s.lower()
>>> print(s2)
hello python

upper( )
This method converts all alphabetic characters to uppercase.

>>>s = 'heLlo pYthOn'


>>> s2 = s.upper()
>>> print(s2)
HELLO PYTHON

title( )
This method converts the first letter of each word to uppercase and remaining letters to
lowercase

>>>s = 'heLlo pYthOn'


>>> s2 = s.title()
>>> print(s2)
Hello Python

swapcase([<chars>])
This method swaps case of all alphabetic characters.

>>>s = 'HeLlo PyThOn'


>>> s2 = s.swapcase ()
>>> print(s2)
hElLO pYtHoN
12
Python Programming Unit-1 Notes

count(<sub>, <start>, <end>)


This method returns the number of time <sub> occurs in string.

>>>s = 'Python Programming'


>>>s.count('P')
2
>>>s.count('mm')
1
>>>s.count('P',3,10)
1

find(<sub>, <start>, <end>)


This method returns the index of the first occurrence of <sub> in s. Returns -1 if the substring is not
present in the string.

>>>s = 'Python Programming'


>>>s.find('Pro')
7
>>>s.find('on',3,10)
4
lstrip( )
This method removes leading characters from a string. Removes leading whitespaces if you don’t
provide a <chars> argument.

>>>s = ' Python '


>>>s.lstrip()
'Python '

rstrip( )
This method removes trailing characters from a string. Removes trailing whitespaces if you don’t
provide a <chars> argument.

>>>s = ' Python '


>>>s.rstrip()
' Python'

strip( )
This method removes leading and trailing characters from a string. Removes leading and
trailing whitespaces if you don’t provide a <chars> argument

>>>s = ' Python '


>>>s.strip() 13
'Python'
Python Programming Unit-1 Notes

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.

>>>s = 'Python Programming'


>>>s.split()
['Python', 'Programming']
>>>s = 'Python Programming'
>>>s.split('o')
['Pyth', 'n Pr', 'gramming']

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.

>>>s = ''we are the so-called ''Vikings'' from the north''


SyntaxError: invalid syntax

To fix this problem, use the escape character \"

>>>s = ''we are the so-called \''Vikings\'' from the north''


'we are the so-called ''Vikings'' from the north'

14
Python Programming Unit-1 Notes

List of escape sequences available in Python 3:


Code Result Code Result

\' Single Quote \t Tab

\\ Backslash \b Backspace

\n New Line \f Form Feed

\r Carriage Return \ooo Octal value

\xhh Hex value

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.

>>>x = 1.10 >>>x = 35e3


>>>y = 1.0 >>>y = 12E4
>>>z = -35.59 >>>z = -87.7e100
>>>print(type(x)) >>>print(type(x))
<class 'float'> <class 'float'>
>>>print(type(y)) >>>print(type(y))
<class 'float'> <class 'float'>
>>>print(type(z)) >>>print(type(z))
<class 'float'> <class 'float'>

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.

Operator Description Syntax

+ Addition: adds two operands x+y

- Subtraction: subtracts two operands x–y

* Multiplication: multiplies two operands x*y

/ Division (float): divides the first operand by the x / y


second

// Division (floor): divides the first operand by the x // y


second

% Modulus: returns the remainder when the first x % y


operand is divided by the second

** Power: Returns first raised to power second x ** y

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.

Operator Description Syntax

> 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

== Equal to: True if both operands are equal x == y

!= Not equal to – True if operands are not equal x != y

>= Greater than or equal to True if the left operand is x >= y


greater than or equal to the right

<= Less than or equal to True if the left operand is less x <= y
than or equal to the right
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

>>># 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.

Operator Description Syntax

and Logical AND: True if both the operands are true x and y

or Logical OR: True if either of the operands is true x or y

not Logical NOT: True if the operand is false Not x

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

& Operator copies a bit to the result if it exists in both x & y


Bitwise AND operands (means 0000 1100)

| It copies a bit if it exists in either operand. x | y = 61 (means


Bitwise OR 0011 1101)

~ It copies the bit if it is set in one operand but not ~x


Bitwise NOT both.

^ It is unary and has the effect of 'flipping' bits. x^y


Bitwise XOR

>> The left operands value is moved left by the number x>>
Bitwise right of bits specified by the right operand.
shift

<< The left operands value is moved right by the x<<


Bitwise left number of bits specified by the right operand.
shift

19
Python Programming Unit-1 Notes

Example: Output:

>>># Examples of Bitwise operators


a = 60 # 60 = 0011 1100
b = 13 # 13 = 0000 1101
Answer of a & b is:- 12
c=0
Answer of a | b is:- 61
Answer of a ^ b is:- 49
c=a&b # 12 = 0000 1100
Answer of ~60 is:- -61
print('Answer of a & b is:-',c)
Answer of a<<2 is:- 240
Answer of a>>2 is:- 15
c=a|b # 61 = 0011 1101
>>>
print('Answer of a | b is:-',c)

c=a^b # 49 = 0011 0001


print('Answer of a ^ b is:-',c)

c = ~a # -61 = 1100 0011


print('Answer of ~60 is:-',c)

c = a << 2 # 240 = 1111 0000


print('Answer of a<<2 is:-',c)

c = a >> 2 # 15 = 0000 1111


print('Answer of a>>2 is:-',c)

Assignment Operators
Assignment operators are used to assigning values to the variables.

Operator Description Syntax

= Assign value of right side of expression to left side x = y + z


operand

+= Add AND: Add right-side operand with left side a +=b


operand and then assign to left operand a=a+b

-= Subtract AND: Subtract right operand from left a -=b


operand and then assign to left operand a=a - b

*= Multiply AND: Multiply right operand with left a *=b


operand and then assign to left operand a=a * b

20
Python Programming Unit-1 Notes

/= Divide AND: Divide left operand with right operand a /=b


and then assign to left operand a=a / b

%= Modulus AND: Takes modulus using left and right a %=b


operands and assign the result to left operand a=a % b

//= Divide(floor) AND: Divide left operand with right a /=b


operand and then assign the value(floor) to left a=a // b
operand

**= Exponent AND: Calculate exponent(raise power) a **=b


value using operands and assign value to left operand a=a ** b

&= Performs Bitwise AND on operands and assign value a &=b


to left operand a=a&b

|= Performs Bitwise OR on operands and assign value to a |=b


left operand a=a | b

^= Performs Bitwise XOR on operands and assign value a ^=b


to left operand a=a ^ b

>>= Performs Bitwise right shift on operands and assign a >>=b


value to left operand a=a>>b

<<= Performs Bitwise left shift on operands and assign a <<=b


value to left operand a=a<<b

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

is True if the operands are identical

is not True if the operands are not identical

>>> a = 10
>>> b = 20
>>> c = a

>>> print(a is not b)


True
>>> print(a is c)
True
21
Python Programming Unit-1 Notes

Membership Operators

in and not in are the membership operators; used to test whether a value or variable is in a
sequence.

Operator Description

in True if value is found in the sequence

in not True if value is not found in the sequence

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:-

x is NOT present in given list


y is present in given list

22
Python Programming Unit-1 Notes

Precedence and Associativity of Operators


Operator precedence and associativity determine the priorities of the operator.
Operator Precedence
This is used in an expression with more than one operator with different precedence to determine
which operation to perform first.

>>> # Precedence of '+' & '*'


>>> expr = 10 + 20 * 30
>>> print(expr)
610

>>> # Precedence of 'or' & 'and'


>>> name = "Alex"
>>> age = 0

>>> if name == "Alex" or name == "John" and age >= 2:


... print("Hello! Welcome.")
. . . else:
... print("Good Bye!!")
Hello! Welcome.

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

CHAPTER 2- Control flow & Function in Python

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.

The syntax of the if-statement is given below.

if (condition):
#statement1
#extra statements....
#statement2

# Here if the condition is true, if block


# will consider only statement1 and extra statements to be inside its block.
# statement 2 is outside of if block.

Example:-

# Python program to illustrate If statement

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

# Python program to illustrate If else statement

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

# Python program to illustrate nested If statement


i = 10
if (i == 10):
# First if statement
if (i< 15):
print("i is smaller than 15")

# 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

# Python program to illustrate if-elif-else ladder

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.

# Python program to illustrate while loop


count = 0
while count <3 :
count = count + 1
print("Hello World")

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.

#Python program to illustrate combining else with while


count = 0
while (count < 1):
count = count + 1
print("Hello World")
else:
print("In Else Block")

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.

range(start, stop, step)

Parameter Description

Start Optional. An integer number specifying at which position to start. Default is


0

Stop Required. An integer number specifying at which position to stop (not


included).

Step Optional. An integer number specifying the incrementation. Default is 1

# Python program to illustrate Iterating over range 0 to n-1

n=4
for i in range(0, n):
print(i)

0
1
2
3

# Using range to print number divisible by 3


for i in range(0, 30, 3):
print(i, end=" ")

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

# Python program to decrement with range()


# incremented by -2

for i in range(25, 2, -2):


print(i, end=" ")

25 23 21 19 17 15 13 11 9 7 5 3

Using else statement with for loops


We can also combine else statement with for loop like in while loop. But as there is no
condition in for loop based on which the execution will terminate so the else block will be executed
immediately after for block finishes execution.

# Python program to illustrate combining else with for

list = ["ABC", "BCD", "CDE"]


for index in range(len(list)):
print(list[index])
else:
print("Inside Else Block")

ABC
BCD
CDE
Inside Else Block

Nested loops
Python programming language allows to use one loop inside another loop.

# Python program to illustrate nested for loops

for i in range(1, 5):


for j in range(i):
print(i, end=' ')
print()

1
22
333
4444
Python Programming Unit-2 Notes

Loop Control Statements


Loop control statements change execution from its normal sequence. When execution leaves
a scope, all automatic objects that were created in that scope are destroyed. Python supports the
following control statements.

Continue Statement: It returns the control to the beginning of the loop

# Prints all letters except 'e' and 'o'



for letter in 'Python':
if letter == 'e' or letter == 'o':
continue
print('Current Letter :', letter)

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

# Break the loop as soon it sees 't'

for letter in 'Python':


if letter == 't':
break
print('Current Letter :', 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

for letter in 'python':


pass
print('Last Letter :', letter)

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.

# A simple Python function

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.

# A simple Python function

def fun():
print("Python Programming")

# Driver code to call a function


fun()

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.

# Python program to demonstrate default arguments

def myFun(x, y=50):


print("x: ", x)
print("y: ", y)

# Driver code (We call myFun() with only argument)


myFun(10)

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.

# Python program to demonstrate Keyword Arguments

def student(firstArg, lastArg):


print(firstArg, lastArg)

# Keyword arguments
student(firstArg='Python', lastArg ='Practice')
student(lastArg ='Practice', firstArg='Python')

Python Practice
Python Practice
Python Programming Unit-3 Notes

CHAPTER 3- Data Structures in Python

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.

# Python program to illustrate iterating over a list

print("List Iteration")
l = ["ABC", "BCD", "CDE"]
for i in l:
print(i)

List Iteration
ABC
BCD
CDE

# Iterating over a tuple (immutable)

print("Tuple Iteration")
t = ("ABC", "BCD", "CDE")
for i in t:
print(i)

Tuple Iteration
ABC
BCD
CDE

# Iterating over a String

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:
[]

# Creating a List of numbers

List = [10, 20, 30]


print("List of numbers: ")
print(List)

List of numbers:
[10, 20, 30]

# Creating a List of strings and accessing using index

List = ["Programming", "in", "Python"]


print("List Items: ")
print(List[0])
print(List[2])

List Items:
Programming
Python

# Creating a Multi-Dimensional List (By Nesting a list inside a List)

List = [['Programming', 'in'] , ['Python']]


print("Multi-Dimensional List: ")
print(List)

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 the use of Numbers/(Having duplicate values)


vvvvvvvalues)
List = [1, 2, 4, 4, 3, 3, 3, 6, 5]
print("List with the use of Numbers: ")
print(List)

List with the use of Numbers:


[1, 2, 4, 4, 3, 3, 3, 6, 5]

# Creating a List with mixed type of values (Having numbers and strings)

List = [1, 2, 'Programming', 4, 'in', 6, 'Python']


print("List with the use of Mixed Values: ")
print(List)

List with the use of Mixed Values:


[1, 2, 'Programming', 4, 'in', 6, Python']

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.

Updating a List elements (List are mutable)


Numbers=[17,123]
Print(“Before:”, Numbers)
Numbers[1]=5
Print (“After:”, Numbers)

Before: [17, 123]


After: [17,5]

Using len() function we can find the length (no. of elements in list) of list.

# Creating a List of numbers and finding the length

List = [10, 20, 14]


print(len(List))

3
Python Programming Unit-3 Notes

List operation

# The + operator concatenates lists

a = [1, 2, 3]
b = [4, 5, 6]
c=a+b
print(c)

[1, 2, 3, 4, 5, 6]

# The * operator repeats a list a given number of times

a = [1]
a=a*3
print(a)

[1, 1, 1]

List slices

# The slice operator

List = ['a', 'b', 'c', 'd', 'e', 'f']


print(List[1:3])
print(List[:4])
print(List[3:])

['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.

List = ['a', 'b', 'c', 'd', 'e', 'f']


print(List[:])

['a', 'b', 'c', 'd', 'e', 'f']

4
Python Programming Unit-3 Notes

A slice operator on the left side of an assignment can update multiple elements.

List = ['a', 'b', 'c', 'd', 'e', 'f']


List[1:3] = ['x', 'y']
print(List)

['a', 'x', 'y', 'd', 'e', 'f']

List methods
Python has a set of built-in methods that you can use on lists.

Method Description

append() Adds an element at the end of the list

clear() Removes all the elements from the list

copy() Returns a copy of the list

count() Returns the number of elements with the specified value

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

insert() Adds an element at the specified position

pop() Removes the element at the specified position

remove() Removes the first item with the specified value

reverse() Reverses the order of the list

sort() Sorts the list

# append()

fruits = ['apple', 'banana', 'cherry']


fruits.append("orange")
print(fruits)

['apple', 'banana', 'cherry', 'orange']

5
Python Programming Unit-3 Notes

# clear()

fruits = ['apple', 'banana', 'cherry', 'orange']


fruits.clear()
print(fruits)

[]

# copy()

fruits = ['apple', 'banana', 'cherry', 'orange']


x = fruits.copy()
print(x)

['apple', 'banana', 'cherry', 'orange']

# count()

fruits = ['apple', 'banana', 'cherry']


x = fruits.count("cherry")
print(x)

#extend()
fruits = ['apple', 'banana', 'cherry']
cars = ['Ford', 'BMW', 'Volvo']
fruits.extend(cars)
print(fruits)

['apple', 'banana', 'cherry', 'Ford', 'BMW', 'Volvo']

#index()

fruits = ['apple', 'banana', 'cherry']


x = fruits.index("cherry")
print(x)

6
Python Programming Unit-3 Notes

#insert()

fruits = ['apple', 'banana', 'cherry']


fruits.insert(1, "orange")
print(fruits)

['apple', 'orange', 'banana', 'cherry']

#pop()

fruits = ['apple', 'banana', 'cherry']


fruits.pop(1)
print(fruits)

['apple', 'cherry']

#remove()

fruits = ['apple', 'banana', 'cherry']


fruits.remove("banana")
print(fruits)

['apple', 'cherry']

#reverse()

fruits = ['apple', 'banana', 'cherry']


fruits.reverse()
print(fruits)

['cherry', 'banana', 'apple']

#sort()

cars = ['Ford', 'BMW', 'Volvo']


cars.sort()
print(cars)

['BMW', 'Ford', 'Volvo']

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 = ('ABC', 'pqr', 1000, 2000);


tup2 = (1, 2, 3, 4, 5);
tup3 = "a", "b", "c", "d";
print(tup1)
print(tup2)
print(tup3)

('ABC', 'pqr', 1000, 2000)


(1, 2, 3, 4, 5)
('a', 'b', 'c', 'd')
The empty tuple is written as two parentheses containing nothing

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 = ('physics', 'chemistry', 1997, 2000);


tup2 = (1, 2, 3, 4, 5, 6, 7);
print("tup1[0]: ", tup1[0])
print("tup2[1:5]: ", tup2[1:5])

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

tup1 = (12, 34.56);


tup2 = ('abc', 'xyz');
# following action is not valid for tuples
# tup1[0] = 100;
# so let's create a new tuple as follows
tup3 = tup1 + tup2;
print(tup3)

(12, 34.56, 'abc', 'xyz')

Delete Tuple Elements


Removing individual tuple elements is not possible. There is, of course, nothing wrong with putting
together another tuple with the undesired elements discarded.
To explicitly remove an entire tuple, just use the del statement. For example

# deleting a tuple

tup = ('ABC', 'pqr', 1997, 2000);


print(tup)
del tup;
print("After deleting tup : ")
print(tup)

This produces the following result. Note an exception raised, this is because after del tup tuple does
not exist any more

('ABC', 'pqr', 1997, 2000)


After deleting tup :

NameError Traceback (most recent call last)


<ipython-input-54-692273a13f26> in <module>
3deltup;
4print("After deleting tup : ")
----> 5print(tup)
NameError: name 'tup' is not defined

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

Python Expression Results Description

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

Indexing, Slicing, Matrices


Because tuples are sequences, indexing and slicing work the same way for tuples as they do for strings.
Assuming following input

L = ('spam', 'Spam', 'SPAM!')

Python Expression Results Description

print(L[2]) 'SPAM!' Offsets start at zero

print(L[-2]) 'Spam' Negative: count from the right

print(L[1:]) ['Spam', 'SPAM!'] Slicing fetches sections

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()

tuple1, tuple2 = (123, 'xyz', 'zara'), ('abc')


print("First tuple length : ", len(tuple1))
print("Second tuple length : ", len(tuple2))

First tuple length : 3


Second tuple length : 3

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 = {'Alice': '2341', 'Beth': '9102', 'Cecil': '3258'}

You can create dictionary in the following way as well:

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

d1 = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};


print("Name:", d1['Name']);
print("Age:", d1['Age']);
print("Class:", d1['Class']);

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

d1 = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};


print("d1['Alice']: ", d1['Alice'])

KeyError Traceback (most recent call last)


<ipython-input-58-d6f7f5c44745> in <module>
1 d1 ={'Name':'Zara','Age':7,'Class':'First'};
----> 2print("d1['Alice']: ", d1['Alice'])
KeyError: 'Alice'

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)

{'Name': 'Zara', 'Age': 7, 'Class': 'First'}


d1['Age']: 8
d1['School']: LJP
{'Name': 'Zara', 'Age': 8, 'Class': 'First', 'School': 'LJP'}

Deleting Dictionary Elements


To explicitly remove an entire dictionary, just use the del statement.

# 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

{'Name': 'Zara', 'Age': 7, 'Class': 'First'}


d1['Age']: 8
d1['School']: LJP
{'Name': 'Zara', 'Age': 8, 'Class': 'First', 'School': 'LJP'}

Build-in Dictionary Functions & Methods


Method Description
d1.clear() Removes all elements of dictionary d1
d1.copy() Returns a shallow copy of dictionary d1
d1.get(key, default=None) Returns the value of the item with the specified key
d1.items() Returns a list of d1's (key, value) tuple pairs
d1.keys() Returns list of dictionary d1's keys
d1.update(d2) Adds dictionary d2's key-values pairs to d1
d1.values() Returns list of dictionary d1's values

# clear()

d1 = {'Name': 'Zara', 'Age': 7};


print("Start Len:", len(d1))
d1.clear()
print("End Len:", len(d1))

Start Len: 2
End Len: 0

# copy()

d1 = {'Name': 'Zara', 'Age': 7};


d2 = d1.copy()
print("New Dictionary:", str(d2))

New Dictionary: {'Name': 'Zara', 'Age': 7}

# get()

d1 = {'Name': 'Zara', 'Age': 7}


print("Value:", d1.get('Age'))
print("Value:", d1.get('Education', "Never"))
print(d1.get('c'))

Value: 7
Value: Never
None

13
Python Programming Unit-3 Notes

# items()

d1 = {'Name': 'Zara', 'Age': 7}


print("Value:", d1.items())

Value : dict_items([('Name', 'Zara'), ('Age', 7)])

# keys()

d1 = {'Name': 'Zara', 'Age': 7}


print("Keys:", d1.keys())

Keys: dict_keys(['Name', 'Age'])

#values()

d1 = {'Name': 'Zara', 'Age': 7}


print("Values:", d1.values())

Values: dict_values(['Zara', 7])

# update()

d1 = {'Name': 'Zara', 'Age': 7}


d2 = {'Gender': 'female'}
d1.update(d2)
print("Value:", d1)

Value: {'Name': 'Zara', 'Age': 7, 'Gender': 'female'}

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

thisset = {"apple", "banana", "cherry"}


print(thisset)

{'banana', 'apple', 'cherry'}

Note: Sets are unordered, so you cannot be sure in which order the items will appear.

Duplicates Not Allowed


Sets cannot have two items with the same value.

# creating set

thisset = {"apple", "banana", "cherry", "cherry"}


print(thisset)

{'banana', 'apple', 'cherry'}

Set Items - Data Types


Set items can be of any data type.

# string, int and boolean data types

set1 = {"apple", "banana", "cherry"}


set2 = {1, 5, 7, 9, 3} #in numeric, it will print in order.
set3 = {True, False, False}
set4= {"abc", 34, True, 40, "male"} # set with strings, integers and boolean values
print(set1)
print(set2)
print(set3)
print(set4)

{'banana', 'cherry', 'apple'}


{1, 3, 5, 7, 9}
{False, True}
{True, 34, 'male', 40, 'abc'}

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.

# loop through the set, and print the values

thisset = {"apple", "banana", "cherry"}


for x in thisset:
print(x, end=",")

cherry,banana,apple,

# check if "apple" is present in the set:

thisset= {"apple", "banana", "cherry"}


print("apple" in thisset)

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.

# add an item to a set, using the add() method


thisset = {"apple", "banana", "cherry"}
thisset.add("orange")
print(thisset)

{'cherry', 'orange', 'banana', 'apple'}

To add items from another set into the current set, use the update() method.

# add elements from tropical into thisset

thisset = {"apple", "banana", "cherry"}


tropical = {"pineapple", "mango", "papaya"}
thisset.update(tropical)
print(thisset)

16
Python Programming Unit-3 Notes

{'banana', 'mango', 'apple', 'cherry', 'papaya', 'pineapple'}

Add Any Iterable


The object in the update() method does not have to be a set, it can be any iterable object (tuples,
lists, dictionaries etc.).

# add elements from tropical into thisset

thisset = {"apple", "banana", "cherry"}


mylist = ["kiwi", "orange"]
thisset.update(mylist)
print(thisset)

{'cherry', 'kiwi', 'orange', 'banana', 'apple'}

Remove Item
To remove an item in a set, use the remove(), or the discard() method.

# remove "apple" by using the remove() method

thisset= {"apple", "banana", "cherry"}


thisset.remove("apple")
print(thisset)

{'cherry', 'banana'}

# remove "apple" by using the discard() method

thisset= {"apple", "banana", "cherry"}


thisset.discard("apple")
print(thisset)

{'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.

# remove the last item by using the pop() method

thisset = {"apple", "banana", "cherry"}


x = thisset.pop()
print(x)
print(thisset)

cherry
{'banana', 'apple'}

#clear() method empties the set

thisset = {"apple", "banana", "cherry"}


thisset.clear()
print(thisset)

set()

#del keyword will delete the set completely

thisset = {"apple", "banana", "cherry"}


del thisset
print(thisset)

NameError Traceback (most recent call last)


<ipython-input-24-2ec9feb8cb8a> in <module>
1 thisset = {"apple", "banana", "cherry"}
2 del thisset
----> 3 print(thisset)
NameError: name 'thisset' is not defined

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

set1 = {"a", "b","c"}


set2 = {1, 2, 3}
set3 = set1.union(set2)
print(set3)

{1, 'c', 2, 3, 'a', 'b'}

#update() method inserts the items in set2 into set1

set1 = {"a", "b" , "c"}


set2 = {1, 2, 3}
set1.update(set2)
print(set1)

{1, 'c', 2, 3, 'a', 'b'}

Note: Both union() and update() will exclude any duplicate items.

19
Python Programming Unit-2 Notes

CHAPTER 4 - Classes & Modules in Python

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.

# create a class named MyClass, with a property named x

class MyClass:
x=5

Create Object
Now we can use the class named MyClass to create objects

# create an object named p1, and print the value of x

p1 = MyClass()
print(p1.x)

# example of class and object

class MyClass:
x=5

p1 = MyClass()
print(p1.x)

The __init__() Function


The examples above are classes and objects in their simplest form, and are not really useful in real
life applications.
To understand the meaning of classes we have to understand the built-in __init__() function.
All classes have a function called __init__(), which is always executed when the class is being
initiated. The__init__() function is used to assign values to object properties and other operations that
are necessary to do when the object is being created.
Python Programming Unit-2 Notes

# create a class named Person


# use the __init__() function to assign values for name and age

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

The self Parameter


The self parameter is a reference to the current instance of the class, and is used to access variables
that belongs to the class.
It does not have to be named self, you can call it whatever you like, but it has to be the first
parameter of any function in the class.

#use the words myobject and arg instead of self

class Person:

def __init__(myobject, name, age):


myobject.name = name
myobject.age = age

def myfunc(arg):
print("Hello my name is " + arg.name)

p1 = Person("John", 36)
p1.myfunc()

Hello my name is John


Python Programming Unit-2 Notes

Modify Object Properties


You can modify properties on objects like this

p1.age = 40

# Set the age of p1 to 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

Delete Object Properties or Object


You can delete properties of objects or object by using the del keyword

del p1.age #delete the age property from the p1 object

del p1 # delete the p1 object


Python Programming Unit-2 Notes

# delete the p1 object

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

AttributeError Traceback (most recent call last)


<ipython-input-16-46454e0e6825> in <module>
12 del p1.age
---> 13 print(p1.age)
AttributeError: 'Person' object has no attribute 'age'

NameError Traceback (most recent call last)


15 del p1
---> 16 print(p1)
NameError: name 'p1' is not defined
Python Programming Unit-2 Notes

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.

Following is the example of Polymorphism in Python:

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()

# passing the object


flying_test(blu)
flying_test(peggy)
Python Programming Unit-2 Notes

Following is the output:

Parrot can fly


Penguin can't fly

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:

>>> Enter the value: 4


>>>24
Python Programming Unit-2 Notes

pip and PyPI

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'

How to install pip?

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.

pip install numpy

The Python pip list command displays a list of packages installed in the system.

pip list
Python Programming Unit-2 Notes

The Python pip uninstall command uninstalls a particular existing package.

pip uninstall numpy

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

CHAPTER 5 - Python Standard Libraries

Working with path, files and directories


Python supports file handling and allows users to handle files i.e., to read and write files,
along with many other file handling options, to operate on files. Python treats file differently as text
or binary and this is important. Each line of code includes a sequence of characters and they form
text file. Each line of a file is terminated with a special character, called the EOL or End of Line
characters like comma {,} or newline character. It ends the current line and tells the interpreter a new
one has begun.

Working with paths

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.

We can import the Path class from pathlib module as below:

from pathlib import Path

We can create a path class object like:

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( )

Let us create a path object to get the use of some methods.

path = Path(“D://testmodule/test.txt”)

We can check if the path exists or not by exists method.

path.exists()
We can also check if the path represents a file or not.

path.is_file()
Python Programming Unit-5 Notes

Same thing we can check for directory.

path.is_dir()

We can get the file name in the path by name property.

print(path.name)

We can get the file name without extension by stem property.

print(path.stem)

Same way, we can get the extension only by suffix property.

print(path.suffix)

will display .py

We can get the parent directory by using parent property.

print(path.parent)

We can also display the absolute path by using absolute method.

print(path.absolute())

Working with Directories

As we have already covered, Path object can be created using:

path = Path(“test”)

We can create and remove directories as follows.

path.mkdir(‘name’)

path.rmdir(‘name’)

Also, we can rename it by:

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.

Working with Files

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”)

We can check if the file exists or not using:

path.exists()

We can rename the file using rename method.

path.rename(“init.txt”)

We can delete the file using unlink method.

path.unlink()

We can check the details of the file using stat method.

print(path.stat())

Reading from a file can be done using read_text method.

print(path.read_text())

Similarly, we can write into the file using write_text method.

path.write_text(“Hello All”)
Python Programming Unit-5 Notes

Working with CSV

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.

We can use csv module to work with csv files.

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)

As mentioned, we need to pass file object to this method.

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)

for row in reader:

print(row)
Python Programming Unit-5 Notes

Working with time and datetime

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.

Let us see first how we can use time module.

import time

time1 = time.time()

curr = time.ctime(time1)

print(“current time”,curr)

Output:

Wed Nov 23 14:40:52 2022

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.

from datetime import datetime

Now, we can create a datetime object by mentioning year, month and day. Optionally we can
mention hour, minutes and seconds too.

dt = datetime(2022, 12, 25)

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)

print(dt2 > dt1)

Above code will print TRUE as date in dt2 is greater.

You might also like