SlideShare une entreprise Scribd logo
1  sur  212
Presented by:
Shahid Sultan
Research Scholar
National Institute of Technology Srinagar
N.I.T Srinagar 1
What is Python?
Python is a popular programming language. It was
created by Guido van Rossum, and released in 1991.
 It is used for:
 web development (server-side),
 software development,
 mathematics,
 system scripting.
N.I.T Srinagar 2
 Python is a general-purpose interpreted, interactive,
object-oriented, and high-level programming
language. It was created by Guido van Rossum during
1985- 1990. Like Perl, Python source code is also
available under the GNU General Public License
(GPL).
N.I.T Srinagar 3
 Python is Interpreted − Python is processed at runtime by
the interpreter. You do not need to compile your program before
executing it. This is similar to PERL and PHP.
 Python is Interactive − You can actually sit at a Python
prompt and interact with the interpreter directly to write your
programs.
 Python is Object-Oriented − Python supports Object-
Oriented style or technique of programming that encapsulates
code within objects.
 Python is a Beginner's Language − Python is a great
language for the beginner-level programmers and supports the
development of a wide range of applications from simple text
processing to WWW browsers to games.
N.I.T Srinagar 4
Python History
 Python was invented by Guido van Rossum in 1991 at
CWI in Netherland. The idea of Python programming
language has taken from the ABC programming
language or we can say that ABC is a predecessor of
Python language.
 There is also a fact behind the choosing name Python.
Guido van Rossum was a fan of the popular BBC
comedy show of that time, "Monty Python's Flying
Circus". So he decided to pick the name Python for
his newly created programming language.
N.I.T Srinagar 5
Python Features
1. Easy Language
 Python is an easy language. It is easy to read, write, learn
and understand.
 Python has a smooth learning curve. It is easy to learn.
 Python has a simple syntax and Python code is easy to
understand.
 Since it’s easy to understand, you can easily read and
understand someone else’s code.
 Python is also easy to write because of its simple syntax.
 Because it is an easy language, it is used in schools and
universities to introduce students to programming. Python
is for both startups and big companies.
N.I.T Srinagar 6
2. Readable
The Python language is designed to make developers life
easy. Reading a Python code is like reading an English
sentence. This is one of the key reason that makes
Python best for beginners.
Python uses indentation instead of curly braces, unlike
other programming languages. This makes the code look
clean and easier to understand.
N.I.T Srinagar 7
3. Interpreted Language
 Python is an interpreted language. It comes with the
IDLE (Interactive Development Environment).
This is an interpreter and follows the REPL structure
(Read-Evaluate-Print-Loop). It executes and
displays the output of one line at a time.
 So it displays errors while you’re running a line and
displays the entire stack trace for the error.
N.I.T Srinagar 8
 4. Dynamically-Typed Language
 Python is not statically-typed like Java. You don’t
need to declare data type while defining a variable.
The interpreter determines this at runtime based on
the types of the parts of the expression. This is easy for
programmers but can create runtime errors.
 Python follows duck-typing. It means, “If it looks like
a duck, swims like a duck and quacks like a duck, it
must be a duck.”
N.I.T Srinagar 9
5. Object-Oriented
 Python is object-oriented but supports both functional
and object-oriented programming. Everything in
Python is an object.
 It has the OOP (Object-oriented programming)
concepts like inheritance and polymorphism.
N.I.T Srinagar 10
6. Popular and Large Community Support
 Python has one of the largest communities on
StackOverflow and Meetup. If you need help, the
community will answer your questions.
 They also already have many answered questions about
Python.
7. Open-Source
 Python is open-source and the community is always
contributing to it to improve it. It is free and its source
code is freely available to the public. You can download
Python from the official Python Website.
N.I.T Srinagar 11
8. Large Standard Library
 The standard library is large and has many packages and modules with
common and important functionality. If you need something that is available
in this standard library, you don’t need to write it from scratch. Because of this,
you can focus on more important things.
 You can also install packages from the PyPI (Python Package Index) if you
want even more functionality.
9. Platform-Independent
 Python is platform-independent. If you write a program, it will run on different
platforms like Windows, Mac and Linux. You don’t need to write them
separately for each platform.
10. Extensible and Embeddable
 Python is extensible. You can use code from other languages like C++ in your
Python code.
 It is also embeddable. You can embed your Python code in other languages
like C++.
N.I.T Srinagar 12
11. GUI Support
 You can use Python to create GUI (Graphical User
Interfaces). You can use tkinter, PyQt, wxPython or
Pyside for this.
 Python features a huge number of GUI frameworks
available for it to variety of other cross-platform solutions.
It binds to platform-specific technologies.
12. High-level Language
 Python is a high-level language and C++ is mid-level. It is
easy to understand and closer to the user. You don’t need to
remember system architecture or manage the memory.
N.I.T Srinagar 13
Where is Python used?
Python is a general-purpose, popular programming language and it is used in
almost every technical field. The various areas of Python use are given below.
 Data Science
 Date Mining
 Desktop Applications
 Console-based Applications
 Mobile Applications
 Software Development
 Artificial Intelligence
 Web Applications
 Enterprise Applications
 3D CAD Applications
 Machine Learning
 Computer Vision or Image Processing Applications.
 Speech Recognitions
N.I.T Srinagar 14
Installing Python
N.I.T Srinagar 15
Python Indentation
 Indentation refers to the spaces at the beginning of a
code line.
 Where in other programming languages the
indentation in code is for readability only, the
indentation in Python is very important.
 Python uses indentation to indicate a block of code.
N.I.T Srinagar 16
if 5 > 2:
print("Five is greater than two!")
 Python will give you an error if you skip the
indentation:
if 5 > 2:
print("Five is greater than two!")
The number of spaces is up to you as a
programmer, but it has to be at least one.
N.I.T Srinagar 17
if 5 > 2:
print("Five is greater than two!")
print("Five is greater than two!")
if 5 > 2:
print("Five is greater than two!")
 You have to use the same number of spaces in the same
block of code, otherwise Python will give you an error:
if 5 > 2:
print("Five is greater than two!")
print("Five is greater than two!")
N.I.T Srinagar 18
Comments
 Python has commenting capability for the purpose of in-
code documentation.
 Comments can be used to explain Python code.
 Comments can be used to make the code more readable.
 Comments can be used to prevent execution when testing
code.
 Comments start with a #, and Python will render the rest of
the line as a comment:
#This is a comment.
print("Hello, World!")
N.I.T Srinagar 19
 Comments can be placed at the end of a line, and
Python will ignore the rest of the line:
print("Hello, World!") #This is a comment
 To add a multiline comment you could insert a # for
each line:
#This is a comment
#written in
#more than just one line
print("Hello, World!")
N.I.T Srinagar 20
Python Variables
 Variables are containers for storing data values.
 Variables are nothing but reserved memory locations
to store values. This means that when you create a
variable you reserve some space in memory.
 Based on the data type of a variable, the interpreter
allocates memory and decides what can be stored in
the reserved memory. Therefore, by assigning different
data types to variables, you can store integers, decimals
or characters in these variables.
N.I.T Srinagar 21
 Python variables do not need explicit declaration to
reserve memory space. The declaration happens
automatically when you assign a value to a variable.
The equal sign (=) is used to assign values to variables.
 The operand to the left of the = operator is the name of
the variable and the operand to the right of the =
operator is the value stored in the variable.
N.I.T Srinagar 22
x = 5
y = "John"
print (x)
print(y)
 Python allows you to assign a single value to several
variables simultaneously
a = b = c = 1
a,b,c = 1,2,"john“
N.I.T Srinagar 23
Variable Names
 A variable can have a short name (like x and y) or a
more descriptive name (age, carname, total_volume).
 A variable name must start with a letter or the
underscore character
 A variable name cannot start with a number
 A variable name can only contain alpha-numeric
characters and underscores (A-z, 0-9, and _ )
 Variable names are case-sensitive (age, Age and AGE are
three different variables)
N.I.T Srinagar 24
 Legal variable names:
myvar = "John"
my_var = "John"
_my_var = "John"
myVar = "John"
MYVAR = "John"
myvar2 = "John"
N.I.T Srinagar 25
 Illegal variable names:
2myvar = "John"
my-var = "John"
my var = "John"
N.I.T Srinagar 26
Data Types
 The data stored in memory can be of many types. For
example, a person's age is stored as a numeric value
and his or her address is stored as alphanumeric
characters.
 Python has various standard data types that are used
to define the operations possible on them and the
storage method for each of them.
N.I.T Srinagar 27
 Python has five standard data types −
 Numbers
 String
 List
 Tuple
 Dictionary
N.I.T Srinagar 28
Python 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
N.I.T Srinagar 29
 To verify the type of any object in Python, use the
type() function:
X=4
Y=‘shahid’
Z=5.987
print(type(x))
print(type(y))
print(type(z))
N.I.T Srinagar 30
Int
 Int, or integer, is a whole number, positive or negative,
without decimals, of unlimited length.
x = 1458
y = 35656222554887711
z = -3255522
print(type(x))
print(type(y))
print(type(z))
N.I.T Srinagar 31
Float
 Float, or "floating point number" is a number, positive
or negative, containing one or more decimals.
x = 1.10
y = 1.0
z = -35.59
print(type(x))
print(type(y))
print(type(z))
N.I.T Srinagar 32
Complex
 Complex numbers are written with a "j" as the
imaginary part:
x = 3+5j
y = 5j
z = -5j
print(type(x))
print(type(y))
print(type(z))
N.I.T Srinagar 33
Type Conversion
 You can convert from one type to another with the int(), float(), and
complex() methods:
x = 1 # int
y = 2.8 # float
z = 1j # complex
#convert from int to float:
a = float(x)
#convert from float to int:
b = int(y)
#convert from int to complex:
c = complex(x)
print(a)
print(b)
print(c)
print(type(a))
print(type(b))
print(type(c))
N.I.T Srinagar 34
Random Number
 Python has a built-in module called random that can
be used to make random numbers:
import random
A= random.randrange(1, 5)
N.I.T Srinagar 35
Python Strings
 Strings in Python are identified as a contiguous set of
characters represented in the quotation marks. Python
allows for either pairs of single or double quotes.
'hello' is the same as "hello“
print("Hello")
print('Hello')
N.I.T Srinagar 36
Assign String to a Variable
 Assigning a string to a variable is done with the
variable name followed by an equal sign and the
string:
a = "Hello"
print(a)
N.I.T Srinagar 37
Multiline Strings
 You can assign a multiline string to a variable by using
three quotes:
a = ‘’’Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua.’’’
print(a)
N.I.T Srinagar 38
a = '''Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua.'''
print(a)
N.I.T Srinagar 39
String Length
 To get the length of a string, use the len() function.
a = "Hello, World!"
print(len(a))
N.I.T Srinagar 40
Python - Slicing Strings
 You can return a range of characters by using the slice
syntax.
 Specify the start index and the end index, separated by
a colon, to return a part of the string.
 Get the characters from position 2 to position 5 (not
included):
b = "Hello, World!“
S=b[2:5]
Print(S)
N.I.T Srinagar 41
Slice From the Start
 By leaving out the start index, the range will start at
the first character:
 Get the characters from the start to position 5 (not
included):
b = "Hello, World!"
print(b[:5])
N.I.T Srinagar 42
Slice To the End
 By leaving out the end index, the range will go to the
end:
Get the characters from position 2, and all the way to the
end:
b = "Hello, World!"
print(b[2:])
N.I.T Srinagar 43
Upper Case
 The upper() method returns the string in upper case:
a = "Hello, World!“
B=a.upper()
print(B)
N.I.T Srinagar 44
Lower Case
 The lower() method returns the string in lower case:
a = "Hello, World!"
print(a.lower())
N.I.T Srinagar 45
Replace String
 The replace() method replaces a string with another
string:
a = "Hello, World!"
B= a.replace("H", "J")
Print(B)
N.I.T Srinagar 46
String Concatenation
 To concatenate, or combine, two strings you can use
the + operator.
 Merge variable a with variable b into variable c:
a = "Hello"
b = "World"
c = a + b
print(c)
HelloWorld!
N.I.T Srinagar 47
 To add a space between them, add a " ":
a = "Hello"
b = "World"
c = a + " " + b
print(c)
N.I.T Srinagar 48
String Format
 we cannot combine strings and numbers like this:
age = 36
txt = "My name is John, I am " + age
print(txt)
N.I.T Srinagar 49
 But we can combine strings and numbers by using the
format() method!
 The format() method takes the passed arguments,
formats them, and places them in the string where the
placeholders {} are:
N.I.T Srinagar 50
age = 36
txt = "My name is John, and I am {},{}"
D=txt.format(age)
N.I.T Srinagar 51
quantity = 3
itemno = 567
price = 49.95
myorder = "I want {} pieces of item {} for {} dollars."
print(myorder.format(quantity, itemno, price))
N.I.T Srinagar 52
Add Two Numbers
# This program adds two numbers
num1 = 1.5
num2 = 6.3
# Add two numbers
sum = num1 + num2
# Display the sum
print('The sum of {0} and {1} is {2}'.format(num1, num2,
sum))
N.I.T Srinagar 53
Add Two Numbers With User
Input
# Store input numbers
num1 = input('Enter first number: ')
num2 = input('Enter second number: ')
# Add two numbers
sum = float(num1) + float(num2)
# Display the sum
print('The sum of {0} and {1} is {2}'.format(num1, num2,
sum))
N.I.T Srinagar 54
# Python Program to Calculate Cube of a Number
number = float(input(" Please Enter any numeric Value : "))
cube = number * number * number
print("The Cube of a Given Number {0} =
{1}".format(number, cube))
N.I.T Srinagar 55
Types of Operator
 Python language supports the following types of
operators.
 Arithmetic Operators
 Comparison (Relational) Operators
 Assignment Operators
 Logical Operators
 Bitwise Operators
 Membership Operators
 Identity Operators
N.I.T Srinagar 56
Arithmetic Operators
N.I.T Srinagar 57
Comparison Operators
N.I.T Srinagar 58
Assignment Operators
N.I.T Srinagar 59
Bitwise Operators
 Bitwise operator works on bits and performs bit by bit operation. Assume if a = 60; and b = 13;
 Now in the binary format their values will be 0011 1100 and 0000 1101 respectively.
 a = 0011 1100
 b = 0000 1101
 -----------------
 a&b = 0000 1100
 a|b = 0011 1101
 a^b = 0011 0001
 ~a = 1100 0011
N.I.T Srinagar 60
N.I.T Srinagar 61
Logical Operators
N.I.T Srinagar 62
Membership Operators
N.I.T Srinagar 63
LISTS
 A list in Python is used to store the sequence of various
types of data. Python lists are mutable type its mean we
can modify its element after it created. However, Python
consists of six data-types that are capable to store the
sequences, but the most common and reliable type is the
list.
 A list can be defined as a collection of values or items of
different types. The items in the list are separated with the
comma (,) and enclosed with the square brackets [].
N.I.T Srinagar 64
L1 =[1, 2, 4, 3, 5, 6]
L2 = [1, 2, 3, 4, 5, 6]
The list has the following characteristics:
 The lists are ordered.
 The element of the list can access by index.
 The lists are the mutable type.
 The lists are mutable types.
 A list can store the number of various elements.
N.I.T Srinagar 65
 a = [1,2,"Peter",4.50,"Ricky",5,6]
 b = [1,2,5,"Peter",4.50,"Ricky",6]
 a ==b
N.I.T Srinagar 66
List indexing and splitting
 The indexing is processed in the same way as it
happens with the strings. The elements of the list can
be accessed by using the slice operator [].
 The first element of the list is stored at the 0th index,
the second element of the list is stored at the 1st index,
and so on.
N.I.T Srinagar 67
N.I.T Srinagar 68
list = [1,2,3,4,5,6,7]
print(list[0])
print(list[1])
print(list[2])
print(list[3])
# Slicing the elements
print(list[0:6]) # By default the index value is 0 so its starts from
the 0th element and go for index -1.
print(list[:])
print(list[2:5])
print(list[1:6:2])
N.I.T Srinagar 69
 Unlike other languages, Python provides the flexibility
to use the negative indexing also. The negative indices
are counted from the right. The last element
(rightmost) of the list has the index -1; its adjacent left
element is present at the index -2 and so on until the
left-most elements are encountered.
N.I.T Srinagar 70
N.I.T Srinagar 71
list = [1,2,3,4,5]
print(list[-1])
print(list[-3:])
print(list[:-1])
print(list[-3:-1])
N.I.T Srinagar 72
Updating List values
 Lists are the most versatile data structures in Python since they are mutable, and their
values can be updated by using the slice and assignment operator.
list = [1, 2, 3, 4, 5, 6]
print(list) 1 2 3 4 5 6
# It will assign value to the value to the second index
list[2] = 10;
print(list)
# Adding multiple-element
list[1:3] = [89, 78]
print(list)
# It will add value at the end of the list
list[-1] = 25
print(list)
N.I.T Srinagar 73
 Python also provides append() and insert() methods,
which can be used to add values to the list.
 to add an item to the end of the list, use the append()
method:
thislist = ["apple", "banana", "cherry"]
thislist.append("orange")
print(thislist)
N.I.T Srinagar 74
 To insert a list item at a specified index, use the
insert() method.
thislist = ["apple", "banana", "cherry"]
thislist.insert(0, "orange")
print(thislist)
N.I.T Srinagar 75
Remove List Items
 The remove() method removes the specified item.
thislist = ["apple", "banana", "cherry“]
thislist.remove("banana")
print(thislist)
N.I.T Srinagar 76
 The pop() method removes the specified index.
thislist = ["apple", "banana", "cherry"]
thislist.pop(1)
print(thislist)
 If you do not specify the index, the pop() method
removes the last item.
N.I.T Srinagar 77
 The del keyword also removes the specified index:
thislist = ["apple", "banana", "cherry"]
del thislist[0]
print(thislist)
 The del keyword can also delete the list completely.
thislist = ["apple", "banana", "cherry"]
del thislist
N.I.T Srinagar 78
 The clear() method empties the list.
 The list still remains, but it has no content.
thislist = ["apple", "banana", "cherry"]
thislist.clear()
print(thislist)
N.I.T Srinagar 79
Tuple
 A tuple is a collection of objects which ordered and
immutable.
 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.
N.I.T Srinagar 80
thistuple = ("apple", "banana", "cherry")
print(thistuple)
 Tuple items are ordered, unchangeable, and allow
duplicate values.
 Tuple items are indexed, the first item has index [0],
the second item has index [1] etc.
N.I.T Srinagar 81
 When we say that tuples are ordered, it means that the
items have a defined order, and that order will not
change.
 Tuples are unchangeable, meaning that we cannot
change, add or remove items after the tuple has been
created.
 Since tuples are indexed, they can have items with the
same value
N.I.T Srinagar 82
Tuple Length
 To determine how many items a tuple has, use the
len() function:
thistuple = ("apple", "banana", "cherry")
print(len(thistuple))
N.I.T Srinagar 83
Create Tuple With One Item
 To create a tuple with only one item, you have to add a
comma after the item, otherwise Python will not
recognize it as a tuple.
 Example
 One item tuple, remember the comma:
thistuple = ("apple",)
print(type(thistuple)) tuple
#NOT a tuple
thistuple = ("apple")
print(type(thistuple)) string
N.I.T Srinagar 84
Tuple Items - Data Types
 Tuple items can be of any data type:
String, int and boolean data types:
tuple1 = ("apple", "banana", "cherry")
tuple2 = (1, 5, 7, 9, 3)
tuple3 = (True, False, False)
 A tuple can contain different data types:
 A tuple with strings, integers and boolean values:
 tuple1 = ("abc", 34, True, 40, "male")
N.I.T Srinagar 85
Access Tuple Items
 You can access tuple items by referring to the index
number, inside square brackets:
 Print the second item in the tuple:
thistuple = ("apple", "banana", "cherry")
print(thistuple[1])
 Negative indexing means start from the end.
 -1 refers to the last item, -2 refers to the second last item
etc.
 Print the last item of the tuple:
thistuple = ("apple", "banana", "cherry")
print(thistuple[-1])
N.I.T Srinagar 86
Range of Indexes
 You can specify a range of indexes by specifying where
to start and where to end the range.
 When specifying a range, the return value will be a
new tuple with the specified items.
Example
 Return the third, fourth, and fifth item:
 thistuple = ("apple", "banana", "cherry", "orange",
"kiwi", "melon", "mango")
print(thistuple[2:5])
N.I.T Srinagar 87
 This example returns the items from the beginning to,
but NOT included, "kiwi":
thistuple = ("apple", "banana", "cherry", "orange", "kiwi",
"melon", "mango")
print(thistuple[:4])
N.I.T Srinagar 88
 By leaving out the end value, the range will go on to
the end of the list:
 Example
 This example returns the items from "cherry" and to
the end:
thistuple = ("apple", "banana", "cherry", "orange", "kiwi",
"melon", "mango")
print(thistuple[2:])
N.I.T Srinagar 89
Update Tuples
 Tuples are unchangeable, meaning that you cannot
change, add, or remove items once the tuple is created.
 Once a tuple is created, you cannot change its values.
Tuples are unchangeable, or immutable as it also is
called.
 But there is a workaround. You can convert the tuple
into a list, change the list, and convert the list back
into a tuple.
N.I.T Srinagar 90
 Convert the tuple into a list to be able to change it:
x = ("apple", "banana", "cherry")
y = list(x)
y[1] = "kiwi"
x = tuple(y)
print(x)
N.I.T Srinagar 91
Add Items
 Since tuples are immutable, they do not have a build-
in append() method, but there are other ways to add
items to a tuple.
 Convert into a list: Just like the workaround for
changing a tuple, you can convert it into a list, add
your item(s), and convert it back into a tuple.
N.I.T Srinagar 92
 Convert the tuple into a list, add "orange", and convert
it back into a tuple:
thistuple = ("apple", "banana", "cherry")
y = list(thistuple)
y.append("orange")
thistuple = tuple(y)
N.I.T Srinagar 93
Add tuple to a tuple
 You are allowed to add tuples to tuples, so if you want
to add one item, (or many), create a new tuple with the
item(s), and add it to the existing tuple:
 Example
 Create a new tuple with the value "orange", and add
that tuple:
thistuple = ("apple", "banana", "cherry")
y = ("orange",)
thistuple += y
print(thistuple)
N.I.T Srinagar 94
Remove Items
 Tuples are unchangeable, so you cannot remove items from it, but you can use
the same workaround as we used for changing and adding tuple items:
 Example
 Convert the tuple into a list, remove "apple", and convert it back into a tuple:
thistuple = ("apple", "banana", "cherry")
y = list(thistuple)
y.remove("apple")
thistuple = tuple(y)
 Or you can delete the tuple completely:
 Example
 The del keyword can delete the tuple completely:
thistuple = ("apple", "banana", "cherry")
del thistuple
print(thistuple) #this will raise an error because the tuple no longer exists
N.I.T Srinagar 95
Python Sets
 A set is a collection which is unordered,
unchangeable*, and unindexed.
 * Note: Set items are unchangeable, but you can
remove items and add new items.
 Sets are written with curly brackets.
 Create a Set:
thisset = {"apple", "banana", "cherry"}
print(thisset)
N.I.T Srinagar 96
 Duplicates Not Allowed
 Sets cannot have two items with the same value.
 Duplicate values will be ignored:
thisset = {"apple", "banana", "cherry", "apple"}
print(thisset)
N.I.T Srinagar 97
Set Items - Data Types
 Set items can be of any data type:
 Example
 String, int and boolean data types:
 set1 = {"apple", "banana", "cherry"}
set2 = {1, 5, 7, 9, 3}
set3 = {True, False, False}
 A set can contain different data types:
 Example
 A set with strings, integers and boolean values:
 set1 = {"abc", 34, True, 40, "male"}
N.I.T Srinagar 98
Access Set Items
 You cannot access items in a set by referring to an
index or a key.
 But you can loop through the set items using a for
loop, or ask if a specified value is present in a set, by
using the in keyword.
 Example
 Loop through the set, and print the values:
 thisset = {"apple", "banana", "cherry"}
for x in thisset:
print(x)
N.I.T Srinagar 99
Change Items
 Once a set is created, you cannot change its items, but
you can add new items.
N.I.T Srinagar 100
Add Set Items
 To add one item to a set use the add() method.
 Example
 Add an item to a set, using the add() method:
 thisset = {"apple", "banana", "cherry"}
thisset.add("orange")
print(thisset)
N.I.T Srinagar 101
 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)
N.I.T Srinagar 102
Remove Set Items
 To remove an item in a set, use the remove(), or the discard() method.
 Example
 Remove "banana" by using the remove() method:
 thisset = {"apple", "banana", "cherry"}
thisset.remove("banana")
print(thisset)
 Note: If the item to remove does not exist, remove() will raise an error.
 Example
 Remove "banana" by using the discard() method:
 thisset = {"apple", "banana", "cherry"}
thisset.discard("banana")
print(thisset)
 Note: If the item to remove does not exist, discard() will NOT raise an error.
 You can also use the pop() method to remove an item, but this method will
remove the last item. Remember that sets are unordered, so you will not know
what item that gets removed.
 The return value of the pop() method is the removed item.
N.I.T Srinagar 103
 Sets are unordered, so when using the pop() method, you
do not know which item that gets removed.
 The clear() method empties the set:
 thisset = {"apple", "banana", "cherry"}
thisset.clear()
print(thisset)
 The del keyword will delete the set completely:
 thisset = {"apple", "banana", "cherry"}
del thisset
print(thisset)
N.I.T Srinagar 104
Dictionaries
 Dictionaries are used to store data values in key:value
pairs.
 A dictionary is a collection which is ordered*,
changeable and does not allow duplicates.
 As of Python version 3.7, dictionaries are ordered. In
Python 3.6 and earlier, dictionaries are unordered.
 Dictionaries are written with curly brackets, and have
keys and values:
N.I.T Srinagar 105
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)
N.I.T Srinagar 106
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict["brand"])
N.I.T Srinagar 107
 Dictionaries are changeable, meaning that we can change,
add or remove items after the dictionary has been created.
 Dictionaries cannot have two items with the same key:
 Duplicate values will overwrite existing values:
 thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964,
"year": 2020
}
print(thisdict)
N.I.T Srinagar 108
Dictionary Length
 To determine how many items a dictionary has, use the
len() function:
 Example
 Print the number of items in the dictionary:
Student{
“Name”: “Shahid”
“Branch”: “IT”
“Course”: “Ph.D”
}
S= len(Student)
Print(S);
N.I.T Srinagar 109
Dictionary Items - Data Types
 The values in dictionary items can be of any data type:
 Example
 String, int, boolean, and list data types:
 thisdict = {
"brand": "Ford",
"electric": False,
"year": 1964,
"colors": ["red", "white", "blue"]
}
 E=thisdict[“colors”]
 Print(E)
N.I.T Srinagar 110
Get Keys
 The keys() method will return a list of all the keys in the dictionary.
 Example
 Get a list of the keys:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.keys()
print(x) #before the change
car["color"] = "white"
print(x) #after the change
N.I.T Srinagar 111
Get Values
 The values() method will return a list of all the values in the dictionary.
 Example
 Get a list of the values:
 car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.values()
print(x) #before the change
car["year"] = 2020
print(x) #after the change
N.I.T Srinagar 112
Change Values
 You can change the value of a specific item by referring to
its key name:
 Example
 Change the "year" to 2018:
 car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(car)
car[“model"] = “swift”
 print(car)
N.I.T Srinagar 113
Update Dictionary
 The update() method will update the dictionary with the items
from the given argument.
 The argument must be a dictionary, or an iterable object with
key:value pairs.
 Example
 Update the "year" of the car by using the update() method:
 thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)
thisdict.update({"year": 2020})
print(thisdict)
N.I.T Srinagar 114
Add Dictionary Items
 Adding an item to the dictionary is done by using a
new index key and assigning a value to it:
 Example
 thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["color"] = "red"
print(thisdict)
N.I.T Srinagar 115
Update Dictionary
 The update() method will update the dictionary with the items
from a given argument. If the item does not exist, the item will
be added.
 The argument must be a dictionary, or an iterable object with
key:value pairs.
 Example
 Add a color item to the dictionary by using the update() method:
 thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.update({“color": "red"})
N.I.T Srinagar 116
Remove Dictionary Items
 The pop() method removes the item with the specified
key name:
 thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.pop("model")
print(thisdict)
N.I.T Srinagar 117
 The popitem() method removes the last inserted item
(in versions before 3.7, a random item is removed
instead):
 thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.popitem()
print(thisdict)
N.I.T Srinagar 118
 The del keyword removes the item with the specified
key name:
 thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
del thisdict["model"]
print(thisdict)
N.I.T Srinagar 119
 The del keyword can also delete the dictionary
completely:
 thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
del thisdict
print(thisdict) #this will cause an error because
"thisdict" no longer exists.
N.I.T Srinagar 120
Copy a Dictionary
 Make a copy of a dictionary with the copy() method:
 thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
newdict= thisdict.copy()
print(mydict)
N.I.T Srinagar 121
 Make a copy of a dictionary with the dict() function:
 thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
mydict = dict(thisdict)
print(mydict)
N.I.T Srinagar 122
If ... Else
 Python supports the usual logical conditions from
mathematics:
 Equals: a == b
 Not Equals: a != b
 Less than: a < b
 Less than or equal to: a <= b
 Greater than: a > b
 Greater than or equal to: a >= b
 These conditions can be used in several ways, most
commonly in "if statements" and loops.
N.I.T Srinagar 123
 An "if statement" is written by using the if keyword.
a = 33
b = 200
if b > a:
print("b is greater than a")
 In this example we use two variables, a and b, which
are used as part of the if statement to test whether b is
greater than a. As a is 33, and b is 200, we know that
200 is greater than 33, and so we print to screen that "b
is greater than a".
N.I.T Srinagar 124
 Python relies on indentation (whitespace at the
beginning of a line) to define scope in the code. Other
programming languages often use curly-brackets for
this purpose.
 If statement, without indentation (will raise an error):
a = 33
b = 200
if b > a:
print("b is greater than a") # you will get an error
N.I.T Srinagar 125
Elif
 The elif keyword is pythons way of saying "if the previous
conditions were not true, then try this condition".
a = 33
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
In this example a is equal to b, so the first condition is not
true, but the elif condition is true, so we print to screen that
"a and b are equal".
N.I.T Srinagar 126
Else
 The else keyword catches anything which isn't caught by the
preceding conditions.
a = 200
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print("a is greater than b")
In this example a is greater than b, so the first condition is not true,
also the elif condition is not true, so we go to the else condition and
print to screen that "a is greater than b".
N.I.T Srinagar 127
 You can also have an else without the elif:
a = 200
b = 33
if b > a:
print("b is greater than a")
else:
print("b is not greater than a")
N.I.T Srinagar 128
Short Hand If
 If you have only one statement to execute, you can put
it on the same line as the if statement.
 One line if statement:
if a > b: print("a is greater than b")
N.I.T Srinagar 129
Short Hand If ... Else
 If you have only one statement to execute, one for if,
and one for else, you can put it all on the same line:
 One line if else statement:
a = 2
b = 330
print("A") if a > b else print("B")
N.I.T Srinagar 130
 You can also have multiple else statements on the same
line:
 One line if else statement, with 3 conditions:
a = 330
b = 330
print("A") if a > b else print("=") if a == b else print("B")
N.I.T Srinagar 131
And
 The and keyword is a logical operator, and is used to
combine conditional statements:
 Test if a is greater than b, AND if c is greater than a:
a = 200
b = 33
c = 500
if a > b and c > a:
print("Both conditions are True")
N.I.T Srinagar 132
Or
 The or keyword is a logical operator, and is used to
combine conditional statements:
 Test if a is greater than b, OR if a is greater than c:
a = 200
b = 33
c = 500
if a > b or a > c:
print("At least one of the conditions is True")
N.I.T Srinagar 133
Nested If
 You can have if statements inside if statements, this is
called nested if statements.
x = 41
if x > 10:
print("Above ten,")
if x > 20:
print("and also above 20!")
else:
print("but not above 20.")
N.I.T Srinagar 134
Check number is positive
num = float(input("Enter a number: "))
if num >= 0:
if num == 0:
print("Zero")
else:
print("Positive number")
else:
print("Negative number")
N.I.T Srinagar 135
The pass Statement
 if statements cannot be empty, but if you for some
reason have an if statement with no content, put in the
pass statement to avoid getting an error.
a = 33
b = 200
if b > a:
pass
N.I.T Srinagar 136
list=[4,3,5,6,7]
if list[0]>list[1]:
print("sucess")
else:
print("hello")
N.I.T Srinagar 137
Python While Loops
 With the while loop we can execute a set of statements
as long as a condition is true.
 Print i as long as i is less than 6:
i = 1
while i < 6:
print(i)
i += 1
remember to increment i, or else the loop will continue
forever.
N.I.T Srinagar 138
The break Statement
With the break statement we can stop the loop even if
the while condition is true:
Exit the loop when i is 3:
i = 1
while i < 6:
print(i)
if i == 3:
break
i += 1
N.I.T Srinagar 139
The continue Statement
With the continue statement we can stop the current
iteration, and continue with the next:
Example
Continue to the next iteration if i is 3:
i = 0
while i < 6:
i += 1
if i == 3:
continue
print(i)
N.I.T Srinagar 140
The else Statement
With the else statement we can run a block of code once
when the condition no longer is true:
Print a message once the condition is false:
i = 1
while i < 6:
print(i)
i += 1
else:
print("i is no longer less than 6")
N.I.T Srinagar 141
list=[4,3,5,6,7]
s = 5
i = 0
while i < len(list):
if list[i] == s:
print(‘found sucessfully', list[i])
break
i += 1
else:
print("no match")
N.I.T Srinagar 142
Python For Loops
 A for loop is used for iterating over a sequence (that is
either a list, a tuple, a dictionary, a set, or a string).
 This is less like the for keyword in other programming
languages, and works more like an iterator method as
found in other object-orientated programming
languages.
 With the for loop we can execute a set of statements,
once for each item in a list, tuple, set etc.
N.I.T Srinagar 143
Print each fruit in a fruit list:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
The for loop does not require an indexing variable to set
beforehand.
N.I.T Srinagar 144
Even strings are iterable objects, they contain a sequence
of characters:
Example
Loop through the letters in the word "banana":
for x in "banana":
print(x)
N.I.T Srinagar 145
The break Statement
With the break statement we can stop the loop before it
has looped through all the items:
Example
Exit the loop when x is "banana":
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
if x == "banana":
break
N.I.T Srinagar 146
Exit the loop when x is "banana", but this time the break
comes before the print:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
if x == "banana":
break
print(x)
N.I.T Srinagar 147
The continue Statement
With the continue statement we can stop the current
iteration of the loop, and continue with the next:
Do not print banana:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
if x == "banana":
continue
print(x)
N.I.T Srinagar 148
The range() Function
To loop through a set of code a specified number of
times, we can use the range() function,
The range() function returns a sequence of numbers,
starting from 0 by default, and increments by 1 (by
default), and ends at a specified number.
Using the range() function:
for x in range(6):
print(x)
range(6) is not the values of 0 to 6, but the values 0 to 5.
N.I.T Srinagar 149
 The range() function defaults to 0 as a starting value,
however it is possible to specify the starting value by
adding a parameter: range(2, 6), which means values
from 2 to 6 (but not including 6):
for x in range(2, 6):
print(x)
N.I.T Srinagar 150
 The range() function defaults to increment the
sequence by 1, however it is possible to specify the
increment value by adding a third parameter: range(2,
30, 3):
for x in range(2, 30, 3):
print(x)
N.I.T Srinagar 151
Nested Loops
A nested loop is a loop inside a loop.
The "inner loop" will be executed one time for each iteration
of the "outer loop":
Print each adjective for every fruit:
adj = ["red", "big", "tasty"]
fruits = ["apple", "banana", "cherry"]
for x in adj:
for y in fruits:
print(x, y)
N.I.T Srinagar 152
The pass Statement
for loops cannot be empty, but if you for some reason
have a for loop with no content, put in the pass
statement to avoid getting an error.
for x in [0, 1, 2]:
pass
N.I.T Srinagar 153
Program to find the strings in list
are even or odd
even=["red","blue","green"]
for x in even:
if len(x)%2==0:
print("even string")
else:
print("odd string")
N.I.T Srinagar 154
Write a program to compute distance between
two points taking input from the user
x1=int(input("enter x1 : "))
x2=int(input("enter x2 : "))
y1=int(input("enter y1 : "))
y2=int(input("enter y2 : "))
result= ((((x2 - x1 )**2) + ((y2-y1)**2) )**0.5)
print("distance between",(x1,x2),"and",(y1,y2),"is :
",result)
N.I.T Srinagar 155
Program-3 Write a Program for checking whether the given number is an
even number or not.
Using a for loop.
Solution:
# Python program to check if the input number is odd or even.
# A number is even if division by 2 gives a remainder of 0.
# If the remainder is 1, it is an odd number.
num = int(input("Enter a number: "))
if (num % 2) == 0:
print("{0} is Even".format(num))
else:
print("{0} is Odd".format(num))
N.I.T Srinagar 156
Python program to swap two
variables
P = int( input("Please enter value for P: "))
Q = int( input("Please enter value for Q: "))
# To swap the value of two variables
# we will user third variable which is a temporary variable
temp = P
P = Q
Q = temp
print ("The Value of P after swapping: ", P)
print ("The Value of Q after swapping: ", Q)
N.I.T Srinagar 157
Find factorial of a number
num = int(input("Enter a number: "))
factorial = 1
if num < 0:
print(" Factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
for i in range(1,num + 1):
factorial = factorial*i
print("The factorial of",num,"is",factorial)
N.I.T Srinagar 158
Python Program to Find the Sum of Natural
Numbers
num = int(input("Enter a number: "))
if num < 0:
print("Enter a positive number")
else:
sum = 0
# use while loop to iterate un till zero
while(num > 0):
sum += num
num -= 1
print("The sum is",sum)
N.I.T Srinagar 159
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 both built-in or user-defined. It
helps the program to be concise, non-repetitive, and
organized.
N.I.T Srinagar 160
Syntax of Function
def function_name(parameters):
"""docstring"""
statement(s)
 Keyword def that marks the start of the function header.
 A function name to uniquely identify the function. Function naming
follows the same rules of writing identifiers in Python.
 Parameters (arguments) through which we pass values to a function.
They are optional.
 A colon (:) to mark the end of the function header.
 Optional documentation string (docstring) to describe what the
function does.
 One or more valid python statements that make up the function
body. Statements must have the same indentation level (usually 4
spaces).
 An optional return statement to return a value from the function.
N.I.T Srinagar 161
Python Creating Function
# A simple Python function
def fun():
print("Welcome to GFG")
N.I.T Srinagar 162
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("Welcome to GFG")
# Driver code to call a function
fun()
N.I.T Srinagar 163
Arguments of a Function
 Arguments are the values passed inside the parenthesis of
the function. A function can have any number of
arguments separated by a comma.
# A simple Python function to check
# whether x is even or odd
def evenOdd(x=10):
if (x % 2 == 0):
print("even")
else:
print("odd")
# Driver code to call the function
evenOdd(5)
N.I.T Srinagar 164
Types of Arguments
 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)
N.I.T Srinagar 165
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(firstname, lastname):
print(firstname, lastname)
# Keyword arguments
student(firstname='Geeks', lastname='Practice')
student(lastname='Practice', firstname='Geeks')
N.I.T Srinagar 166
The return statement
 The function return statement is used to exit from a
function and go back to the function caller and return
the specified value or data item to the caller.
Syntax: return [expression_list]
 The return statement can consist of a variable, an
expression, or a constant which is returned to the end
of the function execution. If none of the above is
present with the return statement a None object is
returned.
N.I.T Srinagar 167
def square_value(num):
"""This function returns the square
value of the entered number"""
return num**2
print(square_value(2))
print(square_value(-4))
N.I.T Srinagar 168
def my_function(food):
for x in food:
print(x)
fruits = ["apple", "banana", "cherry"]
my_function(fruits)
N.I.T Srinagar 169
Python File Handling
 Till now, we were taking the input from the console and writing it back
to the console to interact with the user.
 Sometimes, it is not enough to only display the data on the console.
The data to be displayed may be very large, and only a limited amount
of data can be displayed on the console since the memory is volatile, it
is impossible to recover the programmatically generated data again and
again.
 The file handling plays an important role when the data needs to be
stored permanently into the file. A file is a named location on disk to
store related information. We can access the stored information (non-
volatile) after the program termination.
 The file-handling implementation is slightly lengthy or complicated in
the other programming language, but it is easier and shorter in Python.
 In Python, files are treated in two modes as text or binary. The file may
be in the text or binary format, and each line of a file is ended with the
special character.
N.I.T Srinagar 170
 File operation can be done in the following order.
 Open a file
 Read or write - Performing operation
 Close the file
N.I.T Srinagar 171
 Python provides inbuilt functions for creating, writing
and reading files. There are two types of files that can
be handled in Python, normal text files and binary
files (written in binary language, 0s and 1s).
 Text files: In this type of file, Each line of text is
terminated with a special character called EOL (End
of Line), which is the new line character (‘n’) in
Python by default.
 Binary files: In this type of file, there is no terminator
for a line and the data is stored after converting it into
machine-understandable binary language.
N.I.T Srinagar 172
Opening a file
 Opening a file refers to getting the file ready either for
reading or for writing. This can be done using the
open(my_file,) function. This function returns a file object
and takes two arguments, one that accepts the file name
and another that accepts the mode(Access Mode).
 Access modes govern the type of operations possible in the
opened file. It refers to how the file will be used once it’s
opened. These modes also define the location of the File
Handle in the file. File handle is like a cursor, which
defines from where the data has to be read or written in the
file. There are 6 access modes in python.
N.I.T Srinagar 173
 Read Only (‘r’): Open text file for reading. The handle is positioned at the
beginning of the file. If the file does not exist, raises I/O error. This is also the
default mode in which the file is opened.
 Read and Write (‘r+’): Open the file for reading and writing. The handle is
positioned at the beginning of the file. Raises I/O error if the file does not
exist.
 Write Only (‘w’): Open the file for writing. For existing file, the data is
truncated and over-written. The handle is positioned at the beginning of the
file. Creates the file if the file does not exist.
 Write and Read (‘w+’): Open the file for reading and writing. For existing file,
data is truncated and over-written. The handle is positioned at the beginning
of the file.
 Append Only (‘a’): Open the file for writing. The file is created if it does not
exist. The handle is positioned at the end of the file. The data being written will
be inserted at the end, after the existing data.
 Append and Read (‘a+’): Open the file for reading and writing. The file is
created if it does not exist. The handle is positioned at the end of the file. The
data being written will be inserted at the end, after the existing data.
N.I.T Srinagar 174
 The file should exist in the same directory as the Python script,
otherwise full address of the file should be written.
 read the content of the file using Python.
# Python program to demonstrate
# opening a file
# Open function to open the file "myfile.txt"
# (same directory) in read mode and store
# it's reference in the variable file1
file1 = open("myfile.txt")
# Reading from file
print(file1.read())
file1.close()
N.I.T Srinagar 175
write more data to the above file
using Python.
# Python program to demonstrate
# opening a file
# Open function to open the file "myfile.txt"
# (same directory) in append mode and store
# it's reference in the variable file1
file1 = open("myfile.txt", "a")
# Writing to file
file1.write("nWriting to file :)")
# Closing file
file1.close()
N.I.T Srinagar 176
Closing a file
 close() function closes the file and frees the memory
space acquired by that file. It is used at the time when
the file is no longer needed or if it is to be opened in a
different file mode.
N.I.T Srinagar 177
file2 = open(r"C:UsersshahidDesktopSER.txt", "r+")
print(file2.read())
N.I.T Srinagar 178
Read Only Parts of the File
By default the read() method returns the whole text, but
you can also specify how many characters you want to
return:
Example
Return the 5 first characters of the file:
f = open("demofile.txt", "r")
print(f.read(5))
N.I.T Srinagar 179
Read Lines
 You can return one line by using the readline()
method:
 Example
 Read one line of the file:
f = open("demofile.txt", "r")
print(f.readline())
N.I.T Srinagar 180
Python Delete File
 To delete a file, you must import the OS module, and
run its os.remove() function:
 Example
 Remove the file "demofile.txt":
import os
os.remove("demofile.txt")
N.I.T Srinagar 181
Delete Folder
 To delete an entire folder, use the os.rmdir() method:
 Example
 Remove the folder "myfolder":
import os
os.rmdir("myfolder")
N.I.T Srinagar 182
Create a New File
 To create a new file in Python, use the open() method, with
one of the following parameters:
 "x" - Create - will create a file, returns an error if the file
exist
 "a" - Append - will create a file if the specified file does not
exist
 "w" - Write - will create a file if the specified file does not
exist
N.I.T Srinagar 183
f = open("myfile.txt", "x")
Create a new file if it does not exist:
f = open("myfile.txt", "w")
N.I.T Srinagar 184
Python Exception
 An exception can be defined as an unusual condition in a
program resulting in the interruption in the flow of the
program.
 Whenever an exception occurs, the program stops the
execution, and thus the further code is not executed.
Therefore, an exception is the run-time errors that are
unable to handle to Python script.
 An exception is a Python object that represents an error
 Python provides a way to handle the exception so that the
code can be executed without any interruption. If we do
not handle the exception, the interpreter doesn't execute
all the code that exists after the exception.
N.I.T Srinagar 185
 A list of common exceptions that can be thrown from a
standard Python program:
 ZeroDivisionError: Occurs when a number is divided
by zero.
 NameError: It occurs when a name is not found. It
may be local or global.
 IndentationError: If incorrect indentation is given.
 IOError: It occurs when Input Output operation fails.
 EOFError: It occurs when the end of the file is
reached, and yet operations are being performed.
N.I.T Srinagar 186
The problem without handling
exceptions
 Suppose we have two variables a and b, which take the
input from the user and perform the division of these
values. What if the user entered the zero as the
denominator? It will interrupt the program execution
and through a ZeroDivision exception.
N.I.T Srinagar 187
N.I.T Srinagar 188
 The above program is syntactically correct, but it
through the error because of unusual input. That kind
of programming may not be suitable or recommended
for the projects because these projects are required
uninterrupted execution. That's why an exception-
handling plays an essential role in handling these
unexpected exceptions.
N.I.T Srinagar 189
Exception handling in python
 The try-expect statement
 If the Python program contains suspicious code that
may throw the exception, we must place that code in
the try block. The try block must be followed with the
except statement, which contains a block of code that
will be executed if there is some exception in the try
block.
N.I.T Srinagar 190
N.I.T Srinagar 191
N.I.T Srinagar 192
 We can also use the else statement with the try-except
statement in which, we can place the code which will
be executed in the scenario if no exception occurs in
the try block.
N.I.T Srinagar 193
N.I.T Srinagar 194
N.I.T Srinagar 195
The except statement with no
exception
 Python provides the flexibility not to specify the name of
exception with the exception statement.
try:
a = int(input("Enter a:"))
b = int(input("Enter b:"))
c = a/b;
print("a/b = %d"%c)
except:
print("can't divide by zero")
else:
print("Hi I am else block")
N.I.T Srinagar 196
try:
#this will throw an exception if the file doesn't exist.
fileptr = open("file.txt","r")
except IOError:
print("File not found")
else:
print("The file opened successfully")
fileptr.close()
N.I.T Srinagar 197
Declaring Multiple Exceptions
 The Python allows us to declare the multiple
exceptions with the except clause. Declaring multiple
exceptions is useful in the cases where a try block
throws multiple exceptions.
N.I.T Srinagar 198
try:
file=open(“textl.txt”)
a=10/0;
except(ArithmeticError, IOError):
print("Arithmetic Exception")
except:
print(“noi error Exception")
else:
print("Successfully Done")
N.I.T Srinagar 199
The try...finally block
 You can use a finally: block along with a try: block.
The finally block is a place to put any code that must
execute, whether the try-block raised an exception or
not.
N.I.T Srinagar 200
N.I.T Srinagar 201
try:
fileptr = open("file2.txt","r")
try:
fileptr.write("Hi I am good")
finally:
fileptr.close()
print("file closed")
except:
print("Error")
N.I.T Srinagar 202
What are Python Modules?
 In Python, Modules are simply files with the “.py” extension
containing Python code that can be imported inside another
Python Program.
 In simple terms, we can consider a module to be the same as a
code library or a file that contains a set of functions that you
want to include in your application.
 With the help of modules, we can organize related functions,
classes, or any code block in the same file. So, It is considered a
best practice while writing bigger codes for production-level
projects in Data Science is to split the large Python code blocks
into modules containing up to 300–400 lines of code.
N.I.T Srinagar 203
 The module contains the following components:
 Definitions and implementation of classes,
 Variables, and
 Functions that can be used inside another program.
N.I.T Srinagar 204
 Suppose we want to make an application for a calculator.
We want to include few operations in our application such
as addition, subtraction, multiplication, division, etc.
 Now, here what we will be doing is to break the complete
code into separate parts and simply create one module for
all these operations or separate modules for each of the
operations. And then we can call these modules in our
main program logic.
 Here the core idea is to minimize the code, and if we create
modules, it doesn’t mean we can only use it for this
program, but we can even call these modules for other
programs as well.
N.I.T Srinagar 205
How to create Python Modules?
 To create a module, we have to save the code that we wish
in a file with the file extension “.py”. Then, the name of the
Python file becomes the name of the module.
 In this program, a function is created with the name
“welcome” and save this file with the name mymodule.py
i.e. name of the file, and with the extension “.py”.
 We saved the following code in a file named mymodule.py
N.I.T Srinagar 206
 To incorporate the module into our program, we will
use the import keyword, and to get only a few or
specific methods or functions from a module, we use
the from keyword.
 NOTE: When we are using a function from a module,
then we use the following syntax:
N.I.T Srinagar 207
N.I.T Srinagar 208
N.I.T Srinagar 209
N.I.T Srinagar 210
Python Built-in Modules
 As we know that the Python interactive shell has a number
of built-in functions. As a shell start, these functions are
loaded automatically and are always available, such as,
 print() and input() for I/O,
 Number conversion functions such as int(), float(),
complex(),
 Data type conversions such as list(), tuple(), set(), etc.
 In addition to these many built-in functions, there are also
a large number of pre-defined functions available as a part
of libraries bundled with Python distributions. These
functions are defined in modules which are known as
built-in modules.
N.I.T Srinagar 211
import math
print("The value of pi is", math.pi)
N.I.T Srinagar 212

Contenu connexe

Tendances

Lesson 02 python keywords and identifiers
Lesson 02   python keywords and identifiersLesson 02   python keywords and identifiers
Lesson 02 python keywords and identifiersNilimesh Halder
 
Variables & Data Types In Python | Edureka
Variables & Data Types In Python | EdurekaVariables & Data Types In Python | Edureka
Variables & Data Types In Python | EdurekaEdureka!
 
Python Course | Python Programming | Python Tutorial | Python Training | Edureka
Python Course | Python Programming | Python Tutorial | Python Training | EdurekaPython Course | Python Programming | Python Tutorial | Python Training | Edureka
Python Course | Python Programming | Python Tutorial | Python Training | EdurekaEdureka!
 
Python Tutorial For Beginners | Python Crash Course - Python Programming Lang...
Python Tutorial For Beginners | Python Crash Course - Python Programming Lang...Python Tutorial For Beginners | Python Crash Course - Python Programming Lang...
Python Tutorial For Beginners | Python Crash Course - Python Programming Lang...Edureka!
 
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Python Functions Tutorial | Working With Functions In Python | Python Trainin...Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Python Functions Tutorial | Working With Functions In Python | Python Trainin...Edureka!
 
Basic Python Programming: Part 01 and Part 02
Basic Python Programming: Part 01 and Part 02Basic Python Programming: Part 01 and Part 02
Basic Python Programming: Part 01 and Part 02Fariz Darari
 
Intro to Python Programming Language
Intro to Python Programming LanguageIntro to Python Programming Language
Intro to Python Programming LanguageDipankar Achinta
 
Introduction to Python
Introduction to PythonIntroduction to Python
Introduction to PythonNowell Strite
 
Python Programming Language | Python Classes | Python Tutorial | Python Train...
Python Programming Language | Python Classes | Python Tutorial | Python Train...Python Programming Language | Python Classes | Python Tutorial | Python Train...
Python Programming Language | Python Classes | Python Tutorial | Python Train...Edureka!
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to pythonYi-Fan Chu
 
Function in Python
Function in PythonFunction in Python
Function in PythonYashdev Hada
 

Tendances (20)

Lesson 02 python keywords and identifiers
Lesson 02   python keywords and identifiersLesson 02   python keywords and identifiers
Lesson 02 python keywords and identifiers
 
Variables & Data Types In Python | Edureka
Variables & Data Types In Python | EdurekaVariables & Data Types In Python | Edureka
Variables & Data Types In Python | Edureka
 
Python basics
Python basicsPython basics
Python basics
 
Python Course | Python Programming | Python Tutorial | Python Training | Edureka
Python Course | Python Programming | Python Tutorial | Python Training | EdurekaPython Course | Python Programming | Python Tutorial | Python Training | Edureka
Python Course | Python Programming | Python Tutorial | Python Training | Edureka
 
Python basics
Python basicsPython basics
Python basics
 
Python Tutorial For Beginners | Python Crash Course - Python Programming Lang...
Python Tutorial For Beginners | Python Crash Course - Python Programming Lang...Python Tutorial For Beginners | Python Crash Course - Python Programming Lang...
Python Tutorial For Beginners | Python Crash Course - Python Programming Lang...
 
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Python Functions Tutorial | Working With Functions In Python | Python Trainin...Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
 
Basic Python Programming: Part 01 and Part 02
Basic Python Programming: Part 01 and Part 02Basic Python Programming: Part 01 and Part 02
Basic Python Programming: Part 01 and Part 02
 
Python Tutorial Part 1
Python Tutorial Part 1Python Tutorial Part 1
Python Tutorial Part 1
 
Python : Data Types
Python : Data TypesPython : Data Types
Python : Data Types
 
Python Basics
Python BasicsPython Basics
Python Basics
 
Python ppt
Python pptPython ppt
Python ppt
 
Intro to Python Programming Language
Intro to Python Programming LanguageIntro to Python Programming Language
Intro to Python Programming Language
 
Introduction to Python
Introduction to PythonIntroduction to Python
Introduction to Python
 
Python basic
Python basicPython basic
Python basic
 
Object oriented programming in python
Object oriented programming in pythonObject oriented programming in python
Object oriented programming in python
 
Python Programming Language | Python Classes | Python Tutorial | Python Train...
Python Programming Language | Python Classes | Python Tutorial | Python Train...Python Programming Language | Python Classes | Python Tutorial | Python Train...
Python Programming Language | Python Classes | Python Tutorial | Python Train...
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
 
Function in Python
Function in PythonFunction in Python
Function in Python
 
Python Programming
Python ProgrammingPython Programming
Python Programming
 

Similaire à Python Programming

Python_Introduction_Good_PPT.pptx
Python_Introduction_Good_PPT.pptxPython_Introduction_Good_PPT.pptx
Python_Introduction_Good_PPT.pptxlemonchoos
 
IRJET- Python: Simple though an Important Programming Language
IRJET- Python: Simple though an Important Programming LanguageIRJET- Python: Simple though an Important Programming Language
IRJET- Python: Simple though an Important Programming LanguageIRJET Journal
 
Python Programming and ApplicationsUnit-1.docx
Python Programming and ApplicationsUnit-1.docxPython Programming and ApplicationsUnit-1.docx
Python Programming and ApplicationsUnit-1.docxManohar k
 
a9855c3532e13484ee6a39ba30218896d7c0d863-1676987272842.pptx
a9855c3532e13484ee6a39ba30218896d7c0d863-1676987272842.pptxa9855c3532e13484ee6a39ba30218896d7c0d863-1676987272842.pptx
a9855c3532e13484ee6a39ba30218896d7c0d863-1676987272842.pptxcigogag569
 
introduction of python in data science
introduction of python in data scienceintroduction of python in data science
introduction of python in data sciencebhavesh lande
 
637b4894085c4_ppt.pptx
637b4894085c4_ppt.pptx637b4894085c4_ppt.pptx
637b4894085c4_ppt.pptxArjun123Bagri
 
Python final presentation kirti ppt1
Python final presentation kirti ppt1Python final presentation kirti ppt1
Python final presentation kirti ppt1Kirti Verma
 
Python - An Introduction
Python - An IntroductionPython - An Introduction
Python - An IntroductionSwarit Wadhe
 

Similaire à Python Programming (20)

Python basics
Python basicsPython basics
Python basics
 
Features of Python.pdf
Features of Python.pdfFeatures of Python.pdf
Features of Python.pdf
 
Python programming
Python programmingPython programming
Python programming
 
Python_Introduction_Good_PPT.pptx
Python_Introduction_Good_PPT.pptxPython_Introduction_Good_PPT.pptx
Python_Introduction_Good_PPT.pptx
 
Python unit1
Python unit1Python unit1
Python unit1
 
IRJET- Python: Simple though an Important Programming Language
IRJET- Python: Simple though an Important Programming LanguageIRJET- Python: Simple though an Important Programming Language
IRJET- Python: Simple though an Important Programming Language
 
Python Programming and ApplicationsUnit-1.docx
Python Programming and ApplicationsUnit-1.docxPython Programming and ApplicationsUnit-1.docx
Python Programming and ApplicationsUnit-1.docx
 
a9855c3532e13484ee6a39ba30218896d7c0d863-1676987272842.pptx
a9855c3532e13484ee6a39ba30218896d7c0d863-1676987272842.pptxa9855c3532e13484ee6a39ba30218896d7c0d863-1676987272842.pptx
a9855c3532e13484ee6a39ba30218896d7c0d863-1676987272842.pptx
 
Chapter - 1.pptx
Chapter - 1.pptxChapter - 1.pptx
Chapter - 1.pptx
 
Python Programming.pptx
Python Programming.pptxPython Programming.pptx
Python Programming.pptx
 
Govind.ppt.pptx
Govind.ppt.pptxGovind.ppt.pptx
Govind.ppt.pptx
 
introduction of python in data science
introduction of python in data scienceintroduction of python in data science
introduction of python in data science
 
Python basic
Python basicPython basic
Python basic
 
637b4894085c4_ppt.pptx
637b4894085c4_ppt.pptx637b4894085c4_ppt.pptx
637b4894085c4_ppt.pptx
 
Python final presentation kirti ppt1
Python final presentation kirti ppt1Python final presentation kirti ppt1
Python final presentation kirti ppt1
 
Introduction to Python
Introduction to PythonIntroduction to Python
Introduction to Python
 
Python Tutorials.pptx
Python Tutorials.pptxPython Tutorials.pptx
Python Tutorials.pptx
 
Python Programming Draft PPT.pptx
Python Programming Draft PPT.pptxPython Programming Draft PPT.pptx
Python Programming Draft PPT.pptx
 
Python Notes.pdf
Python Notes.pdfPython Notes.pdf
Python Notes.pdf
 
Python - An Introduction
Python - An IntroductionPython - An Introduction
Python - An Introduction
 

Dernier

THE SENDAI FRAMEWORK FOR DISASTER RISK REDUCTION
THE SENDAI FRAMEWORK FOR DISASTER RISK REDUCTIONTHE SENDAI FRAMEWORK FOR DISASTER RISK REDUCTION
THE SENDAI FRAMEWORK FOR DISASTER RISK REDUCTIONjhunlian
 
Ch10-Global Supply Chain - Cadena de Suministro.pdf
Ch10-Global Supply Chain - Cadena de Suministro.pdfCh10-Global Supply Chain - Cadena de Suministro.pdf
Ch10-Global Supply Chain - Cadena de Suministro.pdfChristianCDAM
 
Past, Present and Future of Generative AI
Past, Present and Future of Generative AIPast, Present and Future of Generative AI
Past, Present and Future of Generative AIabhishek36461
 
Correctly Loading Incremental Data at Scale
Correctly Loading Incremental Data at ScaleCorrectly Loading Incremental Data at Scale
Correctly Loading Incremental Data at ScaleAlluxio, Inc.
 
multiple access in wireless communication
multiple access in wireless communicationmultiple access in wireless communication
multiple access in wireless communicationpanditadesh123
 
Unit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfg
Unit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfgUnit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfg
Unit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfgsaravananr517913
 
Main Memory Management in Operating System
Main Memory Management in Operating SystemMain Memory Management in Operating System
Main Memory Management in Operating SystemRashmi Bhat
 
11. Properties of Liquid Fuels in Energy Engineering.pdf
11. Properties of Liquid Fuels in Energy Engineering.pdf11. Properties of Liquid Fuels in Energy Engineering.pdf
11. Properties of Liquid Fuels in Energy Engineering.pdfHafizMudaserAhmad
 
home automation using Arduino by Aditya Prasad
home automation using Arduino by Aditya Prasadhome automation using Arduino by Aditya Prasad
home automation using Arduino by Aditya Prasadaditya806802
 
Class 1 | NFPA 72 | Overview Fire Alarm System
Class 1 | NFPA 72 | Overview Fire Alarm SystemClass 1 | NFPA 72 | Overview Fire Alarm System
Class 1 | NFPA 72 | Overview Fire Alarm Systemirfanmechengr
 
Crushers to screens in aggregate production
Crushers to screens in aggregate productionCrushers to screens in aggregate production
Crushers to screens in aggregate productionChinnuNinan
 
welding defects observed during the welding
welding defects observed during the weldingwelding defects observed during the welding
welding defects observed during the weldingMuhammadUzairLiaqat
 
Transport layer issues and challenges - Guide
Transport layer issues and challenges - GuideTransport layer issues and challenges - Guide
Transport layer issues and challenges - GuideGOPINATHS437943
 
complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...asadnawaz62
 
DM Pillar Training Manual.ppt will be useful in deploying TPM in project
DM Pillar Training Manual.ppt will be useful in deploying TPM in projectDM Pillar Training Manual.ppt will be useful in deploying TPM in project
DM Pillar Training Manual.ppt will be useful in deploying TPM in projectssuserb6619e
 
US Department of Education FAFSA Week of Action
US Department of Education FAFSA Week of ActionUS Department of Education FAFSA Week of Action
US Department of Education FAFSA Week of ActionMebane Rash
 
Indian Dairy Industry Present Status and.ppt
Indian Dairy Industry Present Status and.pptIndian Dairy Industry Present Status and.ppt
Indian Dairy Industry Present Status and.pptMadan Karki
 
Comparative study of High-rise Building Using ETABS,SAP200 and SAFE., SAFE an...
Comparative study of High-rise Building Using ETABS,SAP200 and SAFE., SAFE an...Comparative study of High-rise Building Using ETABS,SAP200 and SAFE., SAFE an...
Comparative study of High-rise Building Using ETABS,SAP200 and SAFE., SAFE an...Erbil Polytechnic University
 
Industrial Safety Unit-IV workplace health and safety.ppt
Industrial Safety Unit-IV workplace health and safety.pptIndustrial Safety Unit-IV workplace health and safety.ppt
Industrial Safety Unit-IV workplace health and safety.pptNarmatha D
 
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdfCCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdfAsst.prof M.Gokilavani
 

Dernier (20)

THE SENDAI FRAMEWORK FOR DISASTER RISK REDUCTION
THE SENDAI FRAMEWORK FOR DISASTER RISK REDUCTIONTHE SENDAI FRAMEWORK FOR DISASTER RISK REDUCTION
THE SENDAI FRAMEWORK FOR DISASTER RISK REDUCTION
 
Ch10-Global Supply Chain - Cadena de Suministro.pdf
Ch10-Global Supply Chain - Cadena de Suministro.pdfCh10-Global Supply Chain - Cadena de Suministro.pdf
Ch10-Global Supply Chain - Cadena de Suministro.pdf
 
Past, Present and Future of Generative AI
Past, Present and Future of Generative AIPast, Present and Future of Generative AI
Past, Present and Future of Generative AI
 
Correctly Loading Incremental Data at Scale
Correctly Loading Incremental Data at ScaleCorrectly Loading Incremental Data at Scale
Correctly Loading Incremental Data at Scale
 
multiple access in wireless communication
multiple access in wireless communicationmultiple access in wireless communication
multiple access in wireless communication
 
Unit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfg
Unit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfgUnit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfg
Unit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfg
 
Main Memory Management in Operating System
Main Memory Management in Operating SystemMain Memory Management in Operating System
Main Memory Management in Operating System
 
11. Properties of Liquid Fuels in Energy Engineering.pdf
11. Properties of Liquid Fuels in Energy Engineering.pdf11. Properties of Liquid Fuels in Energy Engineering.pdf
11. Properties of Liquid Fuels in Energy Engineering.pdf
 
home automation using Arduino by Aditya Prasad
home automation using Arduino by Aditya Prasadhome automation using Arduino by Aditya Prasad
home automation using Arduino by Aditya Prasad
 
Class 1 | NFPA 72 | Overview Fire Alarm System
Class 1 | NFPA 72 | Overview Fire Alarm SystemClass 1 | NFPA 72 | Overview Fire Alarm System
Class 1 | NFPA 72 | Overview Fire Alarm System
 
Crushers to screens in aggregate production
Crushers to screens in aggregate productionCrushers to screens in aggregate production
Crushers to screens in aggregate production
 
welding defects observed during the welding
welding defects observed during the weldingwelding defects observed during the welding
welding defects observed during the welding
 
Transport layer issues and challenges - Guide
Transport layer issues and challenges - GuideTransport layer issues and challenges - Guide
Transport layer issues and challenges - Guide
 
complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...
 
DM Pillar Training Manual.ppt will be useful in deploying TPM in project
DM Pillar Training Manual.ppt will be useful in deploying TPM in projectDM Pillar Training Manual.ppt will be useful in deploying TPM in project
DM Pillar Training Manual.ppt will be useful in deploying TPM in project
 
US Department of Education FAFSA Week of Action
US Department of Education FAFSA Week of ActionUS Department of Education FAFSA Week of Action
US Department of Education FAFSA Week of Action
 
Indian Dairy Industry Present Status and.ppt
Indian Dairy Industry Present Status and.pptIndian Dairy Industry Present Status and.ppt
Indian Dairy Industry Present Status and.ppt
 
Comparative study of High-rise Building Using ETABS,SAP200 and SAFE., SAFE an...
Comparative study of High-rise Building Using ETABS,SAP200 and SAFE., SAFE an...Comparative study of High-rise Building Using ETABS,SAP200 and SAFE., SAFE an...
Comparative study of High-rise Building Using ETABS,SAP200 and SAFE., SAFE an...
 
Industrial Safety Unit-IV workplace health and safety.ppt
Industrial Safety Unit-IV workplace health and safety.pptIndustrial Safety Unit-IV workplace health and safety.ppt
Industrial Safety Unit-IV workplace health and safety.ppt
 
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdfCCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
 

Python Programming

  • 1. Presented by: Shahid Sultan Research Scholar National Institute of Technology Srinagar N.I.T Srinagar 1
  • 2. What is Python? Python is a popular programming language. It was created by Guido van Rossum, and released in 1991.  It is used for:  web development (server-side),  software development,  mathematics,  system scripting. N.I.T Srinagar 2
  • 3.  Python is a general-purpose interpreted, interactive, object-oriented, and high-level programming language. It was created by Guido van Rossum during 1985- 1990. Like Perl, Python source code is also available under the GNU General Public License (GPL). N.I.T Srinagar 3
  • 4.  Python is Interpreted − Python is processed at runtime by the interpreter. You do not need to compile your program before executing it. This is similar to PERL and PHP.  Python is Interactive − You can actually sit at a Python prompt and interact with the interpreter directly to write your programs.  Python is Object-Oriented − Python supports Object- Oriented style or technique of programming that encapsulates code within objects.  Python is a Beginner's Language − Python is a great language for the beginner-level programmers and supports the development of a wide range of applications from simple text processing to WWW browsers to games. N.I.T Srinagar 4
  • 5. Python History  Python was invented by Guido van Rossum in 1991 at CWI in Netherland. The idea of Python programming language has taken from the ABC programming language or we can say that ABC is a predecessor of Python language.  There is also a fact behind the choosing name Python. Guido van Rossum was a fan of the popular BBC comedy show of that time, "Monty Python's Flying Circus". So he decided to pick the name Python for his newly created programming language. N.I.T Srinagar 5
  • 6. Python Features 1. Easy Language  Python is an easy language. It is easy to read, write, learn and understand.  Python has a smooth learning curve. It is easy to learn.  Python has a simple syntax and Python code is easy to understand.  Since it’s easy to understand, you can easily read and understand someone else’s code.  Python is also easy to write because of its simple syntax.  Because it is an easy language, it is used in schools and universities to introduce students to programming. Python is for both startups and big companies. N.I.T Srinagar 6
  • 7. 2. Readable The Python language is designed to make developers life easy. Reading a Python code is like reading an English sentence. This is one of the key reason that makes Python best for beginners. Python uses indentation instead of curly braces, unlike other programming languages. This makes the code look clean and easier to understand. N.I.T Srinagar 7
  • 8. 3. Interpreted Language  Python is an interpreted language. It comes with the IDLE (Interactive Development Environment). This is an interpreter and follows the REPL structure (Read-Evaluate-Print-Loop). It executes and displays the output of one line at a time.  So it displays errors while you’re running a line and displays the entire stack trace for the error. N.I.T Srinagar 8
  • 9.  4. Dynamically-Typed Language  Python is not statically-typed like Java. You don’t need to declare data type while defining a variable. The interpreter determines this at runtime based on the types of the parts of the expression. This is easy for programmers but can create runtime errors.  Python follows duck-typing. It means, “If it looks like a duck, swims like a duck and quacks like a duck, it must be a duck.” N.I.T Srinagar 9
  • 10. 5. Object-Oriented  Python is object-oriented but supports both functional and object-oriented programming. Everything in Python is an object.  It has the OOP (Object-oriented programming) concepts like inheritance and polymorphism. N.I.T Srinagar 10
  • 11. 6. Popular and Large Community Support  Python has one of the largest communities on StackOverflow and Meetup. If you need help, the community will answer your questions.  They also already have many answered questions about Python. 7. Open-Source  Python is open-source and the community is always contributing to it to improve it. It is free and its source code is freely available to the public. You can download Python from the official Python Website. N.I.T Srinagar 11
  • 12. 8. Large Standard Library  The standard library is large and has many packages and modules with common and important functionality. If you need something that is available in this standard library, you don’t need to write it from scratch. Because of this, you can focus on more important things.  You can also install packages from the PyPI (Python Package Index) if you want even more functionality. 9. Platform-Independent  Python is platform-independent. If you write a program, it will run on different platforms like Windows, Mac and Linux. You don’t need to write them separately for each platform. 10. Extensible and Embeddable  Python is extensible. You can use code from other languages like C++ in your Python code.  It is also embeddable. You can embed your Python code in other languages like C++. N.I.T Srinagar 12
  • 13. 11. GUI Support  You can use Python to create GUI (Graphical User Interfaces). You can use tkinter, PyQt, wxPython or Pyside for this.  Python features a huge number of GUI frameworks available for it to variety of other cross-platform solutions. It binds to platform-specific technologies. 12. High-level Language  Python is a high-level language and C++ is mid-level. It is easy to understand and closer to the user. You don’t need to remember system architecture or manage the memory. N.I.T Srinagar 13
  • 14. Where is Python used? Python is a general-purpose, popular programming language and it is used in almost every technical field. The various areas of Python use are given below.  Data Science  Date Mining  Desktop Applications  Console-based Applications  Mobile Applications  Software Development  Artificial Intelligence  Web Applications  Enterprise Applications  3D CAD Applications  Machine Learning  Computer Vision or Image Processing Applications.  Speech Recognitions N.I.T Srinagar 14
  • 16. Python Indentation  Indentation refers to the spaces at the beginning of a code line.  Where in other programming languages the indentation in code is for readability only, the indentation in Python is very important.  Python uses indentation to indicate a block of code. N.I.T Srinagar 16
  • 17. if 5 > 2: print("Five is greater than two!")  Python will give you an error if you skip the indentation: if 5 > 2: print("Five is greater than two!") The number of spaces is up to you as a programmer, but it has to be at least one. N.I.T Srinagar 17
  • 18. if 5 > 2: print("Five is greater than two!") print("Five is greater than two!") if 5 > 2: print("Five is greater than two!")  You have to use the same number of spaces in the same block of code, otherwise Python will give you an error: if 5 > 2: print("Five is greater than two!") print("Five is greater than two!") N.I.T Srinagar 18
  • 19. Comments  Python has commenting capability for the purpose of in- code documentation.  Comments can be used to explain Python code.  Comments can be used to make the code more readable.  Comments can be used to prevent execution when testing code.  Comments start with a #, and Python will render the rest of the line as a comment: #This is a comment. print("Hello, World!") N.I.T Srinagar 19
  • 20.  Comments can be placed at the end of a line, and Python will ignore the rest of the line: print("Hello, World!") #This is a comment  To add a multiline comment you could insert a # for each line: #This is a comment #written in #more than just one line print("Hello, World!") N.I.T Srinagar 20
  • 21. Python Variables  Variables are containers for storing data values.  Variables are nothing but reserved memory locations to store values. This means that when you create a variable you reserve some space in memory.  Based on the data type of a variable, the interpreter allocates memory and decides what can be stored in the reserved memory. Therefore, by assigning different data types to variables, you can store integers, decimals or characters in these variables. N.I.T Srinagar 21
  • 22.  Python variables do not need explicit declaration to reserve memory space. The declaration happens automatically when you assign a value to a variable. The equal sign (=) is used to assign values to variables.  The operand to the left of the = operator is the name of the variable and the operand to the right of the = operator is the value stored in the variable. N.I.T Srinagar 22
  • 23. x = 5 y = "John" print (x) print(y)  Python allows you to assign a single value to several variables simultaneously a = b = c = 1 a,b,c = 1,2,"john“ N.I.T Srinagar 23
  • 24. Variable Names  A variable can have a short name (like x and y) or a more descriptive name (age, carname, total_volume).  A variable name must start with a letter or the underscore character  A variable name cannot start with a number  A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )  Variable names are case-sensitive (age, Age and AGE are three different variables) N.I.T Srinagar 24
  • 25.  Legal variable names: myvar = "John" my_var = "John" _my_var = "John" myVar = "John" MYVAR = "John" myvar2 = "John" N.I.T Srinagar 25
  • 26.  Illegal variable names: 2myvar = "John" my-var = "John" my var = "John" N.I.T Srinagar 26
  • 27. Data Types  The data stored in memory can be of many types. For example, a person's age is stored as a numeric value and his or her address is stored as alphanumeric characters.  Python has various standard data types that are used to define the operations possible on them and the storage method for each of them. N.I.T Srinagar 27
  • 28.  Python has five standard data types −  Numbers  String  List  Tuple  Dictionary N.I.T Srinagar 28
  • 29. Python 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 N.I.T Srinagar 29
  • 30.  To verify the type of any object in Python, use the type() function: X=4 Y=‘shahid’ Z=5.987 print(type(x)) print(type(y)) print(type(z)) N.I.T Srinagar 30
  • 31. Int  Int, or integer, is a whole number, positive or negative, without decimals, of unlimited length. x = 1458 y = 35656222554887711 z = -3255522 print(type(x)) print(type(y)) print(type(z)) N.I.T Srinagar 31
  • 32. Float  Float, or "floating point number" is a number, positive or negative, containing one or more decimals. x = 1.10 y = 1.0 z = -35.59 print(type(x)) print(type(y)) print(type(z)) N.I.T Srinagar 32
  • 33. Complex  Complex numbers are written with a "j" as the imaginary part: x = 3+5j y = 5j z = -5j print(type(x)) print(type(y)) print(type(z)) N.I.T Srinagar 33
  • 34. Type Conversion  You can convert from one type to another with the int(), float(), and complex() methods: x = 1 # int y = 2.8 # float z = 1j # complex #convert from int to float: a = float(x) #convert from float to int: b = int(y) #convert from int to complex: c = complex(x) print(a) print(b) print(c) print(type(a)) print(type(b)) print(type(c)) N.I.T Srinagar 34
  • 35. Random Number  Python has a built-in module called random that can be used to make random numbers: import random A= random.randrange(1, 5) N.I.T Srinagar 35
  • 36. Python Strings  Strings in Python are identified as a contiguous set of characters represented in the quotation marks. Python allows for either pairs of single or double quotes. 'hello' is the same as "hello“ print("Hello") print('Hello') N.I.T Srinagar 36
  • 37. Assign String to a Variable  Assigning a string to a variable is done with the variable name followed by an equal sign and the string: a = "Hello" print(a) N.I.T Srinagar 37
  • 38. Multiline Strings  You can assign a multiline string to a variable by using three quotes: a = ‘’’Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.’’’ print(a) N.I.T Srinagar 38
  • 39. a = '''Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.''' print(a) N.I.T Srinagar 39
  • 40. String Length  To get the length of a string, use the len() function. a = "Hello, World!" print(len(a)) N.I.T Srinagar 40
  • 41. Python - Slicing Strings  You can return a range of characters by using the slice syntax.  Specify the start index and the end index, separated by a colon, to return a part of the string.  Get the characters from position 2 to position 5 (not included): b = "Hello, World!“ S=b[2:5] Print(S) N.I.T Srinagar 41
  • 42. Slice From the Start  By leaving out the start index, the range will start at the first character:  Get the characters from the start to position 5 (not included): b = "Hello, World!" print(b[:5]) N.I.T Srinagar 42
  • 43. Slice To the End  By leaving out the end index, the range will go to the end: Get the characters from position 2, and all the way to the end: b = "Hello, World!" print(b[2:]) N.I.T Srinagar 43
  • 44. Upper Case  The upper() method returns the string in upper case: a = "Hello, World!“ B=a.upper() print(B) N.I.T Srinagar 44
  • 45. Lower Case  The lower() method returns the string in lower case: a = "Hello, World!" print(a.lower()) N.I.T Srinagar 45
  • 46. Replace String  The replace() method replaces a string with another string: a = "Hello, World!" B= a.replace("H", "J") Print(B) N.I.T Srinagar 46
  • 47. String Concatenation  To concatenate, or combine, two strings you can use the + operator.  Merge variable a with variable b into variable c: a = "Hello" b = "World" c = a + b print(c) HelloWorld! N.I.T Srinagar 47
  • 48.  To add a space between them, add a " ": a = "Hello" b = "World" c = a + " " + b print(c) N.I.T Srinagar 48
  • 49. String Format  we cannot combine strings and numbers like this: age = 36 txt = "My name is John, I am " + age print(txt) N.I.T Srinagar 49
  • 50.  But we can combine strings and numbers by using the format() method!  The format() method takes the passed arguments, formats them, and places them in the string where the placeholders {} are: N.I.T Srinagar 50
  • 51. age = 36 txt = "My name is John, and I am {},{}" D=txt.format(age) N.I.T Srinagar 51
  • 52. quantity = 3 itemno = 567 price = 49.95 myorder = "I want {} pieces of item {} for {} dollars." print(myorder.format(quantity, itemno, price)) N.I.T Srinagar 52
  • 53. Add Two Numbers # This program adds two numbers num1 = 1.5 num2 = 6.3 # Add two numbers sum = num1 + num2 # Display the sum print('The sum of {0} and {1} is {2}'.format(num1, num2, sum)) N.I.T Srinagar 53
  • 54. Add Two Numbers With User Input # Store input numbers num1 = input('Enter first number: ') num2 = input('Enter second number: ') # Add two numbers sum = float(num1) + float(num2) # Display the sum print('The sum of {0} and {1} is {2}'.format(num1, num2, sum)) N.I.T Srinagar 54
  • 55. # Python Program to Calculate Cube of a Number number = float(input(" Please Enter any numeric Value : ")) cube = number * number * number print("The Cube of a Given Number {0} = {1}".format(number, cube)) N.I.T Srinagar 55
  • 56. Types of Operator  Python language supports the following types of operators.  Arithmetic Operators  Comparison (Relational) Operators  Assignment Operators  Logical Operators  Bitwise Operators  Membership Operators  Identity Operators N.I.T Srinagar 56
  • 60. Bitwise Operators  Bitwise operator works on bits and performs bit by bit operation. Assume if a = 60; and b = 13;  Now in the binary format their values will be 0011 1100 and 0000 1101 respectively.  a = 0011 1100  b = 0000 1101  -----------------  a&b = 0000 1100  a|b = 0011 1101  a^b = 0011 0001  ~a = 1100 0011 N.I.T Srinagar 60
  • 64. LISTS  A list in Python is used to store the sequence of various types of data. Python lists are mutable type its mean we can modify its element after it created. However, Python consists of six data-types that are capable to store the sequences, but the most common and reliable type is the list.  A list can be defined as a collection of values or items of different types. The items in the list are separated with the comma (,) and enclosed with the square brackets []. N.I.T Srinagar 64
  • 65. L1 =[1, 2, 4, 3, 5, 6] L2 = [1, 2, 3, 4, 5, 6] The list has the following characteristics:  The lists are ordered.  The element of the list can access by index.  The lists are the mutable type.  The lists are mutable types.  A list can store the number of various elements. N.I.T Srinagar 65
  • 66.  a = [1,2,"Peter",4.50,"Ricky",5,6]  b = [1,2,5,"Peter",4.50,"Ricky",6]  a ==b N.I.T Srinagar 66
  • 67. List indexing and splitting  The indexing is processed in the same way as it happens with the strings. The elements of the list can be accessed by using the slice operator [].  The first element of the list is stored at the 0th index, the second element of the list is stored at the 1st index, and so on. N.I.T Srinagar 67
  • 69. list = [1,2,3,4,5,6,7] print(list[0]) print(list[1]) print(list[2]) print(list[3]) # Slicing the elements print(list[0:6]) # By default the index value is 0 so its starts from the 0th element and go for index -1. print(list[:]) print(list[2:5]) print(list[1:6:2]) N.I.T Srinagar 69
  • 70.  Unlike other languages, Python provides the flexibility to use the negative indexing also. The negative indices are counted from the right. The last element (rightmost) of the list has the index -1; its adjacent left element is present at the index -2 and so on until the left-most elements are encountered. N.I.T Srinagar 70
  • 73. Updating List values  Lists are the most versatile data structures in Python since they are mutable, and their values can be updated by using the slice and assignment operator. list = [1, 2, 3, 4, 5, 6] print(list) 1 2 3 4 5 6 # It will assign value to the value to the second index list[2] = 10; print(list) # Adding multiple-element list[1:3] = [89, 78] print(list) # It will add value at the end of the list list[-1] = 25 print(list) N.I.T Srinagar 73
  • 74.  Python also provides append() and insert() methods, which can be used to add values to the list.  to add an item to the end of the list, use the append() method: thislist = ["apple", "banana", "cherry"] thislist.append("orange") print(thislist) N.I.T Srinagar 74
  • 75.  To insert a list item at a specified index, use the insert() method. thislist = ["apple", "banana", "cherry"] thislist.insert(0, "orange") print(thislist) N.I.T Srinagar 75
  • 76. Remove List Items  The remove() method removes the specified item. thislist = ["apple", "banana", "cherry“] thislist.remove("banana") print(thislist) N.I.T Srinagar 76
  • 77.  The pop() method removes the specified index. thislist = ["apple", "banana", "cherry"] thislist.pop(1) print(thislist)  If you do not specify the index, the pop() method removes the last item. N.I.T Srinagar 77
  • 78.  The del keyword also removes the specified index: thislist = ["apple", "banana", "cherry"] del thislist[0] print(thislist)  The del keyword can also delete the list completely. thislist = ["apple", "banana", "cherry"] del thislist N.I.T Srinagar 78
  • 79.  The clear() method empties the list.  The list still remains, but it has no content. thislist = ["apple", "banana", "cherry"] thislist.clear() print(thislist) N.I.T Srinagar 79
  • 80. Tuple  A tuple is a collection of objects which ordered and immutable.  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. N.I.T Srinagar 80
  • 81. thistuple = ("apple", "banana", "cherry") print(thistuple)  Tuple items are ordered, unchangeable, and allow duplicate values.  Tuple items are indexed, the first item has index [0], the second item has index [1] etc. N.I.T Srinagar 81
  • 82.  When we say that tuples are ordered, it means that the items have a defined order, and that order will not change.  Tuples are unchangeable, meaning that we cannot change, add or remove items after the tuple has been created.  Since tuples are indexed, they can have items with the same value N.I.T Srinagar 82
  • 83. Tuple Length  To determine how many items a tuple has, use the len() function: thistuple = ("apple", "banana", "cherry") print(len(thistuple)) N.I.T Srinagar 83
  • 84. Create Tuple With One Item  To create a tuple with only one item, you have to add a comma after the item, otherwise Python will not recognize it as a tuple.  Example  One item tuple, remember the comma: thistuple = ("apple",) print(type(thistuple)) tuple #NOT a tuple thistuple = ("apple") print(type(thistuple)) string N.I.T Srinagar 84
  • 85. Tuple Items - Data Types  Tuple items can be of any data type: String, int and boolean data types: tuple1 = ("apple", "banana", "cherry") tuple2 = (1, 5, 7, 9, 3) tuple3 = (True, False, False)  A tuple can contain different data types:  A tuple with strings, integers and boolean values:  tuple1 = ("abc", 34, True, 40, "male") N.I.T Srinagar 85
  • 86. Access Tuple Items  You can access tuple items by referring to the index number, inside square brackets:  Print the second item in the tuple: thistuple = ("apple", "banana", "cherry") print(thistuple[1])  Negative indexing means start from the end.  -1 refers to the last item, -2 refers to the second last item etc.  Print the last item of the tuple: thistuple = ("apple", "banana", "cherry") print(thistuple[-1]) N.I.T Srinagar 86
  • 87. Range of Indexes  You can specify a range of indexes by specifying where to start and where to end the range.  When specifying a range, the return value will be a new tuple with the specified items. Example  Return the third, fourth, and fifth item:  thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango") print(thistuple[2:5]) N.I.T Srinagar 87
  • 88.  This example returns the items from the beginning to, but NOT included, "kiwi": thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango") print(thistuple[:4]) N.I.T Srinagar 88
  • 89.  By leaving out the end value, the range will go on to the end of the list:  Example  This example returns the items from "cherry" and to the end: thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango") print(thistuple[2:]) N.I.T Srinagar 89
  • 90. Update Tuples  Tuples are unchangeable, meaning that you cannot change, add, or remove items once the tuple is created.  Once a tuple is created, you cannot change its values. Tuples are unchangeable, or immutable as it also is called.  But there is a workaround. You can convert the tuple into a list, change the list, and convert the list back into a tuple. N.I.T Srinagar 90
  • 91.  Convert the tuple into a list to be able to change it: x = ("apple", "banana", "cherry") y = list(x) y[1] = "kiwi" x = tuple(y) print(x) N.I.T Srinagar 91
  • 92. Add Items  Since tuples are immutable, they do not have a build- in append() method, but there are other ways to add items to a tuple.  Convert into a list: Just like the workaround for changing a tuple, you can convert it into a list, add your item(s), and convert it back into a tuple. N.I.T Srinagar 92
  • 93.  Convert the tuple into a list, add "orange", and convert it back into a tuple: thistuple = ("apple", "banana", "cherry") y = list(thistuple) y.append("orange") thistuple = tuple(y) N.I.T Srinagar 93
  • 94. Add tuple to a tuple  You are allowed to add tuples to tuples, so if you want to add one item, (or many), create a new tuple with the item(s), and add it to the existing tuple:  Example  Create a new tuple with the value "orange", and add that tuple: thistuple = ("apple", "banana", "cherry") y = ("orange",) thistuple += y print(thistuple) N.I.T Srinagar 94
  • 95. Remove Items  Tuples are unchangeable, so you cannot remove items from it, but you can use the same workaround as we used for changing and adding tuple items:  Example  Convert the tuple into a list, remove "apple", and convert it back into a tuple: thistuple = ("apple", "banana", "cherry") y = list(thistuple) y.remove("apple") thistuple = tuple(y)  Or you can delete the tuple completely:  Example  The del keyword can delete the tuple completely: thistuple = ("apple", "banana", "cherry") del thistuple print(thistuple) #this will raise an error because the tuple no longer exists N.I.T Srinagar 95
  • 96. Python Sets  A set is a collection which is unordered, unchangeable*, and unindexed.  * Note: Set items are unchangeable, but you can remove items and add new items.  Sets are written with curly brackets.  Create a Set: thisset = {"apple", "banana", "cherry"} print(thisset) N.I.T Srinagar 96
  • 97.  Duplicates Not Allowed  Sets cannot have two items with the same value.  Duplicate values will be ignored: thisset = {"apple", "banana", "cherry", "apple"} print(thisset) N.I.T Srinagar 97
  • 98. Set Items - Data Types  Set items can be of any data type:  Example  String, int and boolean data types:  set1 = {"apple", "banana", "cherry"} set2 = {1, 5, 7, 9, 3} set3 = {True, False, False}  A set can contain different data types:  Example  A set with strings, integers and boolean values:  set1 = {"abc", 34, True, 40, "male"} N.I.T Srinagar 98
  • 99. Access Set Items  You cannot access items in a set by referring to an index or a key.  But you can loop through the set items using a for loop, or ask if a specified value is present in a set, by using the in keyword.  Example  Loop through the set, and print the values:  thisset = {"apple", "banana", "cherry"} for x in thisset: print(x) N.I.T Srinagar 99
  • 100. Change Items  Once a set is created, you cannot change its items, but you can add new items. N.I.T Srinagar 100
  • 101. Add Set Items  To add one item to a set use the add() method.  Example  Add an item to a set, using the add() method:  thisset = {"apple", "banana", "cherry"} thisset.add("orange") print(thisset) N.I.T Srinagar 101
  • 102.  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) N.I.T Srinagar 102
  • 103. Remove Set Items  To remove an item in a set, use the remove(), or the discard() method.  Example  Remove "banana" by using the remove() method:  thisset = {"apple", "banana", "cherry"} thisset.remove("banana") print(thisset)  Note: If the item to remove does not exist, remove() will raise an error.  Example  Remove "banana" by using the discard() method:  thisset = {"apple", "banana", "cherry"} thisset.discard("banana") print(thisset)  Note: If the item to remove does not exist, discard() will NOT raise an error.  You can also use the pop() method to remove an item, but this method will remove the last item. Remember that sets are unordered, so you will not know what item that gets removed.  The return value of the pop() method is the removed item. N.I.T Srinagar 103
  • 104.  Sets are unordered, so when using the pop() method, you do not know which item that gets removed.  The clear() method empties the set:  thisset = {"apple", "banana", "cherry"} thisset.clear() print(thisset)  The del keyword will delete the set completely:  thisset = {"apple", "banana", "cherry"} del thisset print(thisset) N.I.T Srinagar 104
  • 105. Dictionaries  Dictionaries are used to store data values in key:value pairs.  A dictionary is a collection which is ordered*, changeable and does not allow duplicates.  As of Python version 3.7, dictionaries are ordered. In Python 3.6 and earlier, dictionaries are unordered.  Dictionaries are written with curly brackets, and have keys and values: N.I.T Srinagar 105
  • 106. thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 } print(thisdict) N.I.T Srinagar 106
  • 107. car = { "brand": "Ford", "model": "Mustang", "year": 1964 } print(thisdict["brand"]) N.I.T Srinagar 107
  • 108.  Dictionaries are changeable, meaning that we can change, add or remove items after the dictionary has been created.  Dictionaries cannot have two items with the same key:  Duplicate values will overwrite existing values:  thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964, "year": 2020 } print(thisdict) N.I.T Srinagar 108
  • 109. Dictionary Length  To determine how many items a dictionary has, use the len() function:  Example  Print the number of items in the dictionary: Student{ “Name”: “Shahid” “Branch”: “IT” “Course”: “Ph.D” } S= len(Student) Print(S); N.I.T Srinagar 109
  • 110. Dictionary Items - Data Types  The values in dictionary items can be of any data type:  Example  String, int, boolean, and list data types:  thisdict = { "brand": "Ford", "electric": False, "year": 1964, "colors": ["red", "white", "blue"] }  E=thisdict[“colors”]  Print(E) N.I.T Srinagar 110
  • 111. Get Keys  The keys() method will return a list of all the keys in the dictionary.  Example  Get a list of the keys: car = { "brand": "Ford", "model": "Mustang", "year": 1964 } x = car.keys() print(x) #before the change car["color"] = "white" print(x) #after the change N.I.T Srinagar 111
  • 112. Get Values  The values() method will return a list of all the values in the dictionary.  Example  Get a list of the values:  car = { "brand": "Ford", "model": "Mustang", "year": 1964 } x = car.values() print(x) #before the change car["year"] = 2020 print(x) #after the change N.I.T Srinagar 112
  • 113. Change Values  You can change the value of a specific item by referring to its key name:  Example  Change the "year" to 2018:  car = { "brand": "Ford", "model": "Mustang", "year": 1964 } print(car) car[“model"] = “swift”  print(car) N.I.T Srinagar 113
  • 114. Update Dictionary  The update() method will update the dictionary with the items from the given argument.  The argument must be a dictionary, or an iterable object with key:value pairs.  Example  Update the "year" of the car by using the update() method:  thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 } print(thisdict) thisdict.update({"year": 2020}) print(thisdict) N.I.T Srinagar 114
  • 115. Add Dictionary Items  Adding an item to the dictionary is done by using a new index key and assigning a value to it:  Example  thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 } thisdict["color"] = "red" print(thisdict) N.I.T Srinagar 115
  • 116. Update Dictionary  The update() method will update the dictionary with the items from a given argument. If the item does not exist, the item will be added.  The argument must be a dictionary, or an iterable object with key:value pairs.  Example  Add a color item to the dictionary by using the update() method:  thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 } thisdict.update({“color": "red"}) N.I.T Srinagar 116
  • 117. Remove Dictionary Items  The pop() method removes the item with the specified key name:  thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 } thisdict.pop("model") print(thisdict) N.I.T Srinagar 117
  • 118.  The popitem() method removes the last inserted item (in versions before 3.7, a random item is removed instead):  thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 } thisdict.popitem() print(thisdict) N.I.T Srinagar 118
  • 119.  The del keyword removes the item with the specified key name:  thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 } del thisdict["model"] print(thisdict) N.I.T Srinagar 119
  • 120.  The del keyword can also delete the dictionary completely:  thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 } del thisdict print(thisdict) #this will cause an error because "thisdict" no longer exists. N.I.T Srinagar 120
  • 121. Copy a Dictionary  Make a copy of a dictionary with the copy() method:  thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 } newdict= thisdict.copy() print(mydict) N.I.T Srinagar 121
  • 122.  Make a copy of a dictionary with the dict() function:  thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 } mydict = dict(thisdict) print(mydict) N.I.T Srinagar 122
  • 123. If ... Else  Python supports the usual logical conditions from mathematics:  Equals: a == b  Not Equals: a != b  Less than: a < b  Less than or equal to: a <= b  Greater than: a > b  Greater than or equal to: a >= b  These conditions can be used in several ways, most commonly in "if statements" and loops. N.I.T Srinagar 123
  • 124.  An "if statement" is written by using the if keyword. a = 33 b = 200 if b > a: print("b is greater than a")  In this example we use two variables, a and b, which are used as part of the if statement to test whether b is greater than a. As a is 33, and b is 200, we know that 200 is greater than 33, and so we print to screen that "b is greater than a". N.I.T Srinagar 124
  • 125.  Python relies on indentation (whitespace at the beginning of a line) to define scope in the code. Other programming languages often use curly-brackets for this purpose.  If statement, without indentation (will raise an error): a = 33 b = 200 if b > a: print("b is greater than a") # you will get an error N.I.T Srinagar 125
  • 126. Elif  The elif keyword is pythons way of saying "if the previous conditions were not true, then try this condition". a = 33 b = 33 if b > a: print("b is greater than a") elif a == b: print("a and b are equal") In this example a is equal to b, so the first condition is not true, but the elif condition is true, so we print to screen that "a and b are equal". N.I.T Srinagar 126
  • 127. Else  The else keyword catches anything which isn't caught by the preceding conditions. a = 200 b = 33 if b > a: print("b is greater than a") elif a == b: print("a and b are equal") else: print("a is greater than b") In this example a is greater than b, so the first condition is not true, also the elif condition is not true, so we go to the else condition and print to screen that "a is greater than b". N.I.T Srinagar 127
  • 128.  You can also have an else without the elif: a = 200 b = 33 if b > a: print("b is greater than a") else: print("b is not greater than a") N.I.T Srinagar 128
  • 129. Short Hand If  If you have only one statement to execute, you can put it on the same line as the if statement.  One line if statement: if a > b: print("a is greater than b") N.I.T Srinagar 129
  • 130. Short Hand If ... Else  If you have only one statement to execute, one for if, and one for else, you can put it all on the same line:  One line if else statement: a = 2 b = 330 print("A") if a > b else print("B") N.I.T Srinagar 130
  • 131.  You can also have multiple else statements on the same line:  One line if else statement, with 3 conditions: a = 330 b = 330 print("A") if a > b else print("=") if a == b else print("B") N.I.T Srinagar 131
  • 132. And  The and keyword is a logical operator, and is used to combine conditional statements:  Test if a is greater than b, AND if c is greater than a: a = 200 b = 33 c = 500 if a > b and c > a: print("Both conditions are True") N.I.T Srinagar 132
  • 133. Or  The or keyword is a logical operator, and is used to combine conditional statements:  Test if a is greater than b, OR if a is greater than c: a = 200 b = 33 c = 500 if a > b or a > c: print("At least one of the conditions is True") N.I.T Srinagar 133
  • 134. Nested If  You can have if statements inside if statements, this is called nested if statements. x = 41 if x > 10: print("Above ten,") if x > 20: print("and also above 20!") else: print("but not above 20.") N.I.T Srinagar 134
  • 135. Check number is positive num = float(input("Enter a number: ")) if num >= 0: if num == 0: print("Zero") else: print("Positive number") else: print("Negative number") N.I.T Srinagar 135
  • 136. The pass Statement  if statements cannot be empty, but if you for some reason have an if statement with no content, put in the pass statement to avoid getting an error. a = 33 b = 200 if b > a: pass N.I.T Srinagar 136
  • 138. Python While Loops  With the while loop we can execute a set of statements as long as a condition is true.  Print i as long as i is less than 6: i = 1 while i < 6: print(i) i += 1 remember to increment i, or else the loop will continue forever. N.I.T Srinagar 138
  • 139. The break Statement With the break statement we can stop the loop even if the while condition is true: Exit the loop when i is 3: i = 1 while i < 6: print(i) if i == 3: break i += 1 N.I.T Srinagar 139
  • 140. The continue Statement With the continue statement we can stop the current iteration, and continue with the next: Example Continue to the next iteration if i is 3: i = 0 while i < 6: i += 1 if i == 3: continue print(i) N.I.T Srinagar 140
  • 141. The else Statement With the else statement we can run a block of code once when the condition no longer is true: Print a message once the condition is false: i = 1 while i < 6: print(i) i += 1 else: print("i is no longer less than 6") N.I.T Srinagar 141
  • 142. list=[4,3,5,6,7] s = 5 i = 0 while i < len(list): if list[i] == s: print(‘found sucessfully', list[i]) break i += 1 else: print("no match") N.I.T Srinagar 142
  • 143. Python For Loops  A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string).  This is less like the for keyword in other programming languages, and works more like an iterator method as found in other object-orientated programming languages.  With the for loop we can execute a set of statements, once for each item in a list, tuple, set etc. N.I.T Srinagar 143
  • 144. Print each fruit in a fruit list: fruits = ["apple", "banana", "cherry"] for x in fruits: print(x) The for loop does not require an indexing variable to set beforehand. N.I.T Srinagar 144
  • 145. Even strings are iterable objects, they contain a sequence of characters: Example Loop through the letters in the word "banana": for x in "banana": print(x) N.I.T Srinagar 145
  • 146. The break Statement With the break statement we can stop the loop before it has looped through all the items: Example Exit the loop when x is "banana": fruits = ["apple", "banana", "cherry"] for x in fruits: print(x) if x == "banana": break N.I.T Srinagar 146
  • 147. Exit the loop when x is "banana", but this time the break comes before the print: fruits = ["apple", "banana", "cherry"] for x in fruits: if x == "banana": break print(x) N.I.T Srinagar 147
  • 148. The continue Statement With the continue statement we can stop the current iteration of the loop, and continue with the next: Do not print banana: fruits = ["apple", "banana", "cherry"] for x in fruits: if x == "banana": continue print(x) N.I.T Srinagar 148
  • 149. The range() Function To loop through a set of code a specified number of times, we can use the range() function, The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and ends at a specified number. Using the range() function: for x in range(6): print(x) range(6) is not the values of 0 to 6, but the values 0 to 5. N.I.T Srinagar 149
  • 150.  The range() function defaults to 0 as a starting value, however it is possible to specify the starting value by adding a parameter: range(2, 6), which means values from 2 to 6 (but not including 6): for x in range(2, 6): print(x) N.I.T Srinagar 150
  • 151.  The range() function defaults to increment the sequence by 1, however it is possible to specify the increment value by adding a third parameter: range(2, 30, 3): for x in range(2, 30, 3): print(x) N.I.T Srinagar 151
  • 152. Nested Loops A nested loop is a loop inside a loop. The "inner loop" will be executed one time for each iteration of the "outer loop": Print each adjective for every fruit: adj = ["red", "big", "tasty"] fruits = ["apple", "banana", "cherry"] for x in adj: for y in fruits: print(x, y) N.I.T Srinagar 152
  • 153. The pass Statement for loops cannot be empty, but if you for some reason have a for loop with no content, put in the pass statement to avoid getting an error. for x in [0, 1, 2]: pass N.I.T Srinagar 153
  • 154. Program to find the strings in list are even or odd even=["red","blue","green"] for x in even: if len(x)%2==0: print("even string") else: print("odd string") N.I.T Srinagar 154
  • 155. Write a program to compute distance between two points taking input from the user x1=int(input("enter x1 : ")) x2=int(input("enter x2 : ")) y1=int(input("enter y1 : ")) y2=int(input("enter y2 : ")) result= ((((x2 - x1 )**2) + ((y2-y1)**2) )**0.5) print("distance between",(x1,x2),"and",(y1,y2),"is : ",result) N.I.T Srinagar 155
  • 156. Program-3 Write a Program for checking whether the given number is an even number or not. Using a for loop. Solution: # Python program to check if the input number is odd or even. # A number is even if division by 2 gives a remainder of 0. # If the remainder is 1, it is an odd number. num = int(input("Enter a number: ")) if (num % 2) == 0: print("{0} is Even".format(num)) else: print("{0} is Odd".format(num)) N.I.T Srinagar 156
  • 157. Python program to swap two variables P = int( input("Please enter value for P: ")) Q = int( input("Please enter value for Q: ")) # To swap the value of two variables # we will user third variable which is a temporary variable temp = P P = Q Q = temp print ("The Value of P after swapping: ", P) print ("The Value of Q after swapping: ", Q) N.I.T Srinagar 157
  • 158. Find factorial of a number num = int(input("Enter a number: ")) factorial = 1 if num < 0: print(" Factorial does not exist for negative numbers") elif num == 0: print("The factorial of 0 is 1") else: for i in range(1,num + 1): factorial = factorial*i print("The factorial of",num,"is",factorial) N.I.T Srinagar 158
  • 159. Python Program to Find the Sum of Natural Numbers num = int(input("Enter a number: ")) if num < 0: print("Enter a positive number") else: sum = 0 # use while loop to iterate un till zero while(num > 0): sum += num num -= 1 print("The sum is",sum) N.I.T Srinagar 159
  • 160. 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 both built-in or user-defined. It helps the program to be concise, non-repetitive, and organized. N.I.T Srinagar 160
  • 161. Syntax of Function def function_name(parameters): """docstring""" statement(s)  Keyword def that marks the start of the function header.  A function name to uniquely identify the function. Function naming follows the same rules of writing identifiers in Python.  Parameters (arguments) through which we pass values to a function. They are optional.  A colon (:) to mark the end of the function header.  Optional documentation string (docstring) to describe what the function does.  One or more valid python statements that make up the function body. Statements must have the same indentation level (usually 4 spaces).  An optional return statement to return a value from the function. N.I.T Srinagar 161
  • 162. Python Creating Function # A simple Python function def fun(): print("Welcome to GFG") N.I.T Srinagar 162
  • 163. 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("Welcome to GFG") # Driver code to call a function fun() N.I.T Srinagar 163
  • 164. Arguments of a Function  Arguments are the values passed inside the parenthesis of the function. A function can have any number of arguments separated by a comma. # A simple Python function to check # whether x is even or odd def evenOdd(x=10): if (x % 2 == 0): print("even") else: print("odd") # Driver code to call the function evenOdd(5) N.I.T Srinagar 164
  • 165. Types of Arguments  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) N.I.T Srinagar 165
  • 166. 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(firstname, lastname): print(firstname, lastname) # Keyword arguments student(firstname='Geeks', lastname='Practice') student(lastname='Practice', firstname='Geeks') N.I.T Srinagar 166
  • 167. The return statement  The function return statement is used to exit from a function and go back to the function caller and return the specified value or data item to the caller. Syntax: return [expression_list]  The return statement can consist of a variable, an expression, or a constant which is returned to the end of the function execution. If none of the above is present with the return statement a None object is returned. N.I.T Srinagar 167
  • 168. def square_value(num): """This function returns the square value of the entered number""" return num**2 print(square_value(2)) print(square_value(-4)) N.I.T Srinagar 168
  • 169. def my_function(food): for x in food: print(x) fruits = ["apple", "banana", "cherry"] my_function(fruits) N.I.T Srinagar 169
  • 170. Python File Handling  Till now, we were taking the input from the console and writing it back to the console to interact with the user.  Sometimes, it is not enough to only display the data on the console. The data to be displayed may be very large, and only a limited amount of data can be displayed on the console since the memory is volatile, it is impossible to recover the programmatically generated data again and again.  The file handling plays an important role when the data needs to be stored permanently into the file. A file is a named location on disk to store related information. We can access the stored information (non- volatile) after the program termination.  The file-handling implementation is slightly lengthy or complicated in the other programming language, but it is easier and shorter in Python.  In Python, files are treated in two modes as text or binary. The file may be in the text or binary format, and each line of a file is ended with the special character. N.I.T Srinagar 170
  • 171.  File operation can be done in the following order.  Open a file  Read or write - Performing operation  Close the file N.I.T Srinagar 171
  • 172.  Python provides inbuilt functions for creating, writing and reading files. There are two types of files that can be handled in Python, normal text files and binary files (written in binary language, 0s and 1s).  Text files: In this type of file, Each line of text is terminated with a special character called EOL (End of Line), which is the new line character (‘n’) in Python by default.  Binary files: In this type of file, there is no terminator for a line and the data is stored after converting it into machine-understandable binary language. N.I.T Srinagar 172
  • 173. Opening a file  Opening a file refers to getting the file ready either for reading or for writing. This can be done using the open(my_file,) function. This function returns a file object and takes two arguments, one that accepts the file name and another that accepts the mode(Access Mode).  Access modes govern the type of operations possible in the opened file. It refers to how the file will be used once it’s opened. These modes also define the location of the File Handle in the file. File handle is like a cursor, which defines from where the data has to be read or written in the file. There are 6 access modes in python. N.I.T Srinagar 173
  • 174.  Read Only (‘r’): Open text file for reading. The handle is positioned at the beginning of the file. If the file does not exist, raises I/O error. This is also the default mode in which the file is opened.  Read and Write (‘r+’): Open the file for reading and writing. The handle is positioned at the beginning of the file. Raises I/O error if the file does not exist.  Write Only (‘w’): Open the file for writing. For existing file, the data is truncated and over-written. The handle is positioned at the beginning of the file. Creates the file if the file does not exist.  Write and Read (‘w+’): Open the file for reading and writing. For existing file, data is truncated and over-written. The handle is positioned at the beginning of the file.  Append Only (‘a’): Open the file for writing. The file is created if it does not exist. The handle is positioned at the end of the file. The data being written will be inserted at the end, after the existing data.  Append and Read (‘a+’): Open the file for reading and writing. The file is created if it does not exist. The handle is positioned at the end of the file. The data being written will be inserted at the end, after the existing data. N.I.T Srinagar 174
  • 175.  The file should exist in the same directory as the Python script, otherwise full address of the file should be written.  read the content of the file using Python. # Python program to demonstrate # opening a file # Open function to open the file "myfile.txt" # (same directory) in read mode and store # it's reference in the variable file1 file1 = open("myfile.txt") # Reading from file print(file1.read()) file1.close() N.I.T Srinagar 175
  • 176. write more data to the above file using Python. # Python program to demonstrate # opening a file # Open function to open the file "myfile.txt" # (same directory) in append mode and store # it's reference in the variable file1 file1 = open("myfile.txt", "a") # Writing to file file1.write("nWriting to file :)") # Closing file file1.close() N.I.T Srinagar 176
  • 177. Closing a file  close() function closes the file and frees the memory space acquired by that file. It is used at the time when the file is no longer needed or if it is to be opened in a different file mode. N.I.T Srinagar 177
  • 178. file2 = open(r"C:UsersshahidDesktopSER.txt", "r+") print(file2.read()) N.I.T Srinagar 178
  • 179. Read Only Parts of the File By default the read() method returns the whole text, but you can also specify how many characters you want to return: Example Return the 5 first characters of the file: f = open("demofile.txt", "r") print(f.read(5)) N.I.T Srinagar 179
  • 180. Read Lines  You can return one line by using the readline() method:  Example  Read one line of the file: f = open("demofile.txt", "r") print(f.readline()) N.I.T Srinagar 180
  • 181. Python Delete File  To delete a file, you must import the OS module, and run its os.remove() function:  Example  Remove the file "demofile.txt": import os os.remove("demofile.txt") N.I.T Srinagar 181
  • 182. Delete Folder  To delete an entire folder, use the os.rmdir() method:  Example  Remove the folder "myfolder": import os os.rmdir("myfolder") N.I.T Srinagar 182
  • 183. Create a New File  To create a new file in Python, use the open() method, with one of the following parameters:  "x" - Create - will create a file, returns an error if the file exist  "a" - Append - will create a file if the specified file does not exist  "w" - Write - will create a file if the specified file does not exist N.I.T Srinagar 183
  • 184. f = open("myfile.txt", "x") Create a new file if it does not exist: f = open("myfile.txt", "w") N.I.T Srinagar 184
  • 185. Python Exception  An exception can be defined as an unusual condition in a program resulting in the interruption in the flow of the program.  Whenever an exception occurs, the program stops the execution, and thus the further code is not executed. Therefore, an exception is the run-time errors that are unable to handle to Python script.  An exception is a Python object that represents an error  Python provides a way to handle the exception so that the code can be executed without any interruption. If we do not handle the exception, the interpreter doesn't execute all the code that exists after the exception. N.I.T Srinagar 185
  • 186.  A list of common exceptions that can be thrown from a standard Python program:  ZeroDivisionError: Occurs when a number is divided by zero.  NameError: It occurs when a name is not found. It may be local or global.  IndentationError: If incorrect indentation is given.  IOError: It occurs when Input Output operation fails.  EOFError: It occurs when the end of the file is reached, and yet operations are being performed. N.I.T Srinagar 186
  • 187. The problem without handling exceptions  Suppose we have two variables a and b, which take the input from the user and perform the division of these values. What if the user entered the zero as the denominator? It will interrupt the program execution and through a ZeroDivision exception. N.I.T Srinagar 187
  • 189.  The above program is syntactically correct, but it through the error because of unusual input. That kind of programming may not be suitable or recommended for the projects because these projects are required uninterrupted execution. That's why an exception- handling plays an essential role in handling these unexpected exceptions. N.I.T Srinagar 189
  • 190. Exception handling in python  The try-expect statement  If the Python program contains suspicious code that may throw the exception, we must place that code in the try block. The try block must be followed with the except statement, which contains a block of code that will be executed if there is some exception in the try block. N.I.T Srinagar 190
  • 193.  We can also use the else statement with the try-except statement in which, we can place the code which will be executed in the scenario if no exception occurs in the try block. N.I.T Srinagar 193
  • 196. The except statement with no exception  Python provides the flexibility not to specify the name of exception with the exception statement. try: a = int(input("Enter a:")) b = int(input("Enter b:")) c = a/b; print("a/b = %d"%c) except: print("can't divide by zero") else: print("Hi I am else block") N.I.T Srinagar 196
  • 197. try: #this will throw an exception if the file doesn't exist. fileptr = open("file.txt","r") except IOError: print("File not found") else: print("The file opened successfully") fileptr.close() N.I.T Srinagar 197
  • 198. Declaring Multiple Exceptions  The Python allows us to declare the multiple exceptions with the except clause. Declaring multiple exceptions is useful in the cases where a try block throws multiple exceptions. N.I.T Srinagar 198
  • 200. The try...finally block  You can use a finally: block along with a try: block. The finally block is a place to put any code that must execute, whether the try-block raised an exception or not. N.I.T Srinagar 200
  • 202. try: fileptr = open("file2.txt","r") try: fileptr.write("Hi I am good") finally: fileptr.close() print("file closed") except: print("Error") N.I.T Srinagar 202
  • 203. What are Python Modules?  In Python, Modules are simply files with the “.py” extension containing Python code that can be imported inside another Python Program.  In simple terms, we can consider a module to be the same as a code library or a file that contains a set of functions that you want to include in your application.  With the help of modules, we can organize related functions, classes, or any code block in the same file. So, It is considered a best practice while writing bigger codes for production-level projects in Data Science is to split the large Python code blocks into modules containing up to 300–400 lines of code. N.I.T Srinagar 203
  • 204.  The module contains the following components:  Definitions and implementation of classes,  Variables, and  Functions that can be used inside another program. N.I.T Srinagar 204
  • 205.  Suppose we want to make an application for a calculator. We want to include few operations in our application such as addition, subtraction, multiplication, division, etc.  Now, here what we will be doing is to break the complete code into separate parts and simply create one module for all these operations or separate modules for each of the operations. And then we can call these modules in our main program logic.  Here the core idea is to minimize the code, and if we create modules, it doesn’t mean we can only use it for this program, but we can even call these modules for other programs as well. N.I.T Srinagar 205
  • 206. How to create Python Modules?  To create a module, we have to save the code that we wish in a file with the file extension “.py”. Then, the name of the Python file becomes the name of the module.  In this program, a function is created with the name “welcome” and save this file with the name mymodule.py i.e. name of the file, and with the extension “.py”.  We saved the following code in a file named mymodule.py N.I.T Srinagar 206
  • 207.  To incorporate the module into our program, we will use the import keyword, and to get only a few or specific methods or functions from a module, we use the from keyword.  NOTE: When we are using a function from a module, then we use the following syntax: N.I.T Srinagar 207
  • 211. Python Built-in Modules  As we know that the Python interactive shell has a number of built-in functions. As a shell start, these functions are loaded automatically and are always available, such as,  print() and input() for I/O,  Number conversion functions such as int(), float(), complex(),  Data type conversions such as list(), tuple(), set(), etc.  In addition to these many built-in functions, there are also a large number of pre-defined functions available as a part of libraries bundled with Python distributions. These functions are defined in modules which are known as built-in modules. N.I.T Srinagar 211
  • 212. import math print("The value of pi is", math.pi) N.I.T Srinagar 212

Notes de l'éditeur

  1. List[2] List[-4]