Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
38 views

Python Complete Notes

The document discusses Python programming language. It describes Python's development cycle which allows for rapid prototyping. Python programs can be changed and reloaded without stopping the program. The document also discusses Python IDEs, what Python is used for, its features like being cross-platform, simple syntax, and ability to write programs with fewer lines. It provides examples of Python syntax like indentation, comments, variables, numbers, operators and more.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
38 views

Python Complete Notes

The document discusses Python programming language. It describes Python's development cycle which allows for rapid prototyping. Python programs can be changed and reloaded without stopping the program. The document also discusses Python IDEs, what Python is used for, its features like being cross-platform, simple syntax, and ability to write programs with fewer lines. It provides examples of Python syntax like indentation, comments, variables, numbers, operators and more.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 74

Unit I

PYTHON CYCLE:

Python's development cycle is dramatically shorter than that of traditional tools. In


Python, there are no compile or link steps -- Python programs simply import modules
at runtime and use the objects they contain. Because of this, Python programs run
immediately after changes are made. And in cases where dynamic module reloading
can be used, it's even possible to change and reload parts of a running program without
stopping it at all. Figure 21-1 shows Python's impact on the development cycle. Figure
21-1. Development cycles

ER.VIPIN RAWAT DEPARTMENT OF COMPUTER SCIENCE Page 1


Python IDE: An IDE (or Integrated Development
Environment) is a program dedicated to software development. As the
name implies, IDEs integrate several tools specifically designed for
software development. These tools usually include:
 An editor designed to handle code (with, for example, syntax
highlighting and auto-completion)
 Build, execution, and debugging tools
 Some form of source control
Most IDEs support many different programming languages and contain
many more features. They can, therefore, be large and take time to
download and install. You may also need advanced knowledge to
use them properly.

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.

What can Python do?


 Python can be used on a server to create web applications.
 Python can be used alongside software to create workflows.
 Python can connect to database systems. It can also read and
modify files.
 Python can be used to handle big data and perform complex
mathematics.
 Python can be used for rapid prototyping, or for production-
ready software development.

ER.VIPIN RAWAT DEPARTMENT OF COMPUTER SCIENCE Page 2


Why Python?
 Python works on different platforms (Windows, Mac, Linux,
Raspberry Pi, etc).
 Python has a simple syntax similar to the English language.
 Python has syntax that allows developers to write programs
with fewer lines than some other programming languages.
 Python runs on an interpreter system, meaning that code can
be executed as soon as it is written. This means that
prototyping can be very quick.
 Python can be treated in a procedural way, an object-
orientated way or a functional way.

Good to know
 The most recent major version of Python is Python 3, which we
shall be using in this tutorial. However, Python 2, although not
being updated with anything other than security updates, is still
quite popular.
 In this tutorial Python will be written in a text editor. It is
possible to write Python in an Integrated Development
Environment, such as Thonny, Pycharm, Netbeans or Eclipse
which are particularly useful when managing larger collections
of Python files.

Python Syntax compared to other programming


languages
 Python was designed for readability, and has some similarities
to the English language with influence from mathematics.
 Python uses new lines to complete a command, as opposed to
other programming languages which often use semicolons or
parentheses.
 Python relies on indentation, using whitespace, to define scope;
such as the scope of loops, functions and classes. Other
programming languages often use curly-brackets for this
purpose.

ER.VIPIN RAWAT DEPARTMENT OF COMPUTER SCIENCE Page 3


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.

Example
if 5 > 2:
print("Five is greater than two!")

Example
The number of spaces is up to you as a programmer, but it has to be
at least one.

if 5 > 2:
print("Five is greater than two!")
if 5 > 2:
print("Five is greater than two!")

Python Variables
In Python variables are created the moment you assign a value to it:

Example
Variables in Python:

x = 5
y = "Hello, World!"
ER.VIPIN RAWAT DEPARTMENT OF COMPUTER SCIENCE Page 4
Python has no command for declaring a variable.

Comments
Python has commenting capability for the purpose of in-code
documentation.

Comments start with a #, and Python will render the rest of the line
as a comment:

Example
Comments in Python:

#This is a comment.
print("Hello, World!")

Creating Variables
Variables are containers for storing data values.

Unlike other programming languages, Python has no command for


declaring a variable.

A variable is created the moment you first assign a value to it

Example
x = 5
y = "John"

ER.VIPIN RAWAT DEPARTMENT OF COMPUTER SCIENCE Page 5


print(x)
print(y)

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:

Example
x = 1 # int
y = 2.8 # float
z = 1j # complex

Python Casting

Specify a Variable Type


There may be times when you want to specify a type on to a
variable. This can be done with casting. Python is an object-
orientated language, and as such it uses classes to define data
types, including its primitive types.

Casting in python is therefore done using constructor functions:

 int() - constructs an integer number from an integer literal, a


float literal (by rounding down to the previous whole number),

ER.VIPIN RAWAT DEPARTMENT OF COMPUTER SCIENCE Page 6


or a string literal (providing the string represents a whole
number)
 float() - constructs a float number from an integer literal, a
float literal or a string literal (providing the string represents a
float or an integer)
 str() - constructs a string from a wide variety of data types,
including strings, integer literals and float literals

Example
 Integers:
 x = int(1) # x will be 1
y = int(2.8) # y will be 2
z = int("3") # z will be 3

Example
 Floats:
 x = float(1) # x will be 1.0
y = float(2.8) # y will be 2.8
z = float("3") # z will be 3.0
w = float("4.2") # w will be 4.2

Example
 Strings:
 x = str("s1") # x will be 's1'
y = str(2) # y will be '2'
z = str(3.0) # z will be '3.0'

ER.VIPIN RAWAT DEPARTMENT OF COMPUTER SCIENCE Page 7


String Literals
String literals in python are surrounded by either single quotation
marks, or double quotation marks.

'hello' is the same as "hello".

You can display a string literal with the print() function:

Example
print("Hello")
print('Hello')

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:

Example
a = "Hello"
print(a)

Multiline Strings
You can assign a multiline string to a variable by using three quotes:

Example
You can use three double quotes:

a = """Lorem ipsum dolor sit amet,


consectetur adipiscing elit,
sed do eiusmod tempor incididunt

ER.VIPIN RAWAT DEPARTMENT OF COMPUTER SCIENCE Page 8


ut labore et dolore magna aliqua."""
print(a)

Or three single quotes:

Example
a = '''Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua.'''
print(a)

Python Operators
Operators are used to perform operations on variables and values.

Python divides the operators in the following groups:

 Arithmetic operators
 Assignment operators
 Comparison operators
 Logical operators
 Identity operators
 Membership operators
 Bitwise operators

Python Arithmetic Operators


Arithmetic operators are used with numeric values to perform
common mathematical operations:

Operator Name Example

ER.VIPIN RAWAT DEPARTMENT OF COMPUTER SCIENCE Page 9


+ Addition x+y

- Subtraction x-y

* Multiplication x*y

/ Division x/y

% Modulus x%y

** Exponentiation x ** y

// Floor division x // y

Python Assignment Operators


Assignment operators are used to assign values to variables:

Operator Example Same As

ER.VIPIN RAWAT DEPARTMENT OF COMPUTER SCIENCE Page 10


= x=5 x=5

+= x += 3 x=x+3

-= x -= 3 x=x-3

*= x *= 3 x=x*3

/= x /= 3 x=x/3

%= x %= 3 x=x%3

//= x //= 3 x = x // 3

**= x **= 3 x = x ** 3

&= x &= 3 x=x&3

|= x |= 3 x=x|3

ER.VIPIN RAWAT DEPARTMENT OF COMPUTER SCIENCE Page 11


^= x ^= 3 x=x^3

>>= x >>= 3 x = x >> 3

<<= x <<= 3 x = x << 3

Python Comparison Operators


Comparison operators are used to compare two values:

Operator Name Example

== Equal x == y

!= Not equal x != y

> Greater than x>y

< Less than x<y

ER.VIPIN RAWAT DEPARTMENT OF COMPUTER SCIENCE Page 12


>= Greater than or equal to x >= y

<= Less than or equal to x <= y

Python Identity Operators


Identity operators are used to compare the objects, not if they are
equal, but if they are actually the same object, with the same
memory location:

erator Description Example

Returns true if both variables are the same object x is y

not Returns true if both variables are not the same x is not y
object

Python Membership Operators


Membership operators are used to test if a sequence is presented in an
object:

ER.VIPIN RAWAT DEPARTMENT OF COMPUTER SCIENCE Page 13


Operator Description Example

in Returns True if a sequence with the specified value is x in y


present in the object

not in Returns True if a sequence with the specified value is not x not in y
present in the object

Python Bitwise Operators


Bitwise operators are used to compare (binary) numbers:

Operator Name Description

& AND Sets each bit to 1 if both bits are 1

| OR Sets each bit to 1 if one of two bits is 1

^ XOR Sets each bit to 1 if only one of two bits is 1

~ NOT Inverts all the bits

<< Zero fill left Shift left by pushing zeros in from the right and let the leftm
shift off

ER.VIPIN RAWAT DEPARTMENT OF COMPUTER SCIENCE Page 14


>> Signed right Shift right by pushing copies of the leftmost bit in from the
shift the rightmost bits fall off

UNIT 2

Python Conditions and If statements


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.

An "if statement" is written by using the if keyword.

Example
If statement:

a = 33
b = 200
if b > a:
print("b is greater than a")

Indentation

ER.VIPIN RAWAT DEPARTMENT OF COMPUTER SCIENCE Page 15


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.

Example 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

Elif
The elif keyword is pythons way of saying "if the previous conditions
were not true, then try this condition".

Example
a = 33
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")

Else
The else keyword catches anything which isn't caught by the preceding
conditions.

Example
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")

ER.VIPIN RAWAT DEPARTMENT OF COMPUTER SCIENCE Page 16


Nested If
You can have if statements inside if statements, this is
called nested if statements.

Example
x = 41

if x > 10:
print("Above ten,")
if x > 20:
print("and also above 20!")
else:
print("but not above 20.")

Python Loops
Python has two primitive loop commands:

 while loops
 for loops

The while Loop


With the while loop we can execute a set of statements as long as a
condition is true.

Example
Print i as long as i is less than 6:

ER.VIPIN RAWAT DEPARTMENT OF COMPUTER SCIENCE Page 17


i = 1
while i < 6:
print(i)
i += 1
1
2
3
4
5

The break Statement


With the break statement we can stop the loop even if the while
condition is true:

Example
Exit the loop when i is 3:

i = 1
while i < 6:
print(i)
if i == 3:
break
i += 1
1
2
3

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:

ER.VIPIN RAWAT DEPARTMENT OF COMPUTER SCIENCE Page 18


i = 0
while i < 6:
i += 1
if i == 3:
continue
print(i)

The else Statement


With the else statement we can run a block of code once when the
condition no longer is true:

Example
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")

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.

ER.VIPIN RAWAT DEPARTMENT OF COMPUTER SCIENCE Page 19


Example
Print each fruit in a fruit list:

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


for x in fruits:
print(x)

Looping Through a String: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)
b
a
n
a
n
a

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
ER.VIPIN RAWAT DEPARTMENT OF COMPUTER SCIENCE Page 20
The continue Statement
With the continue statement we can stop the current iteration of
the loop, and continue with the next:

Example
Do not print banana:

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


for x in fruits:
if x == "banana":
continue
print(x)

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.

Example
Using the range() function:

for x in range(6):
print(x)
0…………………………………..5

Example
Using the start parameter:

for x in range(2, 6):


print(x)

ER.VIPIN RAWAT DEPARTMENT OF COMPUTER SCIENCE Page 21


Else in For Loop
The else keyword in a for loop specifies a block of code to be
executed when the loop is finished:

Example
Print all numbers from 0 to 5, and print a message when the loop
has ended:

for x in range(6):
print(x)
else:
print("Finally finished!")

ER.VIPIN RAWAT DEPARTMENT OF COMPUTER SCIENCE Page 22


UNIT 3

Python Functions

A function is a block of code which only runs when it is called.

You can pass data, known as parameters, into a function.

A function can return data as a result.

Creating a Function

In Python a function is defined using the def keyword:

Example

def my_function():
print("Hello from a function")

Calling a Function

To call a function, use the function name followed by parenthesis:

Example

def my_function():
print("Hello from a function")

my_function()

ER.VIPIN RAWAT DEPARTMENT OF COMPUTER SCIENCE Page 23


parameters

Information can be passed to functions as parameter.

Parameters are specified after the function name, inside the parentheses. You can add
as many parameters as you want, just separate them with a comma.

The following example has a function with one parameter (fname). When the function
is called, we pass along a first name, which is used inside the function to print the full
name:

Example
def my_function(fname):
print(fname + " Refsnes")

my_function("Emil")
my_function("Tobias")
my_function("Linus")

Keyword Arguments
You can also send arguments with the key = value syntax.

This way the order of the arguments does not matter.

Example
def my_function(child3, child2, child1):
print("The youngest child is " + child3)

my_function(child1 = "Emil", child2 = "Tobias", child3 = "Linus")

Default Parameter Value


The following example shows how to use a default parameter value.

If we call the function without parameter, it uses the default value:

Example
ER.VIPIN RAWAT DEPARTMENT OF COMPUTER SCIENCE Page 24
def my_function(country = "Norway"):
print("I am from " + country)

my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")

Python Scope
A variable is only available from inside the region it is
created. This is called scope.

Local Scope
A variable created inside a function belongs to the local scope of that
function, and can only be used inside that function.

Example
A variable created inside a function is available inside that function:

def myfunc():
x = 300
print(x)

myfunc()

Function Inside Function


As explained in the example above, the variable x is not available outside
the function, but it is available for any function inside the function:

Example
The local variable can be accessed from a function within the function:

def myfunc():
x = 300
def myinnerfunc():

ER.VIPIN RAWAT DEPARTMENT OF COMPUTER SCIENCE Page 25


print(x)
myinnerfunc()

myfunc()

Global Scope
A variable created in the main body of the Python code is a global
variable and belongs to the global scope.

Global variables are available from within any scope, global and local.

Example
A variable created outside of a function is global and can be used by
anyone:

x = 300

def myfunc():
print(x)

myfunc()

print(x)

Python Strings

String Literals
String literals in python are surrounded by either single quotation marks, or double
quotation marks.

'hello' is the same as "hello".

You can display a string literal with the print() function:

Example

print("Hello")
print('Hello')

Assign String to a Variable


ER.VIPIN RAWAT DEPARTMENT OF COMPUTER SCIENCE Page 26
Assigning a string to a variable is done with the variable name followed by an equal
sign and the string:

Example

a = "Hello"
print(a)

Strings are Arrays

Like many other popular programming languages, strings in Python are arrays of bytes
representing unicode characters.

However, Python does not have a character data type, a single character is simply a
string with a length of 1.

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

Example

Get the character at position 1 (remember that the first character has the position 0):

a = "Hello, World!"
print(a[1])

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

Example

Get the characters from position 2 to position 5 (not included):

b = "Hello, World!"
print(b[2:5])

Negative Indexing

Use negative indexes to start the slice from the end of the string:

Example
ER.VIPIN RAWAT DEPARTMENT OF COMPUTER SCIENCE Page 27
Get the characters from position 5 to position 1, starting the count from the end of the
string:

b = "Hello, World!"
print(b[-5:-2])

String Length

To get the length of a string, use the len() function.

Example

The len() function returns the length of a string:

a = "Hello, World!"
print(len(a))

String Concatenation

To concatenate, or combine, two strings you can use the + operator.

Example

Merge variable a with variable b into variable c:

a = "Hello"
b = "World"
c=a+b
print(c)
Python Classes and Objects

Python Classes/Objects

Python is an object oriented programming language.

Almost everything in Python is an object, with its properties and methods.

A Class is like an object constructor, or a "blueprint" for creating objects.

Create a Class

ER.VIPIN RAWAT DEPARTMENT OF COMPUTER SCIENCE Page 28


To create a class, use the keyword class:

Example

Create a class named MyClass, with a property named x:

class MyClass:
x=5

Create Object

Now we can use the class named myClass to create objects:

Example

Create an object named p1, and print the value of x:

p1 = MyClass()
print(p1.x)
Python Lambda

A lambda function is a small anonymous function.

A lambda function can take any number of arguments, but can only have one
expression.

Syntax

lambda arguments : expression

The expression is executed and the result is returned:

Example

A lambda function that adds 10 to the number passed in as an argument, and print the
result:

x = lambda a : a + 10
print(x(5))

Lambda functions can take any number of arguments:

Example

A lambda function that multiplies argument a with argument b and print the result:

ER.VIPIN RAWAT DEPARTMENT OF COMPUTER SCIENCE Page 29


x = lambda a, b : a * b
print(x(5, 6))

PYTHON DATA STRUCTURE


Python Collections (Arrays)
There are four collection data types in the Python programming language:

 List is a collection which is ordered and changeable. Allows


duplicate members.
 Tuple is a collection which is ordered and unchangeable. Allows
duplicate members.
 Set is a collection which is unordered and unindexed. No duplicate
members.
 Dictionary is a collection which is unordered, changeable and
indexed. No duplicate members.

When choosing a collection type, it is useful to understand the properties


of that type. Choosing the right type for a particular data set could mean
retention of meaning, and, it could mean an increase in efficiency or
security.

List
A list is a collection which is ordered and changeable. In Python lists are
written with square brackets.

Example
Create a List:

thislist = ["apple", "banana", "cherry"]


print(thislist)

ER.VIPIN RAWAT DEPARTMENT OF COMPUTER SCIENCE Page 30


Access Items
You access the list items by referring to the index number:

Example
Print the second item of the list:

thislist = ["apple", "banana", "cherry"]


print(thislist[1])

Negative Indexing
Negative indexing means beginning from the end, -1 refers to the last
item, -2 refers to the second last item etc.

Example
Print the last item of the list:

thislist = ["apple", "banana", "cherry"]


print(thislist[-1])

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 list with the
specified items.

Example
Return the third, fourth, and fifth item:

ER.VIPIN RAWAT DEPARTMENT OF COMPUTER SCIENCE Page 31


thislist =
["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango
"]
print(thislist[2:5])

Range of Negative Indexes


Specify negative indexes if you want to start the search from the end of
the list:

Example
This example returns the items from index -4 (included) to index -1
(excluded)

thislist =
["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango
"]
print(thislist[-4:-1]

Change Item Value


To change the value of a specific item, refer to the index number:

Example
Change the second item:

thislist = ["apple", "banana", "cherry"]


thislist[1] = "blackcurrant"
print(thislist)

Loop Through a List


You can loop through the list items by using a for loop:

Example
ER.VIPIN RAWAT DEPARTMENT OF COMPUTER SCIENCE Page 32
Print all items in the list, one by one:

thislist = ["apple", "banana", "cherry"]


for x in thislist:
print(x)

List Length
To determine how many items a list has, use the len() method:

Example
Print the number of items in the list:

thislist = ["apple", "banana", "cherry"]


print(len(thislist))

Add Items
To add an item to the end of the list, use the append() method:

Example
Using the append() method to append an item:

thislist = ["apple", "banana", "cherry"]


thislist.append("orange")
print(thislist)

Remove Item
There are several methods to remove items from a list:

Example
The remove() method removes the specified item:

ER.VIPIN RAWAT DEPARTMENT OF COMPUTER SCIENCE Page 33


thislist = ["apple", "banana", "cherry"]
thislist.remove("banana")
print(thislist)

Join Two Lists


There are several ways to join, or concatenate, two or more lists in
Python.

One of the easiest ways are by using the + operator.

Example
Join two list:

list1 = ["a", "b" , "c"]


list2 = [1, 2, 3]

list3 = list1 + list2


print(list3)

Tuple
A tuple is a collection which is ordered and unchangeable. In Python tuples are
written with round brackets.

Example

ER.VIPIN RAWAT DEPARTMENT OF COMPUTER SCIENCE Page 34


Create a Tuple:

thistuple = ("apple", "banana", "cherry")


print(thistuple)

Access Tuple Items


You can access tuple items by referring to the index number, inside square
brackets:

Example
Print the second item in the tuple:

thistuple = ("apple", "banana", "cherry")


print(thistuple[1])

OUTPUT: banana

Negative Indexing
Negative indexing means beginning from the end, -1 refers to the last item, -
2 refers to the second last item etc.

Example
Print the last item of the tuple:

thistuple = ("apple", "banana", "cherry")


print(thistuple[-1])

OUTPUT: cherry

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:

ER.VIPIN RAWAT DEPARTMENT OF COMPUTER SCIENCE Page 35


thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
print(thistuple[2:5])

OUTPUT:

('cherry', 'orange', 'kiwi')

Range of Negative Indexes


Specify negative indexes if you want to start the search from the end of the tuple:

Example
This example returns the items from index -4 (included) to index -1 (excluded)

thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")


print(thistuple[-4:-1])

('orange', 'kiwi', 'melon')

Python Sets
Set
A set is a collection which is unordered and unindexed. In Python sets are written
with curly brackets.

Example
Create a Set:

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


print(thisset)

OUTPUT: {"apple", "banana", "cherry"}

ER.VIPIN RAWAT DEPARTMENT OF COMPUTER SCIENCE Page 36


Access Items
You cannot access items in a set 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.

Example
Loop through the set, and print the values:

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

for x in thisset:
print(x)

OUTPUT:

banana
apple
cherry

Add Items
To add one item to a set use the add() method.

To add more than one item to a set use the update() method.

Example
Add an item to a set, using the add() method:

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

thisset.add("orange")

print(thisset)

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

ER.VIPIN RAWAT DEPARTMENT OF COMPUTER SCIENCE Page 37


Example
Remove "banana" by using the remove() method:

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

thisset.remove("banana")

print(thisset)

Join Two Sets


There are several ways to join two or more sets in Python.

You can use the union() method that returns a new set containing all items from
both sets, or the update() method that inserts all the items from one set into
another:

Example
The union() method returns a new set with all items from both sets:

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


set2 = {1, 2, 3}

set3 = set1.union(set2)
print(set3)

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

Python Dictionaries
Dictionary
A dictionary is a collection which is unordered, changeable and indexed. In Python
dictionaries are written with curly brackets, and they have keys and values.

Example
Create and print a dictionary:

ER.VIPIN RAWAT DEPARTMENT OF COMPUTER SCIENCE Page 38


thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)

{'brand': 'Ford', 'model': 'Mustang', 'year': 1964}

Accessing Items
You can access the items of a dictionary by referring to its key name, inside square
brackets:

x = thisdict["model"]

Change Values
You can change the value of a specific item by referring to its key name:

Example
Change the "year" to 2018:

thisdict = {

"brand": "Ford",

"model": "Mustang",

"year": 1964

thisdict["year"] = 2018

print(thisdict)

{'brand': 'Ford', 'model': 'Mustang', 'year': 2018}

ER.VIPIN RAWAT DEPARTMENT OF COMPUTER SCIENCE Page 39


UNIT – IV

SIEVE OF ERATOSTHENES

The sieve of Eratosthenes is one of the most efficient ways to find all primes smaller than n
when n is smaller than 10 million or so…

Following is the algorithm to find all the prime numbers less than or equal to a given
integer n by Eratosthenes’ method:

1. Create a list of consecutive integers from 2 to n: (2, 3, 4, …, n).


2. Initially, let p equal 2, the first prime number.
3. Starting from p2, count up in increments of p and mark each of these numbers
greater than or equal to p2 itself in the list. These numbers will be p(p+1), p(p+2),
p(p+3), etc..
4. Find the first number greater than p in the list that is not marked. If there was no such
number, stop. Otherwise, let p now equal this number (which is the next prime), and
repeat from step 3.
Explanation with Example:
Let us take an example when n = 50. So we need to print all print numbers smaller than or
ER.VIPIN RAWAT DEPARTMENT OF COMPUTER SCIENCE Page 40
equal to 50.
We create a list of all numbers from 2 to 50.

According to the algorithm we will mark all the numbers which are divisible by 2
and are greater than or equal to the square of it.

ER.VIPIN RAWAT DEPARTMENT OF COMPUTER SCIENCE Page 41


Now we move to our next unmarked number 3 and mark all the numbers which
are multiples of 3 and are greater than or equal to the square of it.

We move to our next unmarked number 5 and mark all multiples of 5 and are greater
than or equal to the square of it.

We continue this process and our final table will look like below:

So the prime numbers are the unmarked ones: 2, 3, 5, 7, 11, 13, 17, 19, 23,
29, 31, 37, 41, 43, 47.

ER.VIPIN RAWAT DEPARTMENT OF COMPUTER SCIENCE Page 42


Implementation:

Following is the implementation of the above algorithm. In the following


implementation, a boolean array arr[] of size n is used to mark multiples of prime
numbers.

# Python program to print all primes smaller than or equal to # n using Sieve of
Eratosthenes
defSieveOfEratosthenes(n):
# Create a boolean array "prime[0..n]" and initialize # all entries it as true. A
value in prime[i] will # finally be false if i is Not a prime, else true. prime =
[Truefori inrange(n+1)]

p =2
while(p *p <=n):
# If prime[p] is not changed, then it is a prime if(prime[p] ==True):
# Update all multiples of p
fori inrange(p *p, n+1, p): prime[i] =False
p +=1
# Print all prime numbers forp in
range(2, n):
ifprime[p]:
printp, #
driver program
if name ==' main ': n =30
print"Following are the prime numbers smaller", print "than or equal to", n
SieveOfEratosthenes(n)

Output:
Following are the prime numbers below 30
2 3 5 7 11 13 17 19 23 29

Time complexity : O(n*log(log(n)))

ER.VIPIN RAWAT DEPARTMENT OF COMPUTER SCIENCE Page 43


FILE I/O OPERATION

1)Input Operation

Python provides us with two inbuilt functions to read the input from the keyboard.

 raw_input()
 input()

raw_input(): This function reads only one line from the standard input and returns it as a
String.

Note: This function is decommissioned in Python 3.

Example:

1 value = raw_input(“Please enter the value: ”);

2 print(“Inputreceived fromthe user is: ”, value)

Output:

Please enter the value: Hello Python

Input received from the user is: Hello Python

input(): The input() function first takes the input from the user and then evaluates the
expression, which means python automatically identifies whether we entered a string or a
number or list.

But in Python 3 the raw_input() function was removed and renamed to input().

ER.VIPIN RAWAT DEPARTMENT OF COMPUTER SCIENCE Page 44


Example:

1 value = input(“Please enter the value:”);

2 print(“Inputreceived fromthe user is: ”, value)

Output:

Please enter the value: [10, 20, 30]

Input received from the user is: [10, 20, 30]

ER.VIPIN RAWAT DEPARTMENT OF COMPUTER SCIENCE Page 45


Output:

Output Operation

In order to print the output, python provides us with a built-in function called print().

Example:

1 Print(“Hello Python”)

Output:

Hello Python

Output:

ER.VIPIN RAWAT DEPARTMENT OF COMPUTER SCIENCE Page 46


ASSERTIONS & EXCEPTIONS

Assertion :

An assertion is a (debugging) boolean expression to self check an assumption about the


internal state of a function or object. If true, nothing happens otherwise, execution halts and
an error is thrown. Assertion is a way to declare a condition that is impossible to
occursWhen to use it? Assertions are used to indicate that something wrong happened. FEW
examples where assertions make more sense to use as opposed to exceptions.

 Parameter types for a private function (ex. the power has to be an integer in
exponential function)

 Precondition (ex. positive number in a square root function)

 Can not happen situations (ex. duplicates in a list, zero divisor)

 Corner cases that are hard to occur but possible (depends on the application)

 Automated unit testing (will provide an example later). What about exceptions.

The Assert Statement

When it encounters an assert statement, Python evaluates the accompanying


expression, which is hopefully true. If the expression is false, Python raises an
AssertionError exception.

The syntax for assert is −

assert Expression[, Arguments]

If the assertion fails, Python uses ArgumentExpression as the argument for the
AssertionError. AssertionError exceptions can be caught and handled like any other
exception using the try- except statement, but if not handled, they will terminate the
program and produce a traceback.

Exception :

ER.VIPIN RAWAT DEPARTMENT OF COMPUTER SCIENCE Page 47


An exception is an event, which occurs during the execution of a program that disrupts
the normal flow of the program's instructions. In general, when a Python script
encounters a situation that it cannot cope with, it raises an exception. An exception is a
Python object that represents an error.

When a Python script raises an exception, it must either handle the exception
immediately otherwise it terminates and quits.

Handling an exception

If you have some suspicious code that may raise an exception, you can defend your program
by placing the suspicious code in a try: block. After the try: block, include

an except: statement, followed by a block of code which handles the problem as elegantly as
possible.

Syntax

Here is simple syntax of try....except...else blocks −

try:

You do your operations here;

......................

except ExceptionI:

If there is ExceptionI, then execute this block. except ExceptionII:

If there is ExceptionII, then execute this block.

......................

else:

If there is no exception then execute this block.

Here are few important points about the above-mentioned syntax −

 A single try statement can have multiple except statements. This is useful when the
try block contains statements that may throw different types of exceptions.

ER.VIPIN RAWAT DEPARTMENT OF COMPUTER SCIENCE Page 48


 You can also provide a generic except clause, which handles any exception.

 After the except clause(s), you can include an else-clause. The code in the else-block
executes if the code in the try: block does not raise an exception.

 The else-block is a good place for code that does not need the try: block's protection.

User-Defined Exceptions

Python also allows you to create your own exceptions by deriving classes from the standard
built-in exceptions. Here is an example related to RuntimeError. Here, a class is created that
is subclassed from RuntimeError.

class Networkerror(RuntimeError):
def init (self, arg):
self.args = arg

So once you defined above class, you can raise the exception as follows −

an except: statement, followed by a block of code which handles the problem as elegantly as
possible.

Syntax

Here is simple syntax of try....except...else blocks −

try:

You do your operations here;

......................

except ExceptionI:

If there is ExceptionI, then execute this block. except ExceptionII:

If there is ExceptionII, then execute this block.

......................

else:

If there is no exception then execute this block.

ER.VIPIN RAWAT DEPARTMENT OF COMPUTER SCIENCE Page 49


Here are few important points about the above-mentioned syntax −

 A single try statement can have multiple except statements. This is useful when the
try block contains statements that may throw different types of exceptions.

 You can also provide a generic except clause, which handles any exception.

 After the except clause(s), you can include an else-clause. The code in the else-block
executes if the code in the try: block does not raise an exception.

 The else-block is a good place for code that does not need the try: block's protection.

User-Defined Exceptions

Python also allows you to create your own exceptions by deriving classes from the standard
built-in exceptions. Here is an example related to RuntimeError. Here, a class is created that
is subclassed from RuntimeError.

class Networkerror(RuntimeError):
def init (self, arg):
self.args = arg

So once you defined above class, you can raise the exception as follows −

try:

raise Networkerror("Bad hostname") except


Networkerror,e:

print e.args

ER.VIPIN RAWAT DEPARTMENT OF COMPUTER SCIENCE Page 50


PYTHON - MODULES

A module allows you to logically organize your Python code. Grouping related code into a
module makes the code easier to understand and use. A module is a Python object with
arbitrarily named attributes that you can bind and referenceSimply, a module is a file
consisting of Python code. A module can define functions, classes and variables. A module
can also include runnable code.

Example

The Python code for a module named aname normally resides in a file named aname.py.
Here's an example of a simple module, support.py

def print_func( par ):


print "Hello : ", par
return

The import Statement

You can use any Python source file as a module by executing an import statement in some
other Python source file. The import has the following syntax −

import module1[, module2[,...


moduleN] The from...import *
Statement

It is also possible to import all names from a module into the current namespace by using the
following import statement −

from modname import *

This provides an easy way to import all the items from a module into the current namespace;
however, this statement should be used sparingly.

ER.VIPIN RAWAT DEPARTMENT OF COMPUTER SCIENCE Page 51


The from...import * Statement

It is also possible to import all names from a module into the current namespace by using the
following import statement −

from modname import *

This provides an easy way to import all the items from a module into the current namespace;
however, this statement should be used sparingly.

Locating Modules

When you import a module, the Python interpreter searches for the module in the following
sequences −

 The current directory.

 If the module isn't found, Python then searches each directory in the shell variable
PYTHONPATH.

 If all else fails, Python checks the default path. On UNIX, this default path is normally

/usr/local/lib/python/.

The module search path is stored in the system module sys as the sys.path variable. The sys.path
variable contains the current directory, PYTHONPATH, and the installation- dependent default

ER.VIPIN RAWAT DEPARTMENT OF COMPUTER SCIENCE Page 52


.

ABSTRACT DATA TYPE

Abstract Data type: Abstract Data type (ADT) is a type (or class) for objects whose
behaviour is defined by a set of value and a set of operations.

The definition of ADT only mentions what operations are to be performed but not how these
operations will be implemented. It does not specify how data will be organized in memory
and what algorithms will be used for implementing the operations. It is called “abstract”
because it gives an implementation-independent view. The process of providing only the
essentials and hiding the details is known as abstraction.

Example: Stack

A stack is a lifo (last in first out ) list with the following operation : Push , Pop,
Create(init),Top, IsEmpty, Size . ( Suchb a list is called a signature or thr interface to the
ADT.)

Stack ADT

ER.VIPIN RAWAT DEPARTMENT OF COMPUTER SCIENCE Page 53


Example : Queue

A Queue is a FIFO(first in first out) list with the following operations: Enqueue
, Dequeue , Size, Font

ER.VIPIN RAWAT DEPARTMENT OF COMPUTER SCIENCE Page 54


CLASSES

Definition : In object oriented programming classes and objects are the main features. A class
creates a new data type and objects are instances of a class which follows the definition given
inside the class. Here is a simple form of class definition.

class Student:
Statement-1
Statement-1
....

ER.VIPIN RAWAT DEPARTMENT OF COMPUTER SCIENCE Page 55


....

....

Statement-n

A class definition started with the keyword 'class' followed by the name of the class and a
colon.

The statements within a class definition may be function definitions, data members or other
statements.

When a class definition is entered, a new namespace is created, and used as the local scope.

Creating a Class:

Here we create a simple class using class keyword followed by the class name (Student) which
follows an indented block

of segments (student class, roll no., name).

studentdetails.py class Student:

stu_class = 'V' stu_roll_no = 12

stu_name = "Davi

ER.VIPIN RAWAT DEPARTMENT OF COMPUTER SCIENCE Page 56


Class Objects: There are two kind of operations class objects supports : attribute references and
instantiation. Attribute references use the standard syntax, obj.name for all attribute references in
Python. Therefore if the class definition (add a method in previous example) look like this

#studentdetails1.p

y class Student:

"""A simple example class"""

stu_class = 'V'

stu_roll_no = 12

stu_name = "David"

def messg(self):

return 'New Session will start soon.'

Special methods

A collection of special methods, with two leading and trailing underscores in the method
names, offers special syntax in Python programs.

The table below provides an overview of the most important special methods

ER.VIPIN RAWAT DEPARTMENT OF COMPUTER SCIENCE Page 57


Construction Meaning2

a. init (self, args) constructor: a = A(args)

a. del (self) destructor: del


a
a. call (self, args) call as function: a(args)

a. str (self) pretty print: print a,


str(a)
a. repr (self) representation: a =
eval(repr(a))
a. add (self, b) a+b

a. sub (self, b) a-b

a. mul (self, b) a*b

a. div (self, b) a/
b
a. radd (self, b) b+a

a. rsub (self, b) b-a

a. rmul (self, b) b*a

a. rdiv (self, b) b/
a
a. pow (self, p) a**p

a. lt (self, b) a<b

a. gt (self, b) a>b

a. le (self, b) a <= b

a. ge (self, b) a => b

a. eq (self, b) a == b

a. neself, b) a != b

a. bool (self) boolean expression, as in if a:

a. len (self) length of a (int): len(a)

objecta. abs
init (self)(self[, ...]) abs(a)

Called after the instance has been created (by new ()), but before it is returned to

ER.VIPIN RAWAT DEPARTMENT OF COMPUTER SCIENCE Page 58


the caller. The arguments are those passed to the class constructor expression. If a base
class has an init () method, the derived class’s init () method, if any, must
explicitly call it to ensure proper initialization of the base class part of the instance; for
example: super(). init ([args...]).

Because new () and __init () work together in constructing objects (__new () to


create it, and init () to customize it), no non-None value may be returned
by init (); doing so will cause a TypeError to be raised at runtime.

object. str (self)

Called by str(object) and the built-in functions format() and print() to compute the
“informal” or nicely printable string representation of an object. The return value must
be a string object.

This method differs from object. repr () in that there is no expectation


that str () return a valid Python expression: a more convenient or concise
representation can be used.

The default implementation defined by the built-in type object calls object. repr ().

Comparison Methods :

The comparison methods were first introduced in Python 2.1 and they are also called
‘rich comparison methods’ or ‘comparison magic methods’

object. lt (self, other) # For x < y


object. le (self, other) # For x <= y
object. eq (self, other) # For x == y

object. ne (self, other) # For x != y OR x <> y object.


gt (self, other) # For x > y

object. ge (self, other) # For x >= y

ER.VIPIN RAWAT DEPARTMENT OF COMPUTER SCIENCE Page 59


 The most common usage is to return False or True when using one of the rich
comparison methods, but you can actually return any value you want, it really
depends on the context of how you use them.

 If x == y it doesn’t mean that x != y. The best practice is always to define

ne () if eq () was defined.

 A rich comparison method may return “NotImplemented” if the operation is not


implemented for a given pair of arguments.

Arithmetic Method :

 a + b : a. add (b)
 a - b : a. sub (b)
 a*b : a. mul (b)
 a/b : a. div (b)
 a**b : a. pow (b)

ER.VIPIN RAWAT DEPARTMENT OF COMPUTER SCIENCE Page 60


PYTHON > CLASSES > EXAMPLE :

1. Create Object

Now we can use the class named myClass to create objects:

Example Create an object named p1, and print the value of


x: p1 = MyClass()

print(p1.x)

2. Modify Object Properties

You can modify properties on objects like this:

Example

Set the age of p1 to 40:

p1.age = 40

3. Delete Object Properties

You can delete properties on objects by using the del keyword:

Example

Delete the age property from the p1 object:

del p1.age

ER.VIPIN RAWAT DEPARTMENT OF COMPUTER SCIENCE Page 61


4. Delete Objects

You can delete objects by using the delkeyword:

Example

Delete the p1 object:

del p1

5. The pass Statement

classdefinitions cannot be empty, but if you for some reason have

a classdefinition with no content, put in the passstatement to avoid getting an error.

Example

class Person:
pass

ER.VIPIN RAWAT DEPARTMENT OF COMPUTER SCIENCE Page 62


PYTHON INHERITANCE

Inheritance is the capability of one class to derive or inherit the properties from some
another class. The benefits of inheritance are:

1. It represents real-world relationships well.


2. It provides reusability of a code. We don’t have to write the same code
again and again. Also, it allows us to add more features to a class without
modifying it.
3. It is transitive in nature, which means that if class B inherits from another class A,
then all the subclasses of B would automatically inherit from class A.

Parent class is the class being inherited from, also called base class.

Child class is the class that inherits from another class, also called derived class.

Create a Parent Class-

Any class can be a parent class, so the syntax is the same as creating any other class:

Example

Create a class named Person, with firstname and lastname properties, and
a printname method:

class Person:

ER.VIPIN RAWAT DEPARTMENT OF COMPUTER SCIENCE Page 63


def init (self, fname, lname):
self.firstname = fname
self.lastname = lname

def printname(self): print(self.firstname,


self.lastname)

#Use the Person class to create an object, and then execute the printname
method:

x = Person("John", "Doe")
x.printname()

Create a Child Class-

To create a class that inherits the functionality from another class, send the parent
class as a parameter when creating the child class:

Example

Create a class named Student, which will inherit the properties and methods
from the Person class:

class Student(Person):

ER.VIPIN RAWAT DEPARTMENT OF COMPUTER SCIENCE Page 64


pass

INHERITANCE & OOP

Python is a multi-paradigm programming language. Meaning, it supports


different programming approach.

One of the popular approach to solve a programming problem is by creating objects.


This is known as Object-Oriented Programming (OOP).

An object has two characteristics:

 attributes
 behavior

Let's take an example:

Parrot is an object,

 name, age, color are attributes


 singing, dancing are behavior

The concept of OOP in Python focuses on creating reusable code. This concept is also
known as DRY (Don't Repeat Yourself).

ER.VIPIN RAWAT DEPARTMENT OF COMPUTER SCIENCE Page 65


In Python, the concept of OOP follows some basic principles:

A process of using details from a new class without modifying existing


Inheritance
class.

Encapsulation Hiding the private details of a class from other objects.

A concept of using common operation in different ways for different


Polymorphism
data input.

INHERITANCE:>>> Inheritance is a way of creating new class for using details of


existing class without modifying it. The newly formed class is a derived class (or child
class).
Similarly, the existing class is a base class (or parent class).

Example 3: Use of Inheritance in Python


# parent
class
class
Bird:
def init (self):
print("Bird is
ready")
def
whoisThis(se
lf):
print("Bird")
def swim(self):
print("Swim
faster")
# child class

ER.VIPIN RAWAT DEPARTMENT OF COMPUTER SCIENCE Page 66


class
Penguin(Bird
): def init
(self):
# call super()
function super(). init
() print("Penguin is
ready")
def
whoisThis(se
lf):
print("Pengui
n")
def run(self):
print("Run
faster")
peggy =
Penguin()
peggy.whoisT
his()
peggy.swim()
peggy.run()
output:
Bird is ready

Penguin is
ready
Penguin
Swim
faster
Run
faster

ER.VIPIN RAWAT DEPARTMENT OF COMPUTER SCIENCE Page 67


UNIT V

Fibonacci sequence:

A Fibonacci sequence is a sequence of integers which first two terms are 0 and 1
and all other terms of the sequence are obtained by adding their preceding two
numbers.

For example: 0, 1, 1, 2, 3, 5, 8, 13 and so on...

1. def recur_fibo(n):
2. if n <= 1:
3. return n
4. else:
5. return(recur_fibo(n-1) + recur_fibo(n-2))
6. # take input from the user
7. nterms = int(input("How many terms? "))
8. # check if the number of terms is valid
9. if nterms <= 0:
10. print("Plese enter a positive integer")
11. else:
12. print("Fibonacci sequence:")
13. for i in range(nterms):
14. print(recur_fibo(i))
output:-0, 1, 1, 2, 3, 5, 8, 13

ER.VIPIN RAWAT DEPARTMENT OF COMPUTER SCIENCE Page 68


Python Program for Tower of Hanoi
Tower of Hanoi is a mathematical puzzle where we have three rods and n disks.
The objective of the puzzle is to move the entire stack to another rod, obeying the
following simple rules:
1) Only one disk can be moved at a time.
2) Each move consists of taking the upper disk from one of the stacks and placing
it on top of another stack i.e. a disk can only be moved if it is the uppermost disk
on a stack
3) No disk may be placed on top of a smaller disk.

def TowerOfHanoi(n , from_rod, to_rod, aux_rod):


if n == 1:
print "Move disk 1 from rod",from_rod,"to rod",to_rod
return
TowerOfHanoi(n-1, from_rod, aux_rod, to_rod)
print "Move disk",n,"from rod",from_rod,"to rod",to_rod
TowerOfHanoi(n-1, aux_rod, to_rod, from_rod)

# Driver code
n=4
TowerOfHanoi(n, \'A\', \'C\', \'B\')
Output:
Move disk 1 from rod A to rod B
Move disk 2 from rod A to rod C
Move disk 1 from rod B to rod C
Move disk 3 from rod A to rod B
Move disk 1 from rod C to rod A

ER.VIPIN RAWAT DEPARTMENT OF COMPUTER SCIENCE Page 69


Move disk 2 from rod C to rod B
Move disk 1 from rod A to rod B
Move disk 4 from rod A to rod C
Move disk 1 from rod B to rod C
Move disk 2 from rod B to rod A
Move disk 1 from rod C to rod A
Move disk 3 from rod B to rod C
Move disk 1 from rod A to rod B
Move disk 2 from rod A to rod C
Move disk 1 from rod B to rod C

def moveTower(height,fromPole, toPole, withPole):


if height >= 1:
moveTower(height-1,fromPole,withPole,toPole)
moveDisk(fromPole,toPole)
moveTower(height-1,withPole,toPole,fromPole)

def moveDisk(fp,tp):
print("moving disk from",fp,"to",tp)

moveTower(3,"A","B","C")

Python Program for Selection Sort

The selection sort algorithm sorts an array by repeatedly finding the minimum element
(considering ascending order) from unsorted part and putting it at the beginning. The algorithm
maintains two subarrays in a given array.
1) The subarray which is already sorted.
2) Remaining subarray which is unsorted.
In every iteration of selection sort, the minimum element (considering ascending order) from the
unsorted subarray is picked and moved to the sorted subarray.
# Python program for implementation of Selection
# Sort
import sys
A = [64, 25, 12, 22, 11]

# Traverse through all array elements


ER.VIPIN RAWAT DEPARTMENT OF COMPUTER SCIENCE Page 70
for i in range(len(A)):

# Find the minimum element in remaining


# unsorted array
min_idx = i
for j in range(i+1, len(A)):
if A[min_idx] > A[j]:
min_idx = j

# Swap the found minimum element with


# the first element
A[i], A[min_idx] = A[min_idx], A[i]

# Driver code to test above


print ("Sorted array")
for i in range(len(A)):
print("%d" %A[i]),

Python Program for Merge Sort


Merge Sort is a Divide and Conquer algorithm. It divides input array in two halves,
calls itself for the two halves and then merges the two sorted halves. The merge()
function is used for merging two halves. The merge(arr, l, m, r) is key process that
assumes that arr[l..m] and arr[m+1..r] are sorted and merges the two sorted sub-
arrays into one.
# Python program for implementation of MergeSort

# Merges two subarrays of arr[].


# First subarray is arr[l..m]
# Second subarray is arr[m+1..r]
def merge(arr, l, m, r):
n1 = m - l + 1
n2 = r- m

# create temp arrays


L = [0] * (n1)
R = [0] * (n2)

# Copy data to temp arrays L[] and R[]


for i in range(0 , n1):
L[i] = arr[l + i]

ER.VIPIN RAWAT DEPARTMENT OF COMPUTER SCIENCE Page 71


for j in range(0 , n2):
R[j] = arr[m + 1 + j]

# Merge the temp arrays back into arr[l..r]


i = 0 # Initial index of first subarray
j = 0 # Initial index of second subarray
k = l # Initial index of merged subarray

while i < n1 and j < n2 :


if L[i] <= R[j]:
arr[k] = L[i]
i += 1
else:
arr[k] = R[j]
j += 1
k += 1

# Copy the remaining elements of L[], if there


# are any
while i < n1:
arr[k] = L[i]
i += 1
k += 1

# Copy the remaining elements of R[], if there


# are any
while j < n2:
arr[k] = R[j]
j += 1
k += 1

# l is for left index and r is right index of the


# sub-array of arr to be sorted
def mergeSort(arr,l,r):
if l < r:

# Same as (l+r)/2, but avoids overflow for


# large l and h
m = (l+(r-1))/2
ER.VIPIN RAWAT DEPARTMENT OF COMPUTER SCIENCE Page 72
# Sort first and second halves
mergeSort(arr, l, m)
mergeSort(arr, m+1, r)
merge(arr, l, m, r)

# Driver code to test above


arr = [12, 11, 13, 5, 6, 7]
n = len(arr)
print ("Given array is")
for i in range(n):
print ("%d" %arr[i]),

mergeSort(arr,0,n-1)
print ("\n\nSorted array is")
for i in range(n):
print ("%d" %arr[i]),
Given array is
12 11 13 5 6 7

Sorted array is
5 6 7 11 12 13

Factorial: Factorial of a number specifies a product of all integers from 1 to that number. It
is defined by the symbol explanation mark (!).

For example: The factorial of 5 is denoted as 5! = 1*2*3*4*5 = 120.

1. def recur_factorial(n):
2. if n == 1:
3. return n
4. else:
5. return n*recur_factorial(n-1)
6. # take input from the user
7. num = int(input("Enter a number: "))
8. # check is the number is negative

ER.VIPIN RAWAT DEPARTMENT OF COMPUTER SCIENCE Page 73


9. if num < 0:
10. print("Sorry, factorial does not exist for negative numbers")
11. elif num == 0:
12. print("The factorial of 0 is 1")
13. else:
14. print("The factorial of",num,"is",recur_factorial(num))

ER.VIPIN RAWAT DEPARTMENT OF COMPUTER SCIENCE Page 74

You might also like