PY Mod 1
PY Mod 1
CORE TEXT
ADDITIONAL REFERENCES
1. Allen B. Downey,” Think Python- How to think like a computer scientist”, Second
Edition, O’Reilly, 2016.
PART A
PART B
Python : Introduction
Python is a widely used general-purpose, high level programming language. It was created by
Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was
designed with an emphasis on code readability, and its syntax allows programmers to express their
concepts in fewer lines of code.
Python is a programming language that lets you work quickly and integrate systems more
efficiently. It also performs automatic memory management.
There are two major Python versions: Python 2 and Python 3. Both are quite different.
Reason for increasing popularity
1. Emphasis on code readability, shorter codes, ease of writing
2. Programmers can express logical concepts in fewer lines of code in comparison to languages
such as C++ or Java.
3. Python supports multiple programming paradigms, like object-oriented, imperative and
functional programming or procedural.
4. There exists inbuilt functions for almost all of the frequently used concepts.
Advantages :
1) Presence of third-party modules
2) Extensive support libraries (NumPy for numerical calculations, Pandas for data analytics etc)
3) Open source and community development
4) Easy to learn
5) User-friendly data structures
6) High-level language
7) Dynamically typed language (No need to mention data type, based on value assigned it takes
data type)
8) Object-oriented language
9) Portable and Interactive
10) Portable across Operating systems
Python: FEATURES
Interpreted
• There are no separate compilation and execution steps like C and C++.
• Directly run the program from the source code.
• Internally, Python converts the source code into an intermediate form called byte codes which
is then translated into native language of specific computer to run it.
The Python Standard Library is very vast. It can help do various things involving regular
expressions, documentation generation, unit testing, threading, databases, web browsers, CGI,
email, XML, HTML, WAV files, cryptography, GUI and many more. Besides the standard library,
there are various other high-quality libraries such as the Python Imaging Library which is an
amazingly simple image manipulation library.
Python Identifiers
A Python identifier is a name used to identify a variable, function, class, module or other object.
An identifier starts with a letter A to Z or a to z or an underscore ( _ ) followed by zero or more
letters, underscores and digits (0 to 9).
Python does not allow punctuation characters such as @, $, and % within identifiers. Python is a
case sensitive programming language. Thus, Man and man are two different identifiers in Python.
Starting an identifier with two leading underscores indicates a strongly private identifier.
•
If the identifier also ends with two trailing underscores, the identifier is a language-defined
•
special name.
Reserved Words
Keywords: Keywords are words which are responsible to perform some specific tasks or the
words which represent some specific functionality. The following table lists some keywords.
These are reserved words and you cannot use them as constant or variable or any other identifier
names. All the Python keywords contain lowercase letters only.
and exec not
assert finally or
def if return
elif in while
else is with
Python developers often make use of the comment system as, without the use of it, things can get
real confusing, real fast. Comments are the useful information that the developers provide to make
the reader understand the source code. It explains the logic or a part of it used in the code.
Comments are usually helpful to someone maintaining or enhancing your code when you are no
longer around to answer questions about it. These are often cited as a useful programming
convention that does not take part in the output of the program but improves the readability of the
whole program. There are two types of comment in Python:
Single line comments: Python single line comment starts with hashtag symbol with no white
spaces (#) and lasts till the end of the line. If the comment exceeds one line, then put a hashtag on
the next line and continue the comment. Python’s single line comments are proved useful for
supplying short explanations for variables, function declarations, and expressions.
Multi-line string as comment: Python multi-line comment is a piece of text enclosed in a
delimiter (""") on each end of the comment. Again, there should be no white space between
delimiter ("""). They are useful when the comment text does not fit into one line; therefore, needs
to span across lines. Multi-line comments or paragraphs serve as documentation for others reading
your code.
Python provides us with two inbuilt functions to read the input from the keyboard.
• raw_input ( prompt )
• input ( prompt ) raw_input ( ) : This function works in older version (like Python 2.x). This
function takes exactly what is typed from the keyboard, convert it to string and then return
it to the variable in which we want to store.
input ( ) : This function first takes the input from the user and then evaluates the expression, which
means Python automatically identifies whether user entered a string or a number or list. If the
input provided is not correct then either syntax error or exception is raised by python.
Python Import
When our program grows bigger, it is a good idea to break it into different modules.
A module is a file containing Python definitions and statements. Python modules have a filename
and end with the extension .py
Definitions inside a module can be imported to another module or the interactive interpreter in
Python. We use the import keyword to do this.
For example, we can import the math module by typing in import math.
import math
print(math.pi)
Now all the definitions inside math module are available in our scope. We can also import some
specific attributes and functions only, using the from keyword. For example:
>>> from math import pi
>>> pi
3.141592653589793
Output using print() function
The simplest way to produce output is using the print() function where you can pass zero
or more expressions separated by commas. This function converts the expressions you pass into a
string before writing to the screen. The syntax of the print() function is print(*objects, sep=' ',
The sep separator is used between the values. It defaults into a space character.
After all values are printed, end is printed. It defaults into a new line.
The file is the object where the values are printed and its default value is sys.stdout (screen). Here
are examples to illustrate this.
l = [1, 2, 3, 4, 5] #
printing a list
print l
x=5
# Two objects are passed
print("x =", x)
>>> x = 5; y = 10
>>> print('The value of x is {} and y is {}'.format(x,y)) The
value of x is 5 and y is 10
Here the curly braces {} are used as placeholders. We can specify the order in which it is printed
by using numbers (tuple index).
>>> x = 12.3456789
>>> print('The value of x is %3.2f' %x) The
value of x is 12.35
>>> print('The value of x is %3.4f' %x) The
value of x is 12.3457
>>> print("5"*6)
555555
You can separate the output using the comma delimiter. By default, this adds a space between the
output items. For example, the sequence of numbers 5,6,7 separated by comma , gets printed with
a space between one number and the next.
>>> print(5,6,7)
567
To change the output to what you want, use the keyword arguments sep and end to print ( ). When
separating the output with a comma delimiter, you can also define the separation format using the
a€œsepa€ keyword.
You can change this default implementation. You can have a colon : between the letters instead of
a new line.
>>> population = 7
>>> print("Population in 2050: ", population * 1.28)
# making the calculation in place
Population in 2050: 8.96
Basic Operators in Python
Operators are special symbols in Python that carry out arithmetic or logical computation.
The value that the operator operates on is called the operand.
For example:
>>> 2+3
5
Here, + is the operator that performs addition. 2 and 3 are the operands and 5 is the output of the
operation.
● Arithmetic operators
● Assignment operators
● Comparison operators
● Logical operators
● Identity operators
● Membership operators
● Bitwise operators
# Addition of numbers
add = a + b
# Subtraction of numbers
sub = a - b
# Multiplication of number
mul = a * b
# Division(float) of number
div1 = a / b
# Division(floor) of number
div2 = a // b
# Modulo of both number
mod = a % b
# print results
print(add)
print(sub)
print(mul)
print(div1)
print(div2)
print(mod)
Output:
13
5
36
2.25 2
1
Relational Operators: Relational operators compares the values. It either returns True or
False according to the condition.
<= Less than or equal to: True if left operand is less than or equal to the x <= y
right
Output:
False
True
False
True
False
True
Logical operators: Logical operators perform Logical AND, Logical OR and Logical NOT
operations.
Operator Description Syntax
and Logical AND: True if both the operands are true x and y
or Logical OR: True if either of the operands is true x or y
not Logical NOT: True if operand is false not x
• Assignment operators: Assignment operators are used to assign values to the variables.
Operator Description Syntax
+= Add AND: Add right side operand with left side operand a+=b a=a+b
and then assign to left operand
-= Subtract AND: Subtract right operand from left operand a-=b a=a-b
and then assign to left operand
*= Multiply AND: Multiply right operand with left operand a*=b a=a*b
and then assign to left operand
/= Divide AND: Divide left operand with right operand and a/=b a=a/b
then assign to left operand
%= Modulus AND: Takes modulus using left and right a%=b a=a%b
operands and assign result to left operand
//= Divide(floor) AND: Divide left operand with right operand a//=b
and then assign the value(floor) to left operand a=a//b
>>= Performs Bitwise right shift on operands and assign value a>>=b
to left operand a=a>>b
<<= Performs Bitwise left shift on operands and assign value a <<= b a=
to left operand a << b
print(a2 is b2)
# Output is False, since lists are mutable.
print(a3 is b3)
Output: False
True
False
o Membership operators-
in and not in are the membership operators; used to test whether a value or variable is in
a sequence.
in True if value is found in the sequence
not in True if value is not found in the sequence
# Examples of Membership operator
x = 'Operators in Python'
y = {3:'a',4:'b'}
print('G' in x) print('python'
not in x) print('Python' not
in x) print(3 in y)
print('b' in y)
Output:
False
True
False
True
False
In Python, the data type is set when you assign a value to a variable:
Example Datatype
x = "Hello World" str
x = 20 int
x = 20.5 float
x = 1j complex
x = ["apple", "banana", "cherry"] list
x = ("apple", "banana", "cherry") tuple
x = range(6) range
x = {"name" : "John", "age" : 36} dict
x = {"apple", "banana", "cherry"} set
x = frozenset({"apple", "banana", "cherry"}) frozenset
x = True bool
x = b"Hello" bytes
x = bytearray(5) bytearray
x = memoryview(bytes(5)) memoryview
Data types are the classification or categorization of data items. It represents the kind of value that
tells what operations can be performed on a particular data. Since everything is an object in Python
programming, data types are actually classes and variables are instance (object) of these classes.
Numeric
In Python, numeric data type represent the data which has numeric value. Numeric value
can be interger, floating number or even complex numbers. These values arre defined as int, float
and complex class in Python.
● Intergers – This value is represented by int class. It contains positive or negative whole
numbers (without fraction or decimal). In Python there is no limit to how long an interger
value can be.
● Float – This value is represented by float class. It is a real number with floating point
representation. It is specified by a decimal point. Optionally, the character e or E followed by a
positive or negative integer may be appended to specify scientific notation.
● Complex Numbers – Complex number is represented by complex class. It is specified as (real
part) + (imaginary part)j. For example – 2+3j
Sequence Type
In Python, sequence is the ordered collection of similar or different data types. Sequences
allows to store multiple values in an organized and efficient fashion. There are several sequence
types in Python –
● String
● List
● Tuple
1) String
In Python, Strings are arrays of bytes representing Unicode characters. A string is a collection of
one or more characters put in a single quote, double-quote or triple quote. In python there is no
character data type, a character is a string of length one. It is represented by str class.
Creating a string
Strings in Python can be created using single quotes or double quotes or even triple quotes.
While accessing an index out of the range will cause an IndexError. Only Integers are
allowed to be passed as an index, float or other types will cause a TypeError.
2) List
Lists are just like the arrays, declared in other languages. Lists need not be homogeneous
always which makes it the most powerful tool in Python. A single list may contain DataTypes like
Integers, Strings, as well as Objects. Lists are mutable, and hence, they can be altered even after
their creation. List in Python are ordered and have a definite count. The elements in a list are
indexed according to a definite sequence and the indexing of a list is done with 0 being the first
index. Each element in the list has its definite place in the list, which allows duplicating of elements
in the list, with each element having its own distinct place and credibility. It is represented by list
class.
Lists in Python can be created by just placing the sequence inside the square brackets[].
Unlike Sets, list doesn’t need a built-in function for creation of list.
Note – Remove method in List will only remove the first occurrence of the searched element.
3) Tuple
Tuple is an ordered collection of Python objects much like a list. The sequence of values
stored in a tuple can be of any type, and they are indexed by integers. The important difference
between a list and a tuple is that tuples are immutable. Also, Tuples are hashable whereas lists are
not. It is represented by tuple class.
Creating a Tuple
In Python, tuples are created by placing sequence of values separated by ‘comma’ with or
without the use of parentheses for grouping of data sequence. Tuples can contain any number of
elements and of any datatype (like strings, integers, list, etc.). Tuples can also be created with a
single element, but it is a bit tricky. Having one element in the parentheses is not sufficient, there
must be a trailing ‘comma’ to make it a tuple.
Note – Creation of Python tuple without the use of parentheses is known as Tuple Packing.
Accessing element of a tuple
In order to access the tuple items refer to the index number. Use the index operator [ ] to
access an item in a tuple. The index must be an integer. Nested tuple are accessed using nested
indexing.
Boolean
Data type with one of the two built-in values, True or False. Boolean objects that are equal
to True are truthy (true), and those equal to False are falsy (false). But non-Boolean objects can be
evaluated in Boolean context as well and determined to be true or false. It is denoted by the class
bool.
Note – True and False with capital ‘T’ and ‘F’ are valid booleans otherwise python will throw an
error.
Set
In Python, Set is an unordered collection of data type that is iterable, mutable and has no
duplicate elements. The order of elements in a set is undefined though it may consist of various
elements. The major advantage of using a set, as opposed to a list, is that it has a highly optimized
method for checking whether a specific element is contained in the set.
Creating a set
Sets can be created by using the built-in set() function with an iterable object or a sequence
by placing the sequence inside curly braces, separated by ‘comma’. A set contains only unique
elements but at the time of set creation, multiple duplicate values can also be passed. The order of
elements in a set is undefined and is unchangeable. Type of elements in a set need not be the same,
various mixed-up data type values can also be passed to the set.
Elements can be added to the Set by using built-in add() function. Only one element at a
time can be added to the set by using add() method. For addition of two or more elements Update()
method is used.
Accessing a Set
Set items cannot be accessed by referring to an index, since sets are unordered the items has no
index. 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.
Elements can be removed from the Set by using built-in remove() function but a KeyError arises
if element doesn’t exist in the set. To remove elements from a set without KeyError, use discard().
Pop() function can also be used to remove and return an element from the set, but it removes only
the last element of the set. To remove all the elements from the set, clear() function is used.
Dictionary
Dictionary in Python is an unordered collection of data values, used to store data values like
a map, which unlike other Data Types that hold only single value as an element, Dictionary holds
key:value pair. Key-value is provided in the dictionary to make it more optimized. Each keyvalue
pair in a Dictionary is separated by a colon :, whereas each key is separated by a ‘comma’.
Creating a dictionary
In Python, a Dictionary can be created by placing a sequence of elements within curly {}
braces, separated by ‘comma’. Dictionary holds a pair of values, one being the Key and the other
corresponding pair element being its Key:value. Values in a dictionary can be of any datatype and
can be duplicated, whereas keys can’t be repeated and must be immutable.
Dictionary can also be created by the built-in function dict(). An empty dictionary can be
created by just placing to curly braces{}.
Note – Dictionary keys are case sensitive, same name but different cases of Key will be treated
distinctly.
Note – While adding a value, if the key-value already exists, the value gets updated otherwise a
new Key with the value is added to the Dictionary.
Every variable in python holds an instance of an object. There are two types of objects in
python i.e. Mutable and Immutable objects. Whenever an object is instantiated, it is assigned a
unique object id. The type of the object is defined at the runtime and it can’t be changed afterwards.
However, it’s state can be changed if it is a mutable object.
To summarise the difference, mutable objects can change their state or contents and
immutable objects can’t change their state or content.
Immutable Objects : These are of in-built types like int, float, bool, string, unicode,
tuple. In simple words, an immutable object can’t be changed after it is created.
Mutable Objects : These are of type list, dict, set . Custom classes are generally mutable.
1. Mutable and immutable objects are handled differently in python. Immutable objects are
quicker to access and are expensive to change because it involves the creation of a copy.
Whereas mutable objects are easy to change.
2. Use of mutable objects is recommended when there is a need to change the size or content of
the object.
3. Exception : However, there is an exception in immutability as well. We know that tuple in
python is immutable. But the tuple consists of a sequence of names with unchangeable
bindings to objects.
Consider a tuple, the tuple consists of a string and a list. Strings are immutable so we can’t change
its value. But the contents of the list can change. The tuple itself isn’t mutable but contain items
that are mutable.
Type Conversion in Python
Python defines type conversion functions to directly convert one data type to another
which is useful in day to day and competitive programming. This article is aimed at providing the
information about certain conversion functions.
1. int(a,base) : This function converts any data type to integer. ‘Base’ specifies the base in which
string is if data type is string.
s = "10010"
# printing string converting to int base 2
c = int(s,2)
2. float() : This function is used to convert any data type to a floating point number
e =float(s)
c =set(s)
8. list() : This function is used to convert any data type to a list type.
c =list(s)
9. dict() : This function is used to convert a tuple of order (key,value) into a dictionary.
tup = (('a', 1) ,('f', 2), ('g', 3))
c =dict(tup)
Syntax:
if (condition1):
# Executes when condition1 is true
if (condition2):
# Executes when condition2 is true
# if Block is end here
# if Block is end here
# python program to illustrate nested If
i = 10
if (i == 10):
# First if statement
if (i < 15):
print ("i is smaller than 15")
# Nested - if statement Will only be executed if statement above it is true
if (i < 12):
print ("i is smaller than 12 too")
else:
print ("i is greater than 15")
Output:
i is smaller than 15
i is smaller than 12 too
if-elif-else ladder
Here, a user can decide among multiple options. The if statements are executed from the top down. As soon
as one of the conditions controlling the if is true, the statement associated with that if is executed, and the
rest of the ladder is bypassed. If none of the conditions is true, then the final else statement will be executed.
Syntax:-
if (condition):
statement
elif (condition):
statement
.
.
else:
statement
Example:-
# Python program to illustrate if-elif-else ladder
i = 20
if (i == 10):
print ("i is 10")
elif (i == 15):
Loops in python
Python programming language provides following types of loops to handle looping requirements. Python
provides three ways for executing the loops. While all the ways provide similar basic functionality, they
differ in their syntax and condition checking time.
While Loop:
In python, while loop is used to execute a block of statements repeatedly until a given a condition is
satisfied. And when the condition becomes false, the line immediately after the loop in program is executed.
Syntax :
while expression:
statement(s)
All the statements indented by the same number of character spaces after a programming construct are
considered to be part of a single block of code. Python uses indentation as its method of grouping
statements.
# Python program to illustrate while loop
count = 0
while (count < 3):
count = count + 1
print("Hello World")
Output:
Hello World
Hello World
Hello World
Using else statement with while loops: As discussed above, while loop executes the block until a condition
is satisfied. When the condition becomes false, the statement immediately after the loop is executed. The
else clause is only executed when your while condition becomes false. If you break out of the loop, or if an
exception is raised, it won’t be executed.
If else like this:
if condition:
# execute these statements
else:
# execute these statements
print(i)
# Iterating over dictionary
print("\nDictionary Iteration")
d = dict()
d['xyz'] = 123
d['abc'] = 345
for i in d :
print("%s %d" %(i, d[i]))
Output:
List Iteration
aaa
bbb
ccc
Tuple Iteration
xxx
yyy
zzz
String Iteration
a
b
c
d
Dictionary Iteration
xyz 123
abc 345
Iterating by index of sequences: We can also use the index of elements in the sequence to iterate. The key
idea is to first calculate the length of the list and in iterate over the sequence within the range of this length.
See the below example:
# Python program to illustrate Iterating by index
list = ["aaa", "bbb", "ccc"]
for index in range(len(list)):
print list[index]
Output:
aaa
bbb
ccc
Using else statement with for loops: We can also combine else statement with for loop like in while loop.
But as there is no condition in for loop based on which the execution will terminate so the else block will
be executed immediately after for block finishes execution.
Below example explains how to do this:
# Python program to illustrate combining else with for
list = ["xxx", "yyy", "zzz"]
statements(s)
statements(s)
The syntax for a nested while loop statement in Python programming language is as follows:
while expression:
while expression:
statement(s)
statement(s)
A final note on loop nesting is that we can put any type of loop inside of any other type of loop. For example
a for loop can be inside a while loop or vice versa.
# Python program to illustrate nested for loops in Python
for i in range(1, 5):
for j in range(i):
print(i, end=' ')
print()
Output:
1
22
333
4444
Loop Control Statements: Loop control statements change execution from its normal sequence. When
execution leaves a scope, all automatic objects that were created in that scope are destroyed. Python
supports the following control statements.
Continue Statement: It returns the control to the beginning of the loop.
Prints all letters except 'h'
for letter in 'Python':
if letter == 'h':
continue
print( 'Current Letter :', letter)
Output:
Current Letter : P
Current Letter : y
Current Letter : t
Current Letter : o
Current Letter : n
def insertionSort(arr):
# Traverse through 1 to len(arr)
for i in range(1, len(arr)):
key = arr[i]
# Move elements of arr[0..i-1], that are greater than key,
#to one position ahead of their current position
j = i-1
while j >=0 and key < arr[j] :
arr[j+1] = arr[j]
j -= 1
arr[j+1] = key