Python Notes (KNC-402)
Python Notes (KNC-402)
Introduction
Python is a general-purpose interpreted, interactive, object-oriented, and high-level
programming language. It was created by Guido van Rossum during 1985- 1990.
Python is named after a TV Show called ‘Monty Python’s Flying Circus’ and not after
Python-the snake.
Python 3.0 was released in 2008.
Python is a high-level, interpreted, interactive and object-oriented scripting language.
Python is designed to be highly readable.
• 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.
History of Python
Python was developed by Guido van Rossum in the late eighties and early nineties at
the National Research Institute for Mathematics and Computer Science in the
Netherlands.
• Python is derived from many other languages, including Modula-3, C, C++,
Algol-68, SmallTalk, and Unix shell and other scripting languages.
• Python is copyrighted. Like Perl, Python source code is now available under the
General Public License (GPL).
• Python is now maintained by a core development team at the institute, although
Guido van Rossum still holds a vital role in directing its progress.
• Python 1.0 was released in November 1994. In 2000, Python 2.0 was released.
Python 2.7.11 is the latest edition of Python 2.
• Meanwhile, Python 3.0 was released in 2008. Python 3 is not backward
compatible with Python 2. The emphasis in Python 3 had been on the removal
of duplicate programming constructs and modules so that "There should be one
-- and preferably only one -- obvious way to do it." Python 3.8.0, documentation
released on 14 October 2019 is the latest version of Python 3.
Python Features
Python's features include −
After installing Python, you should be able to invoke Python on the command line in a
terminal window by typing the name of the program.
This opens the Python Interpreter, where you can run Python code directly in the
terminal by typing ‘python’ and hitting the Enter key:
$ python3.8
Python 3.8 (default, Sep 16 2015, 09:25:04)
[GCC 4.8.2] on linux
Type "help", "copyright", "credits" or "license" for more
information.
>>>
>>>
>>> 4+5
----------------------------
-------------------------------
>>>print(“Hello, Students”)
>>> name
'Sachin Tendulkar'
>>> print(name)
Sachin Tendulkar
---------------------------------------------
>>> c=a+b
Sum = 30
----------------------------------
>>> c=a+b
>>> c
'1020'
1020
----------------------------------------
>>> area=3.14*radius*radius
----------------------------------------------------------------------------------
Enter time--2
>>> SI=(p*r*t)/100
----------------------------------------------------------------
Elements of Python:
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).
Reserved Words
• The following list shows the Python keywords. These are reserved words and
you cannot use them as constants or variables or any other identifier names. All
the Python keywords contain lowercase letters only.
as finally or
continue if return
del in while
elif is with
except
if True:
print ("True")
else:
print ("False")
if True:
print ("Answer")
print ("True")
else:
print ("Answer")
print ("False")
Multi-Line Statements
Statements in Python typically end with a new line. Python, however, allows the use of
the line continuation character (\) to denote that the line should continue. For example
total = item_one + \
item_two + \
item_three
10 | P a g e Python Programming (KNC-402)
The statements contained within the [], {}, or () brackets do not need to use the line
continuation character. For example −
Quotation in Python
Python accepts single ('), double (") and triple (''' or """) quotes to denote string
literals, as long as the same type of quote starts and ends the string.
The triple quotes are used to span the string across multiple lines. For example, all the
following are legal −
word = 'word'
Comments in Python
A hash sign (#) that is not inside a string literal is the beginning of a comment. All
characters after the #, up to the end of the physical line, are part of the comment and
the Python interpreter ignores them.
# First comment
For multiple-line commenting feature. You have to comment each line individually as
follows −
# This is a comment.
“””This is a comment.
‘’’This is a comment.
Variables
Variables are nothing but reserved memory locations to store values. It means that
when you create a variable, you reserve some space in the 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 the variables, you can store integers, decimals or characters in these
variables.
-----------------------------------
>>> a=10
>>> a
10
>>> b=20.58
>>> b
20.58
>>> c='PYTHON'
>>> c
' PYTHON '
---------------------------------
Multiple Assignment
Python allows you to assign a single value to several variables simultaneously.
For example –
a = b = c = 1
a, b, c = 1, 2.5, "Viraat"
Here, two integer objects with values 1 and 2 are assigned to the variables a and b
respectively, and one string object with the value "ITS" is assigned to the variable c.
Python Numbers
Number data types store numeric values. Number objects are created when you assign
a value to them. For example −
a = 10
b = 20
You can also delete the reference to a number object by using the del statement. You
can delete a single object or multiple objects by using the del statement.
For example −
del a
del a, b
Examples
Here are some examples of numbers −
10 0.05 3.14j
Python Strings
Strings in Python are identified as a contiguous set of characters represented in the
quotation marks. Python allows either pair of single or double quotes. Subsets of
strings can be taken using the slice operator ([ ] and [:] ) with indexes starting at 0 in
the beginning of the string and working their way to end -1.
The plus (+) sign is the string concatenation operator and the asterisk (*) is the
repetition operator. For example −
---------------------------------------------------
------------------------------------------------------------------------------
Python Lists
Lists are the most versatile of Python's compound data types. A list contains
items separated by commas and enclosed within square brackets ([]). To
some extent, lists are similar to arrays in C. One of the differences between
them is that all the items belonging to a list can be of different data type.
The values stored in a list can be accessed using the slice operator ([ ] and [:]) with
indexes starting at 0 in the beginning of the list and working their way to end -1. The
plus (+) sign is the list concatenation operator, and the asterisk (*) is the repetition
operator. For example −
Deletion in List-
>>> a=[1,2,3]
>>> a.remove(2)
>>> a
[1, 3]
>>> a=[1,2,3]
>>> del a[1]
>>> a
[1, 3]
>>> a= [1,2,3]
>>> a.pop(1)
2
>>> a
[1, 3]
>>>
• remove removes the first matching value, not a specific index:
• del removes the item at a specific index:
• and pop removes the item at a specific index and returns it.
1 cmp(list1, list2)
len(list)
2
Gives the total length of the list.
max(list)
3
Returns item from the list with max value.
min(list)
4
Returns item from the list with min value.
list(seq)
5
Converts a tuple into list.
list.append(obj)
1
Appends object obj to list
list.count(obj)
2
Returns count of how many times obj occurs in list
list.extend(seq)
3
Appends the contents of seq to list
list.index(obj)
4
Returns the lowest index in list that obj appears
list.insert(index, obj)
5
Inserts object obj into list at offset index
6 list.pop(obj = list[-1])
list.remove(obj)
7
Removes object obj from list
list.reverse()
8
Reverses objects of list in place
list.sort([func])
9
Sorts objects of list, use compare func if given
Python Tuples
A tuple is a sequence of immutable Python objects. Tuples are sequences, just
like lists. The main difference between the tuples and the lists is that the
tuples cannot be changed unlike lists. Tuples use parentheses, whereas lists
use square brackets.
tuple is another sequence data type that is similar to the list. A tuple consists of a
number of values separated by commas. Unlike lists, however, tuples are enclosed
within parenthesis.
The main difference between lists and tuples are − Lists are enclosed in brackets ( [ ] )
and their elements and size can be changed, while tuples are enclosed in parentheses
( ( ) ) and cannot be updated. Tuples can be thought of as read-only lists. For
example −
The following code is invalid with tuple, because we attempted to update a tuple,
which is not allowed. Similar case is possible with lists −
cmp(tuple1, tuple2)
1
Compares elements of both tuples.
len(tuple)
2
Gives the total length of the tuple.
max(tuple)
3
Returns item from the tuple with max value.
min(tuple)
4
Returns item from the tuple with min value.
tuple(seq)
5
Converts a list into tuple.
Python Dictionary
Each key is separated from its value by a colon (:), the items are separated by
commas, and the whole thing is enclosed in curly braces. An empty dictionary without
any items is written with just two curly braces, like this: {}.
Keys are unique within a dictionary while values may not be. The values of a dictionary
can be of any type, but the keys must be of an immutable data type such as strings,
numbers, or tuples.
For example −
This is one
This is two
{'name': 'john', 'dept': 'sales', 'code': 6734}
dict_keys(['name', 'dept', 'code'])
dict_values(['john', 'sales', 6734])
Updating Dictionary
You can update a dictionary by adding a new entry or a key-value pair, modifying an
existing entry, or deleting an existing entry.
(a) More than one entry per key is not allowed. This means no duplicate key is
allowed. When duplicate keys are encountered during assignment, the last assignment
wins. For example −
(b) Keys must be immutable. This means you can use strings, numbers or tuples as
dictionary keys but something like ['key'] is not allowed.
cmp(dict1, dict2)
1
No longer available in Python 3.
len(dict)
2 Gives the total length of the dictionary. This would be equal to the
number of items in the dictionary.
str(dict)
3 Produces a printable string representation of a dictionary
type(variable)
4 Returns the type of the passed variable. If passed variable is dictionary,
then it would return a dictionary type.
dict.clear()
1
Removes all elements of dictionary dict
dict.items()
2 Returns a list of dict's (key, value) tuple pairs
dict.keys()
3 Returns list of dictionary dict's keys
dict.update(dict2)
4 Adds dictionary dict2's key-values pairs to dict
dict.values()
5 Returns list of dictionary dict's values
Eval- In simple terms, the eval() method runs the python code (which is passed as an
argument) within the program.
>>> x = 1
>>> eval('x + 1')
2
>>> eval('x')
1
When a description of an arithmetic operator below uses the phrase “the numeric
arguments are converted to a common type,” this means that the operator
implementation for built-in types works as follows:
Some additional rules apply for certain operators (e.g., a string as a left argument to
the ‘%’ operator). Extensions must define their own conversion behavior.
There are several built-in functions to perform conversion from one data type to
another. These functions return a new object representing the converted value.
int(x)
1
Converts x to an integer.
float(x)
2
Converts x to a floating-point number.
complex(real [,imag])
3
Creates a complex number.
str(x)
4
Converts object x to a string representation.
eval(str)
5
Evaluates a string and returns an object.
tuple(s)
6
Converts s to a tuple.
list(s)
7
Converts s to a list.
set(s)
8
Converts s to a set.
dict(d)
9
Creates a dictionary. d must be a sequence of (key,value) tuples.
chr(x)
10
Converts an integer to a character.
ord(x)
11
Converts a single character to its integer value.
hex(x)
12
Converts an integer to a hexadecimal string.
oct(x)
13
Converts an integer to an octal string.
Expressions
24 | P a g e Python Programming (KNC-402)
an expression in python is a block of code that produces a result or value upon
evaluation. A simple example of an expression is 6+3. An expression can be broken
doun into operators and operands. Operators are symbols which help the user or
command computer to perform mathematical or logical operations.
Operators
Operators are the constructs, which can manipulate the value of operands. Consider the
expression 4 + 5 = 9. Here, 4 and 5 are called the operands and + is called the
operator.
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
Assume variable a holds the value 10 and variable b holds the value 20, then
Bitwise operator works on bits and performs bit-by-bit operation. Assume if a = 60;
and b = 13; Now in binary format they will be as follows −
a = 0011 1100
b = 0000 1101
-----------------
a&b = 0000 1100
a|b = 0011 1101
a^b = 0011 0001
~a = 1100 0011
and Logical If both the operands are true then condition (a and b) is
AND becomes true. False.
Identity operators compare the memory locations of two objects. There are two
Identity operators as explained below −
**
1
Exponentiation (raise to the power)
~+-
2 Complement, unary plus and minus (method names for the last two are
+@ and -@)
* / % //
3
Multiply, divide, modulo and floor division
+-
4
Addition and subtraction
>> <<
5
Right and left bitwise shift
^|
7
Bitwise exclusive `OR' and regular `OR'
<> == !=
9
Equality operators
= %= /= //= -= += *= **=
10
Assignment operators
is is not
11
Identity operators
in not in
12
Membership operators
not or and
13
Logical operators
1. help()
>>> help()
Welcome to Python 3.4's help utility!
If this is your first time using Python, you should definitely check out
the tutorial on the Internet at http://docs.python.org/3.4/tutorial/.
Enter the name of any module, keyword, or topic to get help on writing
Python programs and using Python modules. To quit this help utility and
return to the interpreter, just type "quit".
To get a list of available modules, keywords, symbols, or topics, type
"modules", "keywords", "symbols", or "topics". Each module also comes
with a one-line summary of what it does; to list the modules whose name or
summary contain a given string such as "spam", type "modules spam".
help> quit
>>>
5. type()
With one argument, return the type of an object.
---------------------
>>> a=10
>>> type(a)
<class 'int'>
>>> name="ABC"
>>> type(name)
<class 'str'>
----------------------
Size of a variable-
>>> from sys import getsizeof
>>> a=10
>>> getsizeof(a)
14 bytes
31 | P a g e Python Programming (KNC-402)
>>> a = 2**1000
>>> getsizeof(a)
146 bytes
Operator Precedence
10 + 20 * 30
For example: ‘*’ and ‘/’ have same precedence and their associativity is Left to Right,
so the expression “100 / 10 * 10” is treated as “(100 / 10) * 10”.
Associativity is only used when there are two or more operators of same precedence.
The point to note is associativity doesn’t define the order in which operands of a single
operator are evaluated. For example, consider the following program, associativity of
the + operator is left to right, but it doesn’t mean f1() is always called before f2(). The
output of the following program is in-fact compiler dependent.
• We can see in the above table that more than one operator exists in the same
group. These operators have the same precedence.
• When two operators have the same precedence, associativity helps to determine
which the order of operations.
• Associativity is the order in which an expression is evaluated that has multiple
operator of the same precedence. Almost all the operators have left-to-right
associativity.
• Exponent operator ** has right-to-left associativity in Python.
1. PI = 3.14
2. r = float(input('Enter the radius of the circle :'))
3. area = PI * r * r
4. print("Area of the circle is : ",area)
Decision Making
if statements
1 An if statement consists of a boolean expression followed by one or
more statements.
if...else statements
2 An if statement can be followed by an optional else statement, which
executes when the boolean expression is FALSE.
nested if statements
3 You can use one if or else if statement inside another if or else if
statement(s).
if Statement
Input Customer ID
Input Last Meter Reading(LMR)
Input Current Meter Reading(CMR)
Calculate the bill as per given unit consumption—
For first 150 units, charges are Rs. 3.0 per unit
For units >150 and <=300, charges are Rs. 4.5 per unit
For units>300 and <=500, charges are Rs. 6.0 per units
For Units >500, charges are Rs. 8.0 per unit.
Loops
A loop statement allows us to execute a statement or group of statements multiple times.
Python programming language provides the following types of loops to handle looping
requirements.
while Loop
38 | P a g e Python Programming (KNC-402)
for Loop
For loop provides a mechanism to repeat a task until a particular condition is True. It is usually
known as a determinate or definite loop because the programmer knows exactly how many
times the loop will repeat. The for...in statement is a looping statement used in Python to iterate
over a sequence of objects.
The range() function is a built-in function in Python that is used to iterate over a sequence of
numbers. The syntax of range() is range(beg, end, [step])
The range() produces a sequence of numbers starting with beg (inclusive) and ending with one
less than the number end. The step argument is option (that is why it is placed in brackets). By
default, every number in the range is incremented by 1 but we can specify a different increment
using step. It can be both negative and positive, but not zero.
• If range() is called with two arguments, it produces values from the first to the second. For
example, range(0,10).
• If range() has three arguments then the third argument specifies the interval of the sequence
produced. In this case, the third argument must be an integer. For example, range(1,20,3).
Nested Loops
• Python allows its users to have nested loops, that is, loops that can be placed inside other
loops. Although this feature will work with any loop like while loop as well as for loop.
• A for loop can be used to control the number of times a particular set of statements will
be executed. Another outer loop could be used to control the number of times that a
whole loop is repeated.
• Loops should be properly indented to identify which statements are contained within
each for statement.
Like the break statement, the continue statement can only appear in the body of a loop. When the
compiler encounters a continue statement then the rest of the statements in the loop are skipped and
the control is unconditionally transferred to the loop-continuation portion of the nearest enclosing
loop.
3.1 Functions
Functions
Python enables its programmers to break up a program into segments commonly known as functions, each
of which can be written more or less independently of the others. Every function in the program is
supposed to perform a well-defined task.
• A function, f that uses another function g, is known as the calling function and g is known as the called function.
• The inputs that the function takes are known as arguments/parameters.
• When a called function returns some result back to the calling function, it is said to return that result.
• The calling function may or may not pass parameters to the called function. If the called function accepts
arguments, the calling function will pass parameters, else not.
• Function declaration is a declaration statement that identifies a function with its name, a list of arguments
that it accepts and the type of data it returns.
• Function definition consists of a function header that identifies the function, followed by the body of the
function containing the executable code for that function.
Function Call
The function call statement invokes the function. When a function is invoked the program control jumps to
the called function to execute the statements that are a part of that function. Once the called function is
executed, the program control passes back to the calling function.
Function Parameters
A function can take parameters which are nothing but some values that are passed to it so that the function
can manipulate them to produce the desired result. These parameters are normal variables with a small
difference that the values of these variables are defined (initialized) when we call the function and are then
passed to the function.
Function name and the number and type of arguments in the function call must be same as that given in the
function definition.
If the data type of the argument passed does not matches with that expected in function then an error is
generated. Example: 6
A variable which is defined within a function is local to that function. A local variable can be accessed from
the point of its definition until the end of the function in which it is defined. It exists as long as the function is
executing. Function parameters behave like local variables in the function. Moreover, whenever we use the
assignment operator (=) inside a function, a new local variable is created.
Global variables are those variables which are defined in the main body of the program file. They are visible
throughout the program file. As a good programming habit, you must try to avoid the use of global variables
because they may get altered by mistake and then result in erroneous output.
Example:
10
Example:
11
12
In the required arguments, the arguments are passed to a function in correct positional order. Also, the number
of arguments in the function call should exactly match with the number of arguments specified in the
function definition
Examples:
13
Keyword Arguments
When we call a function with some values, the values are assigned to the arguments based on their position.
Python also allow functions to be called using keyword arguments in which the order (or position) of the
arguments can be changed. The values are not assigned to arguments according to their position but based
on their name (or keyword).
Keyword arguments are beneficial in two cases.
• First, if you skip arguments.
• Second, if in the function call you change the order of parameters.
Example:
14
Example:
16
Example:
17
Indexing: Individual characters in a string are accessed using the subscript ([ ]) operator. The expression in
brackets is called an index. The index specifies a member of an ordered set and in this case it specifies the
character we want to access from the given set of characters in the string.
The index of the first character is 0 and that of the last character is n-1 where n is the number of characters
in the string. If you try to exceed the bounds (below 0 or above n-1), then an error is raised.
2
Strings
Traversing a String: A string can be traversed by accessing character(s) from one index to another. For
example, the following program uses indexing to traverse a string from first character to the last.
Example:
Examples:
10
Examples:
11
Examples:
12
Comparing Strings
13
Examples:
14
15
Lists
List is a versatile data type available in Python. It is a sequence in which elements are written as a list of
comma-separated values (items) between square brackets. The key feature of a list is that it can have
elements that belong to different data types.The syntax of defining a list can be given as,
List_variable = [val1, val2,...]
Examples:
Similar to strings, lists can also be sliced and concatenated. To access values in lists, square brackets are used
to slice along with the index or indices to get value stored at that index. The syntax for the slice operation is
given as, seq = List[start:stop:step]
Example:
Example:
Cloning Lists
If you want to modify a list and also keep a copy of the original list, then you should create a separate copy
of the list (not just the reference).This process is called cloning.The slice operation is used to clone a list.
Example:
List Methods
14
Looping in Lists
Python's for and in constructs are extremely useful especially when working with lists. The for var in list
statement is an easy way to access each element in a list (or any other sequence). For example, in the
following code, the for loop is used to access each item in the list.
for i in list: Example:
print(i)
15
Examples:
16
Using an Iterator
You can create an iterator using the built-in iter() function. The iterator is used to loop over the elements
of the list. For this, the iterator fetches the value and then automatically points to the next element in the
list when it is used with the next() method.
Example:
17
Utility of Tuples
In real-world applications, tuples are extremely useful for representing records or structures as we call
in other programming languages.These structures store related information about a subject together.
The information belongs to different data types.
For example, a tuple that stores information about a student can have elements like roll_no, name, course,
total marks, avg, etc. Some built-in functions return a tuple. For example, the divmod() function returns two
values—quotient as well as the remainder after performing the divide operation.
Examples:
22
Example:
23
Examples:
24
25
Tuple Assignment
Tuple assignment is a very powerful feature in Python. It allows a tuple of variables on the left side of the
assignment operator to be assigned values from a tuple given on the right side of the assignment operator.
Each value is assigned to its respective variable. In case, an expression is specified on the right side of the
assignment operator, first that expression is evaluated and then assignment is done.
Example:
26
27
Examples:
28
Examples:
29
• Tuples are used to store values of different data types. Lists can however, store data of similar data types.
• Since tuples are immutable, iterating through tuples is faster than iterating over a list.This means that a
tuple performs better than a list.
• Tuples can be used as key for a dictionary but lists cannot be used as keys.
• Tuples are best suited for storing data that is write-protected.
• Tuples can be used in place of lists where the number of values is known and small.
• If you are passing a tuple as an argument to a function, then the potential for unexpected behavior due to
aliasing gets reduced.
• Multiple values from a function can be returned using a tuple.
• Tuples are used to format strings.
32
Sets is another data structure supported by Python. Basically, sets are same as lists but with a difference that
sets are lists with no duplicate entries.Technically, a set is a mutable and an unordered collection of items.This
means that we can easily add or remove items from it.
A set is created by placing all the elements inside curly brackets {}, separated by comma or by using the
built-in function set().The syntax of creating a set can be given as,
33
Set Operations
34
35
Set Operations
36
37
Dictionaries
Dictionary is a data structure in which we store values as a pair of key and value. Each key is separated from its
value by a colon (:), and consecutive items are separated by commas.The entire items in a dictionary are
enclosed in curly brackets({}).The syntax for defining a dictionary is
dictionary_name = {key_1: value_1, key_2: value_2, key_3: value_3}
If there are many keys and values in dictionaries, then we can also write just one key-value pair on a line
to make the code easier to read and understand.This is shown below.
dictionary_name = {key_1: value_1, key_2: value_2, key_3: value_3, ….}
Example:
38
Example:
39
Example:
40
41
Deleting Items
You can delete one or more items using the del keyword. To delete or remove all the items in just one
statement, use the clear() function. Finally, to remove an entire dictionary from the memory, we can gain
use the del statement as del Dict_name.The syntax to use the del statement can be given as,
del dictionary_variable[key]
Example:
42
43
Nested Dictionaries
Example:
44
45
46
47
Python also allows you to use string formatting feature with dictionaries. So you can use %s, %d, %f, etc. to
represent string, integer, floating point number, or any other data.
Example: Program that uses string formatting feature to print the key-value pairs stored in the dictionary
49
50
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 Given a number n, print all primes smaller than or equal to n. It is
also given that n is a small number.
For example, if n is 10, the output should be “2, 3, 5, 7”. If n is 20, the output should be “2, 3, 5, 7,
11, 13, 17, 19”
def prime_eratosthenes(n):
prime_list = []
for i in range(2, n+1):
if i not in prime_list:
print (i)
for j in range(i*i, n+1, i):
prime_list.append(j)
print(prime_eratosthenes(100))';
What is a file?
File is a named location on disk to store related information. It is used to permanently store data in a
non-volatile memory (e.g. hard disk).
Since, random access memory (RAM) is volatile which loses its data when computer is turned off,
we use files for future use of the data.
When we want to read from or write to a file we need to open it first. When we are done, it needs to
be closed, so that resources that are tied with the file are freed.
The default is reading in text mode. In this mode, we get strings when reading from the file.
On the other hand, binary mode returns bytes and this is the mode to be used when dealing with
non-text files like image or exe files.
Mode Description
'w' Open a file for writing. Creates a new file if it does not exist or truncates the file if it exists.
'x' Open a file for exclusive creation. If the file already exists, the operation fails.
'a' Open for appending at the end of the file without truncating it. Creates a new file if it does not exist.
Unlike other languages, the character 'a' does not imply the number 97 until it is encoded
using ASCII (or other equivalent encodings).
83 | P a g e Python Programming (KNC-402)
Moreover, the default encoding is platform dependent. In windows, it is 'cp1252' but 'utf-8' in
Linux.
So, we must not also rely on the default encoding or else our code will behave differently in different
platforms.
Hence, when working with files in text mode, it is highly recommended to specify the encoding type.
When we are done with operations to the file, we need to properly close the file.
Closing a file will free up the resources that were tied with the file and is done using
Python close() method.
Python has a garbage collector to clean up unreferenced objects but, we must not rely on it to close
the file.
1. f = open("test.txt",encoding = 'utf-8')
2. # perform file operations
3. f.close()
This method is not entirely safe. If an exception occurs when we are performing some operation with
the file, the code exits without closing the file.
A safer way is to use a try...finally block.
1. try:
2. f = open("test.txt",encoding = 'utf-8')
3. # perform file operations
4. finally:
5. f.close()
This way, we are guaranteed that the file is properly closed even if an exception is raised, causing
program flow to stop.
The best way to do this is using the with statement. This ensures that the file is closed when the
block inside with is exited.
In order to write into a file in Python, we need to open it in write 'w', append 'a' or exclusive
creation 'x' mode.
We need to be careful with the 'w' mode as it will overwrite into the file if it already exists. All
previous data are erased.
Writing a string or sequence of bytes (for binary files) is done using write() method. This method
returns the number of characters written to the file.
1. with open("test.txt",'w',encoding = 'utf-8') as f:
2. f.write("my first file\n")
3. f.write("This file\n\n")
4. f.write("contains three lines\n")
This program will create a new file named 'test.txt' if it does not exist. If it does exist, it is
overwritten.
There are various methods available for this purpose. We can use the read(size) method to read
in size number of data. If size parameter is not specified, it reads and returns up to the end of the
file.
1. >>> f = open("test.txt",'r',encoding = 'utf-8')
2. >>> f.read(4) # read the first 4 data
3. 'This'
4.
5. >>> f.read(4) # read the next 4 data
6. ' is '
7.
8. >>> f.read() # read in the rest till end of file
9. 'my first file\nThis file\ncontains three lines\n'
10.
11. >>> f.read() # further reading returns empty sting
12. ''
We can see that, the read() method returns newline as '\n'. Once the end of file is reached, we
get empty string on further reading.
We can change our current file cursor (position) using the seek() method. Similarly,
the tell() method returns our current position (in number of bytes).
We can read a file line-by-line using a for loop. This is both efficient and fast.
1. >>> f.readline()
2. 'This is my first file\n'
3.
4. >>> f.readline()
5. 'This file\n'
6.
7. >>> f.readline()
8. 'contains three lines\n'
9.
10. >>> f.readline()
11. ''
Lastly, the readlines() method returns a list of remaining lines of the entire file. All these reading
method return empty values when end of file (EOF) is reached.
1. >>> f.readlines()
2. ['This is my first file\n', 'This file\n', 'contains three lines\n']
There are various methods available with the file object. Some of them have been used in above
examples.
Here is the complete list of methods in text mode with a brief description.
86 | P a g e Python Programming (KNC-402)
Method Description
close() Close an open file. It has no effect if the file is already closed.
Separate the underlying binary buffer from the TextIOBase and return
detach() it.
Read atmost n characters form the file. Reads till end of file if it is
read(n) negative or None.
Read and return one line from the file. Reads in at most n bytes if
readline(n=-1) specified.
Resize the file stream to size bytes. If size is not specified, resize to
truncate(size=None) current location.
write(s) Write string s to the file and return the number of characters written.
other hand, are caused by events that are beyond the control of the program.
© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.
Logic error specifies all those type of errors in which the program executes but gives incorrect results. Logical
error may occur due to wrong algorithm or logic to solve a particular program. In some cases, logic errors
may lead to divide by zero or accessing an item in a list where the index of the item is outside the bounds of
the list. In this case, the logic error leads to a run-time error that causes the program to terminate abruptly.
These types of run-time errors are known as exceptions. 3
Handling Exceptions
We can handle exceptions in our program by using try block and except block. A critical operation which can
raise exception is placed inside the try block and the code that handles exception is written in except block. The
syntax for try–except block can be given as,
Example:
10
Raising Exceptions
You can deliberately raise an exception using the raise keyword.The general syntax for the raise statement is,
raise [Exception [, args [, traceback]]]
Here, Exception is the name of exception to be raised (example, TypeError). args is optional and specifies a
value for the exception argument. If args is not specified, then the exception argument is None.The final
argument, traceback, is also optional and if present, is the traceback object used for the exception.
Example:
11
Example:
12
Example:
13
14
16
Re-raising Exception
Python allows programmers to re-raise an exception. For example, an exception thrown from the try block
can be handled as well as re-raised in the except block using the keyword raise.The code given below
illustrates this concept.
Example: Program to re-raise the exception
17
19
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
Importing modules
#!/usr/bin/python
Python's from statement lets you import specific attributes from a module into the
current namespace. The from...import has the following syntax −
from modname import name1[, name2[, ... nameN]]
For example, to import the function fibonacci from the module fib, use the following
statement −
from fib import fibonacci
This statement does not import the entire module fib into the current namespace; it
just introduces the item fibonacci from the module fib into the global symbol table of
the importing module.
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.
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.
Python is an “object-oriented programming language.” This means that almost all the
code is implemented using a special construct called classes. Programmers use classes
to keep related things together. This is done using the keyword “class,” which is a
grouping of object-oriented constructs.
What is a class?
A class is a code template for creating objects. Objects have member variables and
have behavior (methods) associated with them. In python a class is created by the
keyword class.
99 | P a g e Python Programming (KNC-402)
An object is created using the constructor of the class. This object will then be called
the instance of the class. In Python we create instances in the following manner
Instance = class(arguments)
The simplest class can be created using the class keyword. For example, let's create a
simple, empty class with no functionalities.
A class by itself is of no use unless there is some functionality associated with it.
Functionalities are defined by setting attributes, which act as containers for data and
functions related to those attributes. Those functions are called methods.
Attributes:
You can define the following class with the name Snake. This class will have an
attribute name.
You can assign the class to a variable. This is called object instantiation. You will then
be able to access the attributes that are present inside the class using the
dot . operator. For example, in the Snake example, you can access the
attribute name of the class Snake.
>>> # access the class attribute name inside the class Snake.
>>> print(snake.name)
python
Once there are attributes that “belong” to the class, you can define functions that will
access the class attribute. These functions are called methods. When you define
methods, you will need to always provide the first argument to the method with a self
keyword.
For example, you can define a class Snake, which has one attribute name and one
method change_name. The method change name will take in an
argument new_name along with the keyword self.
Now, you can instantiate this class Snake with a variable snake and then change the
name with the method change_name.
You can also provide the values for the attributes at runtime. This is done by defining
the attributes inside the init method. The following example illustrates this.
class Snake:
Special Methods
All the built-in data types implement a collection of special object methods. The names
of special methods are always preceded and followed by double underscores (__).
User-defined classes can define new objects that behave like the built-in types simply
by supplying an appropriate subset of the special methods described in this section. In
addition, built-in types such as lists and dictionaries can be specialized (via inheritance)
by redefining some of the special methods.
The methods in Table 3.9 create, initialize, destroy, and represent objects.
Method Description
The __new__() and __init__() methods are used to create and initialize new instances.
When an object is created by calling A(args), it is translated into the following steps:
x = A.__new__(A,args)
is isinstance(x,A): x.__init__(args)
f = open("foo")
The __str__() method is called by the built-in str() function and by the print statement.
It differs from __repr__() in that the string it returns can be more concise and
informative to the user. If this method is undefined, the __repr__() method is invoked.
The __cmp__(self,other) method is used by all the comparison operators. It returns a
negative number if self < other, zero if self == other, and positive if self > other. If this
method is undefined for an object, the object will be compared by object identity. In
addition, an object may define an alternative set of comparison functions for each of
the relational operators. These are known as rich comparisons and are described
shortly. The __nonzero__() method is used for truth-value testing and should
return 0 or 1 (or True or False). If undefined, the __len__() method is invoked to
determine truth.
Finally, the __hash__() method computes an integer hash key used in dictionary
operations (the hash value can also be returned using the built-in function hash()). The
value returned should be identical for two objects that compare as equal. Further-more,
mutable objects should not define this method; any changes to an object will alter the
hash value and make it impossible to locate an object on subsequent dictionary
lookups. An object should not define a __hash__() method without also
defining __cmp__().
Attribute Access
The methods in Table 3.10 read, write, and delete the attributes of an object using the
dot (.) operator and the del operator, respectively.
Method Description
__setattr__(self, name, value) Sets the attribute self.name = value. Overrides the
default mechanism.
class Foo(object):
def __init__(self):
self.x = 37
f = Foo()
a = f.x # Invokes __getattribute__(f,"x")
b = f.y # Invokes __getattribute__(f,"y") --> Not found
# Then invokes __getattr__(f,"y")
f.x = 42 # Invokes __setattr__(f,"x",42)
f.y = 93 # Invokes __setattr__(f,"y",93)
del f.y # Invokes __delattr__(f,"y")
Method Description
class SimpleProperty(object):
def __init__(self,fget,fset):
self.fget = fget
self.fset = fset
def __get__(self,instance,cls):
return self.fget(instance) # Calls instance.fget()
105 | P a g e Python Programming (KNC-402)
def __set__(self,instance,value)
return self.fset(instance,value) # Calls instance.fset(value)
class Circle(object):
def __init__(self,radius):
self.radius = radius
def getArea(self):
return math.pi*self.radius**2
def setArea(self):
self.radius = math.sqrt(area/math.pi)
area = SimpleProperty(getArea,setArea)
In this example, the class SimpleProperty defines a descriptor in which two functions,
fget and fset, are supplied by the user to get and set the value of an attribute (note
that a more advanced version of this is already provided using the property() function
described in Chapter 7). In the Circle class that follows, these functions are used to
create a descriptor attribute called area. In subsequent code, the area attribute is
accessed transparently.
c = Circle(10)
Underneath the covers, access to the attribute c.area is being translated into an
operation such as Circle.__dict__[‘area’].__get__(c,Circle).
It is important to emphasize that descriptors can only be created at the class level. It is
not legal to create descriptors on a per-instance basis by defining descriptor objects
inside __init__() and other methods.
Method Description
Here's an example:
a = [1,2,3,4,5,6]
len(a) # __len__(a)
x = a[2] # __getitem__(a,2)
a[1] = 7 # __setitem__(a,1,7)
x = a[1:5] # __getslice__(a,1,5)
For manipulating individual items, the __getitem__() method can return an item by key
value. The key can be any Python object, but is typically an integer for sequences.
The __setitem__() method assigns a value to an element. The __delitem__() method is
invoked whenever the del operation is applied to a single element.
The slicing methods support the slicing operator s[i:j]. The __getslice__() method
returns a slice, which is normally the same type of sequence as the original object. The
indices i and j must be integers, but their interpretation is up to the method. Missing
values for i and j are replaced with 0 and sys.maxint, respectively.
The __setslice__() method assigns values to a slice. Similarly, __delslice__() deletes all
the elements in a slice.
Finally, Python supports an extended slicing operation that's useful for working with
multidimensional data structures such as matrices and arrays. Syntactically, you specify
an extended slice as follows:
The general format for each dimension of an extended slice is i:j[:stride], where stride
is optional. As with ordinary slices, you can omit the starting or ending values for each
part of a slice. In addition, a special object known as the Ellipsis and written as ... is
available to denote any number of trailing or leading dimensions in an extended slice:
m[10:20, ...] = n
Python strings, tuples, and lists currently provide some support for extended slices,
which is described in Chapter 4. Special-purpose extensions to Python, especially those
with a scientific flavor, may provide new types and objects with advanced support for
extended slicing operations.
Iteration
If an object, obj, supports iteration, it must provide a method, obj.__iter__(), that
returns an iterator object. The iterator object iter, in turn, must implement a single
method, iter.next(), that returns the next object or raises StopIteration to signal the
end of iteration. Both of these methods are used by the implementation of
the for statement as well as other operations that implicitly perform iteration. For
example, the statement for x in s is carried out by performing steps equivalent to the
following:
_iter = s.__iter__()
while 1:
try:
x = _iter.next()
except StopIteration:
break
# Do statements in body of for loop
...
Mathematical Operations
Table 3.13 lists special methods that objects must implement to emulate numbers.
Mathematical operations are always evaluated from left to right; when an expression
such as x + y appears, the interpreter tries to invoke the method x.__add__(y). The
109 | P a g e Python Programming (KNC-402)
special methods beginning with r support operations with reversed operands. These are
invoked only if the left operand doesn’t implement the specified operation. For example,
if x in x + y doesn’t support the __add__() method, the interpreter tries to invoke the
method y.__radd__(x).
Method Result
__divmod__(self,other) divmod(self,other)
__rdivmod__(self,other) divmod(other,self)
__neg__(self) –self
__pos__(self) +self
__invert__(self) ~self
__int__(self) int(self)
__long__(self) long(self)
__float__(self) float(self)
__complex__(self) complex(self)
__oct__(self) oct(self)
__hex__(self) hex(self)
The methods __iadd__(), __isub__(), and so forth are used to support in-place
arithmetic operators such as a+=b and a-=b (also known as augmented assignment). A
distinction is made between these operators and the standard arithmetic methods
because the implementation of the in-place operators might be able to provide certain
customizations such as performance optimizations. For instance, if the self parameter is
not shared, it might be possible to modify its value in place without having to allocate a
newly created object for the result.
Although strings define a few arithmetic operations, the __coerce__() method is not
used in mixed-string operations involving standard and Unicode strings.
The interpreter supports only a limited number of mixed-type operations involving the
built-in types, in particular the following:
Comparison Operations
Table 3.14 lists special methods that objects can implement to provide individualized
versions of the relational operators (<, >, <=, >=, ==, !=). These are known as rich
comparisons. Each of these functions takes two arguments and is allowed to return any
kind of object, including a Boolean value, a list, or any other Python type. For instance,
a numerical package might use this to perform an element-wise comparison of two
matrices, returning a matrix with the results. If a comparison can’t be made, these
functions may also raise an exception.
Method Result
Callable Objects
Finally, an object can emulate a function by providing
the __call__(self [,*args [, **kwargs]]) method. If an object, x, provides this method,
it can be invoked like a function. That is, x(arg1, arg2, ...) invokes
x.__call__(self, arg1, arg2, ...).
Python Inheritance
Inheritance allows us to define a class that inherits all the methods and properties from
another class.
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.
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:
114 | P a g e Python Programming (KNC-402)
class Person:
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()
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):
pass
Note: Use the pass keyword when you do not want to add any other properties or
methods to the class.
Now the Student class has the same properties and methods as the Person class.
Example
Use the Student class to create an object, and then execute the printname method:
x = Student("Mike", "Olsen")
x.printname()
So far we have created a child class that inherits the properties and methods from its
parent.
Note: The __init__() function is called automatically every time the class is being used
to create a new object.
Example
class Student(Person):
def __init__(self, fname, lname):
#add properties etc.
When you add the __init__() function, the child class will no longer inherit the
parent's __init__() function.
To keep the inheritance of the parent's __init__() function, add a call to the
parent's __init__() function:
Example
class Student(Person):
def __init__(self, fname, lname):
Person.__init__(self, fname, lname)
Now we have successfully added the __init__() function, and kept the inheritance of the
parent class, and we are ready to add functionality in the __init__() function.
Python also has a super() function that will make the child class inherit all the methods
and properties from its parent:
By using the super() function, you do not have to use the name of the parent element,
it will automatically inherit the methods and properties from its parent.
Add Properties
Example
class Student(Person):
def __init__(self, fname, lname):
super().__init__(fname, lname)
self.graduationyear = 2019
In the example below, the year 2019 should be a variable, and passed into
the Student class when creating student objects. To do so, add another parameter in
the __init__() function:
Example
Add a year parameter, and pass the correct year when creating objects:
class Student(Person):
def __init__(self, fname, lname, year):
super().__init__(fname, lname)
self.graduationyear = year
Add Methods
Example
class Student(Person):
def __init__(self, fname, lname, year):
117 | P a g e Python Programming (KNC-402)
super().__init__(fname, lname)
self.graduationyear = year
def welcome(self):
print("Welcome", self.firstname, self.lastname, "to the class of",
self.graduationyear)
If you add a method in the child class with the same name as a function in the parent
class, the inheritance of the parent method will be overridden.
• attributes
• behavior
Parrot is an object,
The concept of OOP in Python focuses on creating reusable code. This concept is also
known as DRY (Don't Repeat Yourself).
Class
We can think of class as an sketch of a parrot with labels. It contains all the details
about the name, colors, size etc. Based on these descriptions, we can study about the
parrot. Here, parrot is an object.
class Parrot:
pass
Here, we use class keyword to define an empty class Parrot. From class, we construct
instances. An instance is a specific object created from a particular class.
Object
obj = Parrot()
Suppose we have details of parrot. Now, we are going to show how to build the class
and objects of parrot.
class Parrot:
# class attribute
species = "bird"
119 | P a g e Python Programming (KNC-402)
# instance attribute
self.name = name
self.age = age
print("Blu is a {}".format(blu.__class__.species))
Blu is a bird
Woo is also a bird
Blu is 10 years old
Woo is 15 years old
In the above program, we create a class with name Parrot. Then, we define attributes.
The attributes are a characteristic of an object.
Then, we create instances of the Parrot class. Here, blu and woo are references (value)
to our new objects.
Then, we access the class attribute using __class __.species. Class attributes are same
for all instances of a class. Similarly, we access the instance attributes
using blu.name and blu.age. However, instance attributes are different for every
instance of a class.
Methods
Methods are functions defined inside the body of a class. They are used to define the
behaviors of an object.
# instance attributes
self.name = name
self.age = age
# instance method
def dance(self):
print(blu.sing("'Happy'"))
print(blu.dance())
In the above program, we define two methods i.e sing() and dance(). These are called
instance method because they are called on an instance object i.e blu.
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).
# parent class
class Bird:
print("Bird is ready")
def whoisThis(self):
print("Bird")
def swim(self):
print("Swim faster")
# child class
class Penguin(Bird):
def __init__(self):
super().__init__()
print("Penguin is ready")
def whoisThis(self):
print("Penguin")
def run(self):
print("Run faster")
peggy = Penguin()
peggy.whoisThis()
peggy.swim()
peggy.run()
Bird is ready
Penguin is ready
Penguin
Swim faster
Run faster
In the above program, we created two classes i.e. Bird (parent class)
and Penguin (child class). The child class inherits the functions of parent class. We can
see this from swim() method. Again, the child class modified the behavior of parent
Additionally, we use super() function before __init__() method. This is because we want
to pull the content of __init__() method from the parent class into the child class.
Encapsulation
Using OOP in Python, we can restrict access to methods and variables. This prevent
data from direct modification which is called encapsulation. In Python, we denote
private attribute using underscore as prefix i.e single “ _ “ or double “ __“.
class Computer:
def __init__(self):
self.__maxprice = 900
def sell(self):
self.__maxprice = price
c = Computer()
c.sell()
c.__maxprice = 1000
c.sell()
c.setMaxPrice(1000)
c.sell()
Polymorphism
Polymorphism is an ability (in OOP) to use common interface for multiple form (data
types).
Suppose, we need to color a shape, there are multiple shape option (rectangle, square,
circle). However we could use same method to color any shape. This concept is called
Polymorphism.
class Parrot:
def fly(self):
def swim(self):
class Penguin:
def fly(self):
def swim(self):
# common interface
def flying_test(bird):
bird.fly()
#instantiate objects
blu = Parrot()
peggy = Penguin()
flying_test(peggy)
In the above program, we defined two classes Parrot and Penguin. Each of them have
common method fly() method. However, their functions are different. To allow
polymorphism, we created common interface i.e flying_test() function that can take any
object. Then, we passed the objects blu and peggy in the flying_test() function, it ran
effectively.
UNIT-5
Iterators in Python
Iterator in python is any python type that can be used with a ‘for in loop’. Python lists,
tuples, dicts and sets are all examples of inbuilt iterators. These types are iterators
because they implement following methods. In fact, any object that wants to be an
iterator must implement following methods.
1. __iter__ method that is called on initialization of an iterator. This should return
an object that has a next or __next__ (in Python 3) method.
2. next ( __next__ in Python 3) The iterator next method should return the next
value for the iterable. When an iterator is used with a ‘for in’ loop, the for loop
implicitly calls next() on the iterator object. This method should raise a
StopIteration to signal the end of the iteration.
# Constructor
def __init__(self, limit):
self.limit = limit
# Prints nothing
for i in Test(5):
print(i)
Output :
10
11
12
13
We know that in Python, a function can call other functions. It is even possible for
the function to call itself. These type of construct are termed as recursive
functions.
Factorial of a number is the product of all the integers from 1 to that number. For
example, the factorial of 6 (denoted as 6!) is 1*2*3*4*5*6 = 720.
def calc_factorial(x):
"""This is a recursive function
to find the factorial of an integer"""
if x == 1:
return 1
else:
return (x * calc_factorial(x-1))
num = 4
print("The factorial of", num, "is", calc_factorial(num))
When we call this function with a positive integer, it will recursively call itself by
decreasing the number.
Each function call multiples the number with the factorial of number 1 until the number
is equal to one.
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:
if n == 1:
return
# Driver code
n=4
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
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
The program takes a list and key as input and finds the index of the key in the list using
linear search.
Problem Solution
Here is the source code of a Python program to implement linear search. The program
output is shown below.
def linear_search(alist, key):
"""Return index of key in alist. Return -1 if key not present."""
for i in range(len(alist)):
if alist[i] == key:
return i
return -1
Program Explanation
Case 1:
Enter the list of numbers: 5 4 3 2 1 10 11 2
The number to search for: 1
1 was found at index 4.
Case 2:
Enter the list of numbers: 5 2 1 5 -3
130 | P a g e Python Programming (KNC-402)
The number to search for: 2
2 was found at index 1.
Case 3:
Enter the list of numbers: 3 5 6
The number to search for: 2
2 was not found.
Problem Description
The program takes a list and key as input and finds the index of the key in the list using
binary search.
Problem Solution
Here is the source code of a Python program to implement binary search without using
recursion. The program output is shown below.
def binary_search(alist, key):
"""Search key in alist[start... end - 1]."""
start = 0
end = len(alist)
while start < end:
mid = (start + end)//2
if alist[mid] > key:
end = mid
elif alist[mid] < key:
start = mid + 1
else:
return mid
return -1
Program Explanation
Case 1:
Enter the sorted list of numbers: 3 5 10 12 15 20
The number to search for: 12
12 was found at index 3.
Case 2:
Enter the sorted list of numbers: -3 0 1 5 6 7 8
The number to search for: 2
2 was not found.
Case 3:
Enter the sorted list of numbers: 5
The number to search for: 5
5 was found at index 0.
Here is the source code of a Python program to implement selection sort. The program
output is shown below.
def selection_sort(alist):
for i in range(0, len(alist) - 1):
smallest = i
for j in range(i + 1, len(alist)):
if alist[j] < alist[smallest]:
smallest = j
alist[i], alist[smallest] = alist[smallest], alist[i]
Program Explanation
Case 1:
Enter the list of numbers: 3 1 4 5 2 6
Sorted list: [1, 2, 3, 4, 5, 6]
Case 2:
Enter the list of numbers: 2 10 5 38 1 7
Sorted list: [1, 2, 5, 7, 10, 38]
Case 3:
Enter the list of numbers: 5 3 2 1 0
Sorted list: [0, 1, 2, 3, 5]
1. Create a function merge_sort that takes a list and two variables start and end as
arguments.
2. The function merge_sort will sort the list from indexes start to end – 1 inclusive.
3. If end – start is not greater than 1, then return.
4. Otherwise, set mid equal to the floor of (start + end)/2.
5. Call merge_sort with the same list and with start = start and end = mid as
arguments.
6. Call merge_sort with the same list and with start = mid and end = end as
arguments.
7. Call the function merge_list, passing the list and the variables start, mid and end as
arguments.
8. The function merge_list takes a list and three numbers, start, mid and end as
arguments and assuming the list is sorted from indexes start to mid – 1 and from mid
to end – 1, merges them to create a new sorted list from indexes start to end – 1.
Program/Source Code
Here is the source code of a Python program to implement merge sort. The program
output is shown below.
def merge_sort(alist, start, end):
'''Sorts the list from indexes start to end - 1 inclusive.'''
if end - start > 1:
mid = (start + end)//2
merge_sort(alist, start, mid)
merge_sort(alist, mid, end)
merge_list(alist, start, mid, end)
Program Explanation
Case 1:
Enter the list of numbers: 3 1 5 8 2 5 1 3
Sorted list: [1, 1, 2, 3, 3, 5, 5, 8]
Case 2:
Enter the list of numbers: 5 3 2 1 0
Sorted list: [0, 1, 2, 3, 5]
Case 3:
Enter the list of numbers: 1
Sorted list: [1]
sorted
sorted does pretty much the same thing what you expected.
# sorting alphabetically
In [0]: sorted(['foo', 'bar'])
Out[0]: ['bar', 'foo']