0% found this document useful (0 votes)
326 views148 pages

Python NSR Notes

This document provides notes on the Python programming language covering various topics: 1) Python statements, indentation, and comments. Statements are executed by the interpreter and indentation is used to define code blocks instead of braces. Comments start with #. 2) Python variables and data types. Variables are assigned values without declaring types. Important data types include numbers, lists, tuples, strings, sets, and dictionaries. 3) Details on each data type - integers and floats for numbers, lists and tuples for sequences, strings for text, sets for unique elements, and dictionaries for key-value pairs.

Uploaded by

Shrirang Patil
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
326 views148 pages

Python NSR Notes

This document provides notes on the Python programming language covering various topics: 1) Python statements, indentation, and comments. Statements are executed by the interpreter and indentation is used to define code blocks instead of braces. Comments start with #. 2) Python variables and data types. Variables are assigned values without declaring types. Important data types include numbers, lists, tuples, strings, sets, and dictionaries. 3) Details on each data type - integers and floats for numbers, lists and tuples for sequences, strings for text, sets for unique elements, and dictionaries for key-value pairs.

Uploaded by

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

Notes on Python Programming Language

Notes on Python Programming By Prof.N.S.Raote


Notes on Python Programming By Prof.N.S.Raote
Notes on Python Programming By Prof.N.S.Raote
Python Statement, Indentation and Comments

Python Statement
Instructions that a Python interpreter can execute are called statements. For
example, a = 1 is an assignment statement. if statement, for statement, while
statement etc. are other kinds of statements which will be discussed later.

Multi-line statement

In Python, end of a statement is marked by a newline character. But we can make a


statement extend over multiple lines with the line continuation character (\). For
example:

a=1+2+3+\
4+5+6+\
7+8+9

Notes on Python Programming By Prof.N.S.Raote


This is explicit line continuation. In Python, line continuation is implied inside
parentheses ( ), brackets [ ] and braces { }. For instance, we can implement the
above multi-line statement as

a = (1 + 2 + 3 +
4+5+6+
7 + 8 + 9)

Here, the surrounding parentheses ( ) do the line continuation implicitly. Same is


the case with [ ] and { }. For example:

colors = ['red',
'blue',
'green']

We could also put multiple statements in a single line using semicolons, as follows

a = 1; b = 2; c = 3

Python Indentation

Most of the programming languages like C, C++, Java use braces { } to define a
block of code. Python uses indentation.

A code block (body of a function, loop etc.) starts with indentation and ends with
the first unindented line. The amount of indentation is up to you, but it must be
consistent throughout that block.

Generally four whitespaces are used for indentation and is preferred over tabs.
Here is an example.

for i in range(1,11):

print(i)

if i == 5:

break

Notes on Python Programming By Prof.N.S.Raote


The enforcement of indentation in Python makes the code look neat and clean.
This results into Python programs that look similar and consistent.

Indentation can be ignored in line continuation. But it's a good idea to always
indent. It makes the code more readable. For example:

if True:
print('Hello')
a=5

and

if True: print('Hello'); a = 5

both are valid and do the same thing. But the former style is clearer.

Incorrect indentation will result into IndentationError.

Python Comments

Comments are very important while writing a program. It describes what's going
on inside a program so that a person looking at the source code does not have a
hard time figuring it out. You might forget the key details of the program you just
wrote in a month's time. So taking time to explain these concepts in form of
comments is always fruitful.

In Python, we use the hash (#) symbol to start writing a comment.

It extends up to the newline character. Comments are for programmers for better
understanding of a program. Python Interpreter ignores comment.

#This is a comment
#print out Hello
print('Hello')

Multi-line comments

If we have comments that extend multiple lines, one way of doing it is to use hash
(#) in the beginning of each line. For example:

#This is a long comment


#and it extends
Notes on Python Programming By Prof.N.S.Raote
#to multiple lines

Another way of doing this is to use triple quotes, either ''' or """.

These triple quotes are generally used for multi-line strings. But they can be used
as multi-line comment as well. Unless they are not docstrings, they do not generate
any extra code.

"""This is also a
perfect example of
multi-line comments"""

Docstring in Python

Docstring is short for documentation string.

It is a string that occurs as the first statement in a module, function, class, or


method definition. We must write what a function/class does in the docstring.

Triple quotes are used while writing docstrings. For example:

def double(num):

"""Function to double the value"""

return 2*num

Docstring is available to us as the attribute __doc__ of the function. Issue the


following code in shell once you run the above program.

>>> print(double.__doc__)
Function to double the value

Notes on Python Programming By Prof.N.S.Raote


Python Variables and Data Types

Python Variables

A variable is a location in memory used to store some data (value).

They are given unique names to differentiate between different memory locations.
The rules for writing a variable name is same as the rules for writing identifiers in
Python.

We don't need to declare a variable before using it. In Python, we simply assign a
value to a variable and it will exist. We don't even have to declare the type of the
variable. This is handled internally according to the type of value we assign to the
variable.

Variable assignment

We use the assignment operator (=) to assign values to a variable. Any type of
value can be assigned to any valid variable.

a=5
b = 3.2
c = "Hello"

Here, we have three assignment statements. 5 is an integer assigned to the variable


a.

Similarly, 3.2 is a floating point number and "Hello" is a string (sequence of


characters) assigned to the variables b and c respectively.

Multiple assignments

In Python, multiple assignments can be made in a single statement as follows:

a, b, c = 5, 3.2, "Hello"

If we want to assign the same value to multiple variables at once, we can do this as

x = y = z = "same"

Notes on Python Programming By Prof.N.S.Raote


This assigns the "same" string to all the three variables.

Data types in Python

Every value in Python has a datatype. Since everything is an object in Python


programming, data types are actually classes and variables are instance (object) of
these classes.

There are various data types in Python. Some of the important types are listed
below.

Python Numbers

Integers, floating point numbers and complex numbers falls under Python numbers
category. They are defined as int, float and complex class in Python.

We can use the type() function to know which class a variable or a value belongs
to and the isinstance() function to check if an object belongs to a particular class.

a=5

print(a, "is of type", type(a))

a = 2.0

print(a, "is of type", type(a))

a = 1+2j

print(a, "is complex number?", isinstance(1+2j,complex))

Integers can be of any length, it is only limited by the memory available.

A floating point number is accurate up to 15 decimal places. Integer and floating


points are separated by decimal points. 1 is integer, 1.0 is floating point number.

Complex numbers are written in the form, x + yj, where x is the real part and y is
the imaginary part. Here are some examples.

>>> a = 1234567890123456789

Notes on Python Programming By Prof.N.S.Raote


>>> a
1234567890123456789
>>> b = 0.1234567890123456789
>>> b
0.12345678901234568
>>> c = 1+2j
>>> c
(1+2j)

Notice that the float variable b got truncated.

Python List

List is an ordered sequence of items. It is one of the most used datatype in Python
and is very flexible. All the items in a list do not need to be of the same type.

Declaring a list is pretty straight forward. Items separated by commas are enclosed
within brackets [ ].

>>> a = [1, 2.2, 'python']

We can use the slicing operator [ ] to extract an item or a range of items from a list.
Index starts form 0 in Python.

a = [5,10,15,20,25,30,35,40]

# a[2] = 15

print("a[2] = ", a[2])

# a[0:3] = [5, 10, 15]

print("a[0:3] = ", a[0:3])

# a[5:] = [30, 35, 40]

print("a[5:] = ", a[5:])

Lists are mutable, meaning, value of elements of a list can be altered.

>>> a = [1,2,3]
>>> a[2]=4

Notes on Python Programming By Prof.N.S.Raote


>>> a
[1, 2, 4]

Python Tuple

Tuple is an ordered sequence of items same as list.The only difference is that


tuples are immutable. Tuples once created cannot be modified.

Tuples are used to write-protect data and are usually faster than list as it cannot
change dynamically.

It is defined within parentheses () where items are separated by commas.

>>> t = (5,'program', 1+3j)

We can use the slicing operator [] to extract items but we cannot change its value.

t = (5,'program', 1+3j)

# t[1] = 'program'

print("t[1] = ", t[1])

# t[0:3] = (5, 'program', (1+3j))

print("t[0:3] = ", t[0:3])

# Generates error

# Tuples are immutable

t[0] = 10

Python Strings

String is sequence of Unicode characters. We can use single quotes or double


quotes to represent strings. Multi-line strings can be denoted using triple quotes, '''
or """.

>>> s = "This is a string"


>>> s = '''a multiline
Notes on Python Programming By Prof.N.S.Raote
Like list and tuple, slicing operator [ ] can be used with string. Strings are
immutable.

s = 'Hello world!'

# s[4] = 'o'

print("s[4] = ", s[4])

# s[6:11] = 'world'

print("s[6:11] = ", s[6:11])

# Generates error

# Strings are immutable in Python

s[5] ='d'

Python Set

Set is an unordered collection of unique items. Set is defined by values separated


by comma inside braces { }. Items in a set are not ordered.

a = {5,2,3,1,4}

# printing set variable

print("a = ", a)

# data type of variable a

print(type(a))

We can perform set operations like union, intersection on two sets. Set have unique
values. They eliminate duplicates.

>>> a = {1,2,2,3,3,3}
>>> a
{1, 2, 3}

Notes on Python Programming By Prof.N.S.Raote


Since, set are unordered collection, indexing has no meaning. Hence the slicing
operator [] does not work.

>>> a = {1,2,3}
>>> a[1]
Traceback (most recent call last):
File "<string>", line 301, in runcode
File "<interactive input>", line 1, in <module>
TypeError: 'set' object does not support indexing

Python Dictionary

Dictionary is an unordered collection of key-value pairs.

It is generally used when we have a huge amount of data. Dictionaries are


optimized for retrieving data. We must know the key to retrieve the value.

In Python, dictionaries are defined within braces {} with each item being a pair in
the form key:value. Key and value can be of any type.

>>> d = {1:'value','key':2}
>>> type(d)
<class 'dict'>

We use key to retrieve the respective value. But not the other way around.

d = {1:'value','key':2}

print(type(d))

print("d[1] = ", d[1]);

print("d['key'] = ", d['key']);

# Generates error

Notes on Python Programming By Prof.N.S.Raote


print("d[2] = ", d[2]);

Conversion between data types

We can convert between different data types by using different type conversion
functions like int(), float(), str() etc.

>>> float(5)
5.0

Conversion from float to int will truncate the value (make it closer to zero).

>>> int(10.6)
10
>>> int(-10.6)
-10

Conversion to and from string must contain compatible values.

>>> float('2.5')
2.5
>>> str(25)
'25'
>>> int('1p')
Traceback (most recent call last):
File "<string>", line 301, in runcode
File "<interactive input>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '1p'

We can even convert one sequence to another.

>>> set([1,2,3])
{1, 2, 3}
>>> tuple({5,6,7})
(5, 6, 7)
>>> list('hello')
['h', 'e', 'l', 'l', 'o']

To convert to dictionary, each element must be a pair

>>> dict([[1,2],[3,4]])

Notes on Python Programming By Prof.N.S.Raote


{1: 2, 3: 4}
>>> dict([(3,26),(4,44)])
{3: 26, 4: 44}

Python Input, Output and Import

Python provides numerous built-in functions that are readily available to us at the
Python prompt.

Some of the functions like input() and print() are widely used for standard input
and output operations respectively. Let us see the output section first.

Python Output Using print() function

We use the print() function to output data to the standard output device (screen).

We can also output data to a file, but this will be discussed later. An example use is
given below.

print('This sentence is output to the screen')

# Output: This sentence is output to the screen

a=5

print('The value of a is', a)

# Output: The value of a is 5

In the second print() statement, we can notice that a space was added between the
string and the value of variable a.This is by default, but we can change it.

The actual syntax of the print() function is

print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)

Here, objects is the value(s) to be printed.

Notes on Python Programming By Prof.N.S.Raote


The sep separator is used between the values. It defaults into a space character.

After all values are printed, end is printed. It defaults into a new line.

The file is the object where the values are printed and its default value is sys.stdout
(screen). Here are an example to illustrate this.

print(1,2,3,4)

# Output: 1 2 3 4

print(1,2,3,4,sep='*')

# Output: 1*2*3*4

print(1,2,3,4,sep='#',end='&')

# Output: 1#2#3#4&

Output formatting

Sometimes we would like to format our output to make it look attractive. This can
be done by using the str.format() method. This method is visible to any string
object.

>>> x = 5; y = 10
>>> print('The value of x is {} and y is {}'.format(x,y))
The value of x is 5 and y is 10

Here the curly braces {} are used as placeholders. We can specify the order in
which it is printed by using numbers (tuple index).

print('I love {0} and {1}'.format('bread','butter'))

# Output: I love bread and butter

Notes on Python Programming By Prof.N.S.Raote


print('I love {1} and {0}'.format('bread','butter'))

# Output: I love butter and bread

We can even use keyword arguments to format the string.

>>> print('Hello {name}, {greeting}'.format(greeting = 'Goodmorning', name =


'John'))
Hello John, Goodmorning

We can even format strings like the old sprintf() style used in C programming
language. We use the % operator to accomplish this.

>>> x = 12.3456789
>>> print('The value of x is %3.2f' %x)
The value of x is 12.35
>>> print('The value of x is %3.4f' %x)
The value of x is 12.3457

Python Input

Up till now, our programs were static. The value of variables were defined or hard
coded into the source code.

To allow flexibility we might want to take the input from the user. In Python, we
have the input() function to allow this. The syntax for input() is

input([prompt])

where prompt is the string we wish to display on the screen. It is optional.

>>> num = input('Enter a number: ')


Enter a number: 10
>>> num
'10'

Here, we can see that the entered value 10 is a string, not a number. To convert this
into a number we can use int() or float() functions.

>>> int('10')
Notes on Python Programming By Prof.N.S.Raote
10
>>> float('10')
10.0

This same operation can be performed using the eval() function. But it takes it
further. It can evaluate even expressions, provided the input is a string

>>> int('2+3')
Traceback (most recent call last):
File "<string>", line 301, in runcode
File "<interactive input>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '2+3'
>>> eval('2+3')
5

Python Import

When our program grows bigger, it is a good idea to break it into different
modules.

A module is a file containing Python definitions and statements. Python modules


have a filename and end with the extension .py.

Definitions inside a module can be imported to another module or the interactive


interpreter in Python. We use the import keyword to do this.

For example, we can import the math module by typing in import math.

import math

print(math.pi)

Now all the definitions inside math module are available in our scope. We can also
import some specific attributes and functions only, using the from keyword. For
example:

>>> from math import pi


>>> pi
3.141592653589793

Notes on Python Programming By Prof.N.S.Raote


While importing a module, Python looks at several places defined in sys.path. It is
a list of directory locations.

>>> import sys


>>> sys.path
['',
'C:\\Python33\\Lib\\idlelib',
'C:\\Windows\\system32\\python33.zip',
'C:\\Python33\\DLLs',
'C:\\Python33\\lib',
'C:\\Python33',
'C:\\Python33\\lib\\site-packages']

Python Operators

Operators are special symbols in Python that carry out arithmetic or logical
computation. The value that the operator operates on is called the operand.

For example:

>>> 2+3
5

Here, + is the operator that performs addition. 2 and 3 are the operands and 5 is the
output of the operation.

Notes on Python Programming By Prof.N.S.Raote


Python has a number of operators which are classified below.

Type of operators in Python


Arithmetic operators
Comparison (Relational) operators
Logical (Boolean) operators
Bitwise operators
Assignment operators
Special operators

Arithmetic operators

Arithmetic operators are used to perform mathematical operations like addition,


subtraction, multiplication etc.

Arithmetic operators in Python


Operator Meaning Example
x+y
+ Add two operands or unary plus
+2
x-y
- Subtract right operand from the left or unary minus
-2
* Multiply two operands x*y
Divide left operand by the right one (always results
/ x/y
into float)
Modulus - remainder of the division of left operand x % y (remainder
%
by the right of x/y)
Floor division - division that results into whole
// x // y
number adjusted to the left in the number line
x**y (x to the
** Exponent - left operand raised to the power of right
power y)

x = 15

y=4

Notes on Python Programming By Prof.N.S.Raote


# Output: x + y = 19

print('x + y =',x+y)

# Output: x - y = 11

print('x - y =',x-y)

# Output: x * y = 60

print('x * y =',x*y)

# Output: x / y = 3.75

print('x / y =',x/y)

# Output: x // y = 3

print('x // y =',x//y)

# Output: x ** y = 50625

print('x ** y =',x**y)

When you run the program, the output will be:

x + y = 19
x - y = 11

Notes on Python Programming By Prof.N.S.Raote


x * y = 60
x / y = 3.75
x // y = 3
x ** y = 50625

Comparison operators

Comparison operators are used to compare values. It either returns True or False
according to the condition.

Comparision operators in Python


Operator Meaning Example
> Greater that - True if left operand is greater than the right x>y
< Less that - True if left operand is less than the right x<y
== Equal to - True if both operands are equal x == y
!= Not equal to - True if operands are not equal x != y
Greater than or equal to - True if left operand is greater than
>= x >= y
or equal to the right
Less than or equal to - True if left operand is less than or
<= x <= y
equal to the right

Example #2: Comparison operators in Python

x = 10

y = 12

# Output: x > y is False

print('x > y is',x>y)

# Output: x < y is True

print('x < y is',x<y)

Notes on Python Programming By Prof.N.S.Raote


# Output: x == y is False

print('x == y is',x==y)

# Output: x != y is True

print('x != y is',x!=y)

# Output: x >= y is False

print('x >= y is',x>=y)

# Output: x <= y is True

print('x <= y is',x<=y)

Logical operators

Logical operators are the and, or, not operators.

Logical operators in Python


Operator Meaning Example
and True if both the operands are true x and y
or True if either of the operands is true x or y
not True if operand is false (complements the operand) not x

Example #3: Logical Operators in Python

x = True

y = False
Notes on Python Programming By Prof.N.S.Raote
# Output: x and y is False

print('x and y is',x and y)

# Output: x or y is True

print('x or y is',x or y)

# Output: not x is False

print('not x is',not x)

Bitwise operators

Bitwise operators act on operands as if they were string of binary digits. It operates
bit by bit, hence the name.

For example, 2 is 10 in binary and 7 is 111.

In the table below: Let x = 10 (0000 1010 in binary) and y = 4 (0000 0100 in
binary)

Bitwise operators in Python


Operator Meaning Example
& Bitwise AND x& y = 0 (0000 0000)
| Bitwise OR x | y = 14 (0000 1110)
~ Bitwise NOT ~x = -11 (1111 0101)
^ Bitwise XOR x ^ y = 14 (0000 1110)
>> Bitwise right shift x>> 2 = 2 (0000 0010)
<< Bitwise left shift x<< 2 = 40 (0010 1000)

Assignment operators

Notes on Python Programming By Prof.N.S.Raote


Assignment operators are used in Python to assign values to variables.

a = 5 is a simple assignment operator that assigns the value 5 on the right to the
variable a on the left.

There are various compound operators in Python like a += 5 that adds to the
variable and later assigns the same. It is equivalent to a = a + 5.

Assignment operators in Python


Operator Example Equivatent to
= x=5 x=5
+= x += 5 x = x + 5
-= x -= 5 x=x-5
*= x *= 5 x=x*5
/= x /= 5 x=x/5
%= x %= 5 x = x % 5
//= x //= 5 x = x // 5
**= x **= 5 x = x ** 5
&= x &= 5 x = x & 5
|= x |= 5 x=x|5
^= x ^= 5 x=x^5
>>= x >>= 5 x = x >> 5
<<= x <<= 5 x = x << 5

Special operators

Python language offers some special type of operators like the identity operator or
the membership operator. They are described below with examples.

Identity operators

is and is not are the identity operators in Python. They are used to check if two
values (or variables) are located on the same part of the memory. Two variables
that are equal does not imply that they are identical.

Notes on Python Programming By Prof.N.S.Raote


Identity operators in Python
Operator Meaning Example
is True if the operands are identical (refer to the same object) x is True
True if the operands are not identical (do not refer to the x is not
is not
same object) True

Example #4: Identity operators in Python

x1 = 5

y1 = 5

x2 = 'Hello'

y2 = 'Hello'

x3 = [1,2,3]

y3 = [1,2,3]

# Output: False

print(x1 is not y1)

# Output: True

print(x2 is y2)

# Output: False

print(x3 is y3)

Here, we see that x1 and y1 are integers of same values, so they are equal as well
as identical. Same is the case with x2 and y2 (strings).

Notes on Python Programming By Prof.N.S.Raote


But x3 and y3 are list. They are equal but not identical. Since list are mutable (can
be changed), interpreter locates them separately in memory although they are
equal.

Membership operators

in and not in are the membership operators in Python. They are used to test
whether a value or variable is found in a sequence (string, list, tuple, set and
dictionary).

In a dictionary we can only test for presence of key, not the value.

Operator Meaning Example


in True if value/variable is found in the sequence 5 in x
not in True if value/variable is not found in the sequence 5 not in x

Example #5: Membership operators in Python

x = 'Hello world'

y = {1:'a',2:'b'}

# Output: True

print('H' in x)

# Output: True

print('hello' not in x)

# Output: True

print(1 in y)

# Output: False

print('a' in y)

Here, 'H' is in x but 'hello' is not present in x (remember, Python is case sensitive).
Similary, 1 is key and 'a' is the value in dictionary y. Hence, 'a' in y returns False.

Notes on Python Programming By Prof.N.S.Raote


Flow Control

Python if...else Statement

Decision making is required when we want to execute a code only if a certain


condition is satisfied.

The if…elif…else statement is used in Python for decision making.

Python if Statement Syntax

if test expression:
statement(s)

Here, the program evaluates the test expression and will execute statement(s) only
if the text expression is True.

If the text expression is False, the statement(s) is not executed.

In Python, the body of the if statement is indicated by the indentation. Body starts
with an indentation and the first unindented line marks the end.

Python interprets non-zero values as True. None and 0 are interpreted as False.

Python if Statement Flowchart

Example: Python if Statement

If the number is positive, we print an appropriate message

num = 3

if num > 0:

print(num, "is a positive number.")

print("This is always printed.")

Notes on Python Programming By Prof.N.S.Raote


num = -1

if num > 0:

print(num, "is a positive number.")

print("This is also always printed.")

When you run the program, the output will be:

3 is a positive number
This is always printed
This is also always printed.

In the above example, num > 0 is the test expression.

The body of if is executed only if this evaluates to True.

When variable num is equal to 3, test expression is true and body inside body of if
is executed.

If variable num is equal to -1, test expression is false and body inside body of if is
skipped.

The print() statement falls outside of the if block (unindented). Hence, it is


executed regardless of the test expression.

Python if...else Statement

Syntax of if...else

if test expression:
Body of if
else:
Body of else

The if..else statement evaluates test expression and will execute body of if only
when test condition is True.

If the condition is False, body of else is executed. Indentation is used to separate


the blocks.

Notes on Python Programming By Prof.N.S.Raote


Example of if...else

# Program checks if the number is positive or negative

# And displays an appropriate message

num = 3

# Try these two variations as well.

# num = -5

# num = 0

if num >= 0:

print("Positive or Zero")

else:

print("Negative number")

In the above example, when num is equal to 3, the test expression is true and body
of if is executed and body of else is skipped.

If num is equal to -5, the test expression is false and body of else is executed and
body of if is skipped.

If num is equal to 0, the test expression is true and body of if is executed and body
of else is skipped.

Python if...elif...else

Syntax of if...elif...else

if test expression:
Body of if
elif test expression:
Body of elif
else:

Notes on Python Programming By Prof.N.S.Raote


Body of else

The elif is short for else if. It allows us to check for multiple expressions.

If the condition for if is False, it checks the condition of the next elif block and so
on.

If all the conditions are False, body of else is executed.

Only one block among the several if...elif...else blocks is executed according to the
condition.

The if block can have only one else block. But it can have multiple elif blocks.

# In this program,

# we check if the number is positive or

# negative or zero and

# display an appropriate message

num = 3.4

# Try these two variations as well:

# num = 0

# num = -4.5

if num > 0:

print("Positive number")

elif num == 0:

Notes on Python Programming By Prof.N.S.Raote


print("Zero")

else:

print("Negative number")

When variable num is positive, Positive number is printed.

If num is equal to 0, Zero is printed.

If num is negative, Negative number is printed

Python Nested if statements

We can have a if...elif...else statement inside another if...elif...else statement. This


is called nesting in computer programming.

Any number of these statements can be nested inside one another. Indentation is
the only way to figure out the level of nesting. This can get confusing, so must be
avoided if we can.

Python Nested if Example

# In this program, we input a number


# check if the number is positive or
# negative or zero and display
# an appropriate message
# This time we use nested if

num = float(input("Enter a number: "))


if num >= 0:
if num == 0:
print("Zero")
else:
print("Positive number")
else:
print("Negative number")

Output 1

Notes on Python Programming By Prof.N.S.Raote


Enter a number: 5
Positive number

Output 2

Enter a number: -1
Negative number

Output 3

Enter a number: 0
Zero

Python for Loop

he for loop in Python is used to iterate over a sequence (list, tuple, string) or other
iterable objects. Iterating over a sequence is called traversal.

Syntax of for Loop

for val in sequence:


Body of for

Here, val is the variable that takes the value of the item inside the sequence on each
iteration.

Loop continues until we reach the last item in the sequence. The body of for loop is
separated from the rest of the code using indentation.

Notes on Python Programming By Prof.N.S.Raote


Example: Python for Loop

# Program to find the sum of all numbers stored in a list

# List of numbers

numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11]

# variable to store the sum

sum = 0

# iterate over the list

for val in numbers:

sum = sum+val

# Output: The sum is 48

print("The sum is", sum)


Notes on Python Programming By Prof.N.S.Raote
hen you run the program, the output will be:

The sum is 48

The range() function

We can generate a sequence of numbers using range() function. range(10) will


generate numbers from 0 to 9 (10 numbers).

We can also define the start, stop and step size as range(start,stop,step size). step
size defaults to 1 if not provided.

This function does not store all the values in memory, it would be inefficient. So it
remembers the start, stop, step size and generates the next number on the go.

To force this function to output all the items, we can use the function list().

The following example will clarify this.

# Output: range(0, 10)


print(range(10))

# Output: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(list(range(10)))

# Output: [2, 3, 4, 5, 6, 7]
print(list(range(2, 8)))

# Output: [2, 5, 8, 11, 14, 17]


print(list(range(2, 20, 3)))

We can use the range() function in for loops to iterate through a sequence of
numbers. It can be combined with the len() function to iterate though a sequence
using indexing. Here is an example.

# Program to iterate through a list using indexing

genre = ['pop', 'rock', 'jazz']

Notes on Python Programming By Prof.N.S.Raote


# iterate over the list using index

for i in range(len(genre)):

print("I like", genre[i])

When you run the program, the output will be:

I like pop
I like rock
I like jazz

for loop with else

A for loop can have an optional else block as well. The else part is executed if the
items in the sequence used in for loop exhausts.

break statement can be used to stop a for loop. In such case, the else part is
ignored.

Hence, a for loop's else part runs if no break occurs.

Here is an example to illustrate this.

digits = [0, 1, 5]

for i in digits:

print(i)

else:

print("No items left.")

When you run the program, the output will be:

0
1
5
No items left.

Notes on Python Programming By Prof.N.S.Raote


Here, the for loop prints items of the list until the loop exhausts. When the for loop
exhausts, it executes the block of code in the else and prints

No items left.

Python while Loop

The while loop in Python is used to iterate over a block of code as long as the test
expression (condition) is true.

We generally use this loop when we don't know beforehand, the number of times
to iterate.

Syntax of while Loop in Python

while test_expression:
Body of while

In while loop, test expression is checked first. The body of the loop is entered only
if the test_expression evaluates to True. After one iteration, the test expression is
checked again. This process continues until the test_expression evaluates to False.

In Python, the body of the while loop is determined through indentation.

Body starts with indentation and the first unindented line marks the end.

Python interprets any non-zero value as True. None and 0 are interpreted as False.

Notes on Python Programming By Prof.N.S.Raote


Flowchart of while Loop

Example: Python while Loop

# Program to add natural

# numbers upto

# sum = 1+2+3+...+n

# To take input from the user,

# n = int(input("Enter n: "))

n = 10

# initialize sum and counter

sum = 0

i=1

Notes on Python Programming By Prof.N.S.Raote


while i <= n:

sum = sum + i

i = i+1 # update counter

# print the sum

print("The sum is", sum)

When you run the program, the output will be:

Enter n: 10
The sum is 55

In the above program, the test expression will be True as long as our counter
variable i is less than or equal to n (10 in our program).

We need to increase the value of counter variable in the body of the loop. This is
very important (and mostly forgotten). Failing to do so will result in an infinite
loop (never ending loop).

Finally the result is displayed.

while loop with else

Same as that of for loop, we can have an optional else block with while loop as
well.

The else part is executed if the condition in the while loop evaluates to False. The
while loop can be terminated with a break statement.

In such case, the else part is ignored. Hence, a while loop's else part runs if no
break occurs and the condition is false.

Here is an example to illustrate this.

# Example to illustrate

# the use of else statement

# with the while loop

Notes on Python Programming By Prof.N.S.Raote


counter = 0

while counter < 3:

print("Inside loop")

counter = counter + 1

else:

print("Inside else")

Output

Inside loop
Inside loop
Inside loop
Inside else

Here, we use a counter variable to print the string Inside loop three times.

On the forth iteration, the condition in while becomes False. Hence, the else part is
executed.

Python break and continue

In Python, break and continue statements can alter the flow of a normal loop.

Loops iterate over a block of code until test expression is false, but sometimes we
wish to terminate the current iteration or even the whole loop without cheking test
expression.

The break and continue statements are used in these cases.

Python break statement

Notes on Python Programming By Prof.N.S.Raote


The break statement terminates the loop containing it. Control of the program
flows to the statement immediately after the body of the loop.

If break statement is inside a nested loop (loop inside another loop), break will
terminate the innermost loop.

Syntax of break

break

Flowchart of break

The working of break statement in for loop and while loop is shown below.

Example: Python break

for val in "string":

if val == "i":

break

Notes on Python Programming By Prof.N.S.Raote


print(val)

print("The end")

Output

s
t
r
The end

In this program, we iterate through the "string" sequence. We check if the letter is
"i", upon which we break from the loop. Hence, we see in our output that all the
letters up till "i" gets printed. After that, the loop terminates.

Python continue statement

The continue statement is used to skip the rest of the code inside a loop for the
current iteration only. Loop does not terminate but continues on with the next
iteration.

Syntax of Continue

continue

Flowchart of continue

Notes on Python Programming By Prof.N.S.Raote


The working of continue statement in for and while loop is shown below.

Example: Python continue

for val in "string":

if val == "i":

continue

Notes on Python Programming By Prof.N.S.Raote


print(val)

print("The end")

Output

s
t
r
n
g
The end

This program is same as the above example except the break statement has been
replaced with continue.

We continue with the loop, if the string is "i", not executing the rest of the block.
Hence, we see in our output that all the letters except "i" gets printed.

Python Functions

In Python, function is a group of related statements that perform a specific task.

Functions help break our program into smaller and modular chunks. As our
program grows larger and larger, functions make it more organized and
manageable.

Furthermore, it avoids repetition and makes code reusable.

Syntax of Function

def function_name(parameters):
"""docstring"""
statement(s)

Above shown is a function definition which consists of following components.

1. Keyword def marks the start of function header.

Notes on Python Programming By Prof.N.S.Raote


2. A function name to uniquely identify it. Function naming follows the same
rules of writing identifiers in Python.
3. Parameters (arguments) through which we pass values to a function. They
are optional.
4. A colon (:) to mark the end of function header.
5. Optional documentation string (docstring) to describe what the function
does.
6. One or more valid python statements that make up the function body.
Statements must have same indentation level (usually 4 spaces).
7. An optional return statement to return a value from the function.

Example of a function

def greet(name):

"""This function greets to

the person passed in as

parameter"""

print("Hello, " + name + ". Good morning!")

Function Call

Once we have defined a function, we can call it from another function, program or
even the Python prompt. To call a function we simply type the function name with
appropriate parameters.

>>> greet('Paul')
Hello, Paul. Good morning!

ote: Try running the above code into the Python shell to see the output.

Docstring

The first string after the function header is called the docstring and is short for
documentation string. It is used to explain in brief, what a function does.

Notes on Python Programming By Prof.N.S.Raote


Although optional, documentation is a good programming practice. Unless you can
remember what you had for dinner last week, always document your code.

In the above example, we have a docstring immediately below the function header.
We generally use triple quotes so that docstring can extend up to multiple lines.
This string is available to us as __doc__ attribute of the function.

For example:

Try running the following into the Python shell to see the output.

>>> print(greet.__doc__)
This function greets to
the person passed into the
name parameter

The return statement

The return statement is used to exit a function and go back to the place from where
it was called.

Syntax of return

return [expression_list]

This statement can contain expression which gets evaluated and the value is
returned. If there is no expression in the statement or the return statement itself is
not present inside a function, then the function will return the None object.

For example:

>>> print(greet("May"))
Hello, May. Good morning!
None

Here, None is the returned value.

Example of return

def absolute_value(num):
Notes on Python Programming By Prof.N.S.Raote
"""This function returns the absolute

value of the entered number"""

if num >= 0:

return num

else:

return -num

# Output: 2

print(absolute_value(2))

# Output: 4

print(absolute_value(-4))

Scope and Lifetime of variables

Scope of a variable is the portion of a program where the variable is recognized.


Parameters and variables defined inside a function is not visible from outside.
Hence, they have a local scope.

Lifetime of a variable is the period throughout which the variable exits in the
memory. The lifetime of variables inside a function is as long as the function
executes.

They are destroyed once we return from the function. Hence, a function does not
remember the value of a variable from its previous calls.

Here is an example to illustrate the scope of a variable inside a function.

def my_func():

x = 10

print("Value inside function:",x)

Notes on Python Programming By Prof.N.S.Raote


x = 20

my_func()

print("Value outside function:",x)

Output

Value inside function: 10


Value outside function: 20

Here, we can see that the value of x is 20 initially. Even though the function
my_func() changed the value of x to 10, it did not effect the value outside the
function.

This is because the variable x inside the function is different (local to the function)
from the one outside. Although they have same names, they are two different
variables with different scope.

On the other hand, variables outside of the function are visible from inside. They
have a global scope.

We can read these values from inside the function but cannot change (write) them.
In order to modify the value of variables outside the function, they must be
declared as global variables using the keyword global.

Types of Functions

Basically, we can divide functions into the following two types:

1. Built-in functions - Functions that are built into Python.


2. User-defined functions - Functions defined by the users themselves.

Python Recursion

Recursion is the process of defining something in terms of itself.

A physical world example would be to place two parallel mirrors facing each
other. Any object in between them would be reflected recursively.

Notes on Python Programming By Prof.N.S.Raote


Python Recursive Function

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.

Following is an example of recursive function to find the factorial of an integer.

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.

Example of recursive function

# An example of a recursive function to

# find the factorial of a number

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

Notes on Python Programming By Prof.N.S.Raote


In the above example, calc_factorial() is a recursive functions as it calls itself.

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. This recursive call can be explained in the following steps.

calc_factorial(4) # 1st call with 4


4 * calc_factorial(3) # 2nd call with 3
4 * 3 * calc_factorial(2) # 3rd call with 2
4 * 3 * 2 * calc_factorial(1) # 4th call with 1
4*3*2*1 # return from 4th call as number=1
4*3*2 # return from 3rd call
4*6 # return from 2nd call
24 # return from 1st call

Our recursion ends when the number reduces to 1. This is called the base
condition.

Every recursive function must have a base condition that stops the recursion or else
the function calls itself infinitely.

Advantages of recursion

1. Recursive functions make the code look clean and elegant.


2. A complex task can be broken down into simpler sub-problems using
recursion.
3. Sequence generation is easier with recursion than using some nested
iteration.

Disadvantages of recursion

1. Sometimes the logic behind recursion is hard to follow through.


2. Recursive calls are expensive (inefficient) as they take up a lot of memory
and time.
3. Recursive functions are hard to debug.

Notes on Python Programming By Prof.N.S.Raote


Python Modules

Modules refer to a file containing Python statements and definitions.

A file containing Python code, for e.g.: example.py, is called a module and its
module name would be example.

We use modules to break down large programs into small manageable and
organized files. Furthermore, modules provide reusability of code.

We can define our most used functions in a module and import it, instead of
copying their definitions into different programs.

Let us create a module. Type the following and save it as example.py.

# Python Module example

def add(a, b):


"""This program adds two
numbers and return the result"""

result = a + b
return result

Here, we have defined a function add() inside a module named example. The
function takes in two numbers and returns their sum.

How to import modules in Python?

We can import the definitions inside a module to another module or the interactive
interpreter in Python.

We use the import keyword to do this. To import our previously defined module
example we type the following in the Python prompt.

>>> import example

This does not enter the names of the functions defined in example directly in the
current symbol table. It only enters the module name example there.

Notes on Python Programming By Prof.N.S.Raote


Using the module name we can access the function using dot (.) operation. For
example:

>>> example.add(4,5.5)
9.5

Python has a ton of standard modules available.

You can check out the full list of Python standard modules and what they are for.
These files are in the Lib directory inside the location where you installed Python.

Standard modules can be imported the same way as we import our user-defined
modules.

There are various ways to import modules. They are listed as follows.

Python import statement

We can import a module using import statement and access the definitions inside it
using the dot operator as described above. Here is an example.

# import statement example

# to import standard module math

import math

print("The value of pi is", math.pi)

When you run the program, the output will be:

The value of pi is 3.141592653589793

Import with renaming

We can import a module by renaming it as follows.

import math as m

print("The value of pi is", m.pi)

Notes on Python Programming By Prof.N.S.Raote


We have renamed the math module as m. This can save us typing time in some
cases.

Note that the name math is not recognized in our scope. Hence, math.pi is invalid,
m.pi is the correct implementation.

Python from...import statement

We can import specific names form a module without importing the module as a
whole. Here is an example.

from math import pi

print("The value of pi is", pi)

We imported only the attribute pi form the module.

In such case we don't use the dot operator. We could have imported multiple
attributes as follows.

>>> from math import pi, e


>>> pi
3.141592653589793
>>> e
2.718281828459045

Import all names

We can import all names(definitions) form a module using the following construct.

# import all names form

# the standard module math

from math import *

print("The value of pi is", pi)

Notes on Python Programming By Prof.N.S.Raote


We imported all the definitions from the math module. This makes all names
except those beginnig with an underscore, visible in our scope.

Importing everything with the asterisk (*) symbol is not a good programming
practice. This can lead to duplicate definitions for an identifier. It also hampers the
readability of our code.

Python Module Search Path

While importing a module, Python looks at several places. Interpreter first looks
for a built-in module then (if not found) into a list of directories defined in
sys.path. The search is in this order.

 The current directory.


 PYTHONPATH (an environment variable with a list of directory).
 The installation-dependent default directory.

>>> import sys


>>> sys.path
['',
'C:\\Python33\\Lib\\idlelib',
'C:\\Windows\\system32\\python33.zip',
'C:\\Python33\\DLLs',
'C:\\Python33\\lib',
'C:\\Python33',
'C:\\Python33\\lib\\site-packages']

We can add modify this list to add our own path.

Reloading a module

The Python interpreter imports a module only once during a session. This makes
things more efficient. Here is an example to show how this works.

Suppose we have the following code in a module named my_module.

# This module shows the effect of


# multiple imports and reload

print("This code got executed")

Notes on Python Programming By Prof.N.S.Raote


Now we see the effect of multiple imports.

>>> import my_module


This code got executed
>>> import my_module
>>> import my_module

We can see that our code got executed only once. This goes to say that our module
was imported only once.

Now if our module changed during the course of the program, we would have to
reload it.One way to do this is to restart the interpreter. But this does not help
much.

Python provides a neat way of doing this. We can use the reload() function inside
the imp module to reload a module. This is how its done.

>>> import imp


>>> import my_module
This code got executed
>>> import my_module
>>> imp.reload(my_module)
This code got executed
<module 'my_module' from '.\\my_module.py'>

The dir() built-in function

We can use the dir() function to find out names that are defined inside a module.

For example, we have defined a function add() in the module example that we had
in the beginning.

>>> dir(example)
['__builtins__',
'__cached__',
'__doc__',
'__file__',
'__initializing__',
'__loader__',
'__name__',
'__package__',

Notes on Python Programming By Prof.N.S.Raote


'add']

Here, we can see a sorted list of names (along with add). All other names that
begin with an underscore are default Python attributes associated with the module
(we did not define them ourself).

For example, the __name__ attribute contains the name of the module.

>>> import example


>>> example.__name__
'example'

All the names defined in our current namespace can be found out using the dir()
function without any arguments.

>>> a = 1
>>> b = "hello"
>>> import math
>>> dir()
['__builtins__', '__doc__', '__name__', 'a', 'b', 'math', 'pyscripter']

Notes on Python Programming By Prof.N.S.Raote


LIST
How to create a list?

In Python programming, a list is created by placing all the items (elements) inside
a square bracket [ ], separated by commas.

It can have any number of items and they may be of different types (integer, float,
string etc.).

# empty list
my_list = []

# list of integers
my_list = [1, 2, 3]

# list with mixed datatypes


my_list = [1, "Hello", 3.4]

Also, a list can even have another list as an item. This is called nested list.

# nested list
my_list = ["mouse", [8, 4, 6], ['a']]

How to access elements from a list?

There are various ways in which we can access the elements of a list.

List Index

We can use the index operator [] to access an item in a list. Index starts from 0. So,
a list having 5 elements will have index from 0 to 4.

Trying to access an element other that this will raise an IndexError. The index must
be an integer. We can't use float or other types, this will result into TypeError.

Nested list are accessed using nested indexing.

Notes on Python Programming By Prof.N.S.Raote


my_list = ['p','r','o','b','e']

# Output: p

print(my_list[0])

# Output: o

print(my_list[2])

# Output: e

print(my_list[4])

# Error! Only integer can be used for indexing

# my_list[4.0]

# Nested List

n_list = ["Happy", [2,0,1,5]]

# Nested indexing

# Output: a

print(n_list[0][1])

Notes on Python Programming By Prof.N.S.Raote


# Output: 5

print(n_list[1][3])

Negative indexing

Python allows negative indexing for its sequences. The index of -1 refers to the last
item, -2 to the second last item and so on.

my_list = ['p','r','o','b','e']

# Output: e

print(my_list[-1])

# Output: p

print(my_list[-5])

How to slice lists in Python?

We can access a range of items in a list by using the slicing operator (colon).

my_list = ['p','r','o','g','r','a','m','i','z']

# elements 3rd to 5th

print(my_list[2:5])

Notes on Python Programming By Prof.N.S.Raote


# elements beginning to 4th

print(my_list[:-5])

# elements 6th to end

print(my_list[5:])

# elements beginning to end

print(my_list[:])

Slicing can be best visualized by considering the index to be between the elements
as shown below. So if we want to access a range, we need two index that will slice
that portion from the list.

How to change or add elements to a list?

List are mutable, meaning, their elements can be changed unlike string or tuple.

We can use assignment operator (=) to change an item or a range of items.

# mistake values

odd = [2, 4, 6, 8]

Notes on Python Programming By Prof.N.S.Raote


# change the 1st item

odd[0] = 1

# Output: [1, 4, 6, 8]

print(odd)

# change 2nd to 4th items

odd[1:4] = [3, 5, 7]

# Output: [1, 3, 5, 7]

print(odd)

We can add one item to a list using append() method or add several items using
extend() method.

odd = [1, 3, 5]

odd.append(7)

# Output: [1, 3, 5, 7]
print(odd)

odd.extend([9, 11, 13])

# Output: [1, 3, 5, 7, 9, 11, 13]


print(odd)

We can also use + operator to combine two lists. This is also called concatenation.

The * operator repeats a list for the given number of times.

odd = [1, 3, 5]

# Output: [1, 3, 5, 9, 7, 5]
print(odd + [9, 7, 5])

#Output: ["re", "re", "re"]

Notes on Python Programming By Prof.N.S.Raote


print(["re"] * 3)

Furthermore, we can insert one item at a desired location by using the method
insert() or insert multiple items by squeezing it into an empty slice of a list.

odd = [1, 9]

odd.insert(1,3)

# Output: [1, 3, 9]

print(odd)

odd[2:2] = [5, 7]

# Output: [1, 3, 5, 7, 9]

print(odd)

How to delete or remove elements from a list?

We can delete one or more items from a list using the keyword del. It can even
delete the list entirely.

my_list = ['p','r','o','b','l','e','m']

# delete one item

del my_list[2]

Notes on Python Programming By Prof.N.S.Raote


# Output: ['p', 'r', 'b', 'l', 'e', 'm']

print(my_list)

# delete multiple items

del my_list[1:5]

# Output: ['p', 'm']

print(my_list)

# delete entire list

del my_list

# Error: List not defined

print(my_list)

We can use remove() method to remove the given item or pop() method to remove
an item at the given index.

The pop() method removes and returns the last item if index is not provided. This
helps us implement lists as stacks (first in, last out data structure).

We can also use the clear() method to empty a list.

my_list = ['p','r','o','b','l','e','m']

my_list.remove('p')

Notes on Python Programming By Prof.N.S.Raote


# Output: ['r', 'o', 'b', 'l', 'e', 'm']

print(my_list)

# Output: 'o'

print(my_list.pop(1))

# Output: ['r', 'b', 'l', 'e', 'm']

print(my_list)

# Output: 'm'

print(my_list.pop())

# Output: ['r', 'b', 'l', 'e']

print(my_list)

my_list.clear()

# Output: []

print(my_list)

inally, we can also delete items in a list by assigning an empty list to a slice of
elements.

>>> my_list = ['p','r','o','b','l','e','m']

Notes on Python Programming By Prof.N.S.Raote


>>> my_list[2:3] = []
>>> my_list
['p', 'r', 'b', 'l', 'e', 'm']
>>> my_list[2:5] = []
>>> my_list
['p', 'r', 'm']

Python List Methods

Methods that are available with list object in Python programming are tabulated
below.

They are accessed as list.method(). Some of the methods have already been used
above.

Python List Methods

append() - Add an element to the end of the list

extend() - Add all elements of a list to the another list

insert() - Insert an item at the defined index

remove() - Removes an item from the list

pop() - Removes and returns an element at the given index

clear() - Removes all items from the list

index() - Returns the index of the first matched item

count() - Returns the count of number of items passed as an argument

sort() - Sort items in a list in ascending order

reverse() - Reverse the order of items in the list

copy() - Returns a shallow copy of the list

Notes on Python Programming By Prof.N.S.Raote


Some examples of Python list methods:

my_list = [3, 8, 1, 6, 0, 8, 4]

# Output: 1

print(my_list.index(8))

# Output: 2

print(my_list.count(8))

my_list.sort()

# Output: [0, 1, 3, 4, 6, 8, 8]

print(my_list)

my_list.reverse()

# Output: [8, 8, 6, 4, 3, 1, 0]

print(my_list)

List Comprehension: Elegant way to create new List

List comprehension is an elegant and concise way to create new list from an
existing list in Python.

List comprehension consists of an expression followed by for statement inside


square brackets.

Here is an example to make a list with each item being increasing power of 2.

pow2 = [2 ** x for x in range(10)]

# Output: [1, 2, 4, 8, 16, 32, 64, 128, 256, 512]

print(pow2)

Notes on Python Programming By Prof.N.S.Raote


This code is equivalent to

pow2 = []
for x in range(10):
pow2.append(2 ** x)

A list comprehension can optionally contain more for or if statements. An optional


if statement can filter out items for the new list. Here are some examples.

>>> pow2 = [2 ** x for x in range(10) if x > 5]


>>> pow2
[64, 128, 256, 512]
>>> odd = [x for x in range(20) if x % 2 == 1]
>>> odd
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
>>> [x+y for x in ['Python ','C '] for y in ['Language','Programming']]
['Python Language', 'Python Programming', 'C Language', 'C Programming']

Other List Operations in Python

List Membership Test

We can test if an item exists in a list or not, using the keyword in.

my_list = ['p','r','o','b','l','e','m']

# Output: True

print('p' in my_list)

# Output: False

print('a' in my_list)

# Output: True

print('c' not in my_list)

Notes on Python Programming By Prof.N.S.Raote


Built-in Functions with List

Built-in functions like all(), any(), enumerate(), len(), max(), min(), list(), sorted()
etc. are commonly used with list to perform different tasks.

Built-in Functions with List

Function Description

all() Return True if all elements of the list are true (or if the list is empty).

Return True if any element of the list is true. If the list is empty,
any()
return False.

Return an enumerate object. It contains the index and value of all the
enumerate()
items of list as a tuple.

len() Return the length (the number of items) in the list.

list() Convert an iterable (tuple, string, set, dictionary) to a list.

max() Return the largest item in the list.

min() Return the smallest item in the list

sorted() Return a new sorted list (does not sort the list itself).

sum() Return the sum of all elements in the list.

Notes on Python Programming By Prof.N.S.Raote


Tuple
In Python programming, a tuple is similar to a list. The difference between the two
is that we cannot change the elements of a tuple once it is assigned whereas in a
list, elements can be changed.

Advantages of Tuple over List

Since, tuples are quite similiar to lists, both of them are used in similar situations as
well.

However, there are certain advantages of implementing a tuple over a list. Below
listed are some of the main advantages:

 We generally use tuple for heterogeneous (different) datatypes and list for
homogeneous (similar) datatypes.
 Since tuple are immutable, iterating through tuple is faster than with list. So
there is a slight performance boost.
 Tuples that contain immutable elements can be used as key for a dictionary.
With list, this is not possible.
 If you have data that doesn't change, implementing it as tuple will guarantee
that it remains write-protected.

Creating a Tuple

A tuple is created by placing all the items (elements) inside a parentheses (),
separated by comma. The parentheses are optional but is a good practice to write it.

A tuple can have any number of items and they may be of different types (integer,
float, list, string etc.).

# empty tuple

# Output: ()

my_tuple = ()

print(my_tuple)

Notes on Python Programming By Prof.N.S.Raote


# tuple having integers

# Output: (1, 2, 3)

my_tuple = (1, 2, 3)

print(my_tuple)

# tuple with mixed datatypes

# Output: (1, "Hello", 3.4)

my_tuple = (1, "Hello", 3.4)

print(my_tuple)

# nested tuple

# Output: ("mouse", [8, 4, 6], (1, 2, 3))

my_tuple = ("mouse", [8, 4, 6], (1, 2, 3))

print(my_tuple)

Accessing Elements in a Tuple

There are various ways in which we can access the elements of a tuple.

1. Indexing

We can use the index operator [] to access an item in a tuple where the index starts
from 0.

So, a tuple having 6 elements will have index from 0 to 5. Trying to access an
element other that (6, 7,...) will raise an IndexError.

The index must be an integer, so we cannot use float or other types. This will result
into TypeError.

Notes on Python Programming By Prof.N.S.Raote


Likewise, nested tuple are accessed using nested indexing, as shown in the
example below

my_tuple = ('p','e','r','m','i','t')

# Output: 'p'

print(my_tuple[0])

# Output: 't'

print(my_tuple[5])

# index must be in range

# If you uncomment line 14,

# you will get an error.

# IndexError: list index out of range

#print(my_tuple[6])

# index must be an integer

# If you uncomment line 21,

# you will get an error.

# TypeError: list indices must be integers, not float

Notes on Python Programming By Prof.N.S.Raote


#my_tuple[2.0]

# nested tuple

n_tuple = ("mouse", [8, 4, 6], (1, 2, 3))

# nested index

# Output: 's'

print(n_tuple[0][3])

# nested index

# Output: 4

print(n_tuple[1][1])

When you run the program, the output will be:

p
t
s
4

2. Negative Indexing

Python allows negative indexing for its sequences.

The index of -1 refers to the last item, -2 to the second last item and so on.

my_tuple = ('p','e','r','m','i','t')

# Output: 't'

print(my_tuple[-1])

Notes on Python Programming By Prof.N.S.Raote


# Output: 'p'

print(my_tuple[-6])

3. Slicing

We can access a range of items in a tuple by using the slicing operator - colon ":".

my_tuple = ('p','r','o','g','r','a','m','i','z')

# elements 2nd to 4th

# Output: ('r', 'o', 'g')

print(my_tuple[1:4])

# elements beginning to 2nd

# Output: ('p', 'r')

print(my_tuple[:-7])

# elements 8th to end

# Output: ('i', 'z')

print(my_tuple[7:])

# elements beginning to end

# Output: ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')

Notes on Python Programming By Prof.N.S.Raote


print(my_tuple[:])

Slicing can be best visualized by considering the index to be between the elements
as shown below. So if we want to access a range, we need the index that will slice
the portion from the tuple.

Changing a Tuple

Unlike lists, tuples are immutable.

This means that elements of a tuple cannot be changed once it has been assigned.
But, if the element is itself a mutable datatype like list, its nested items can be
changed.

We can also assign a tuple to different values (reassignment).

my_tuple = (4, 2, 3, [6, 5])

# we cannot change an element

# If you uncomment line 8

# you will get an error:

# TypeError: 'tuple' object does not support item assignment

#my_tuple[1] = 9

# but item of mutable element can be changed

Notes on Python Programming By Prof.N.S.Raote


# Output: (4, 2, 3, [9, 5])

my_tuple[3][0] = 9

print(my_tuple)

# tuples can be reassigned

# Output: ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')

my_tuple = ('p','r','o','g','r','a','m','i','z')

print(my_tuple)

We can use + operator to combine two tuples. This is also called concatenation.

We can also repeat the elements in a tuple for a given number of times using the *
operator.

Both + and * operations result into a new tuple.

# Concatenation

# Output: (1, 2, 3, 4, 5, 6)

print((1, 2, 3) + (4, 5, 6))

# Repeat

# Output: ('Repeat', 'Repeat', 'Repeat')

print(("Repeat",) * 3)

Deleting a Tuple

As discussed above, we cannot change the elements in a tuple. That also means we
cannot delete or remove items from a tuple.

Notes on Python Programming By Prof.N.S.Raote


But deleting a tuple entirely is possible using the keyword del.

my_tuple = ('p','r','o','g','r','a','m','i','z')

# can't delete items

# if you uncomment line 8,

# you will get an error:

# TypeError: 'tuple' object doesn't support item deletion

#del my_tuple[3]

# can delete entire tuple

# NameError: name 'my_tuple' is not defined

del my_tuple

my_tuple

Python Tuple Methods

Methods that add items or remove items are not available with tuple. Only the
following two methods are available.

Python Tuple Method

Method Description

count(x) Return the number of items that is equal to x

index(x) Return index of first item that is equal to x

Some examples of Python tuple methods:

my_tuple = ('a','p','p','l','e',)

Notes on Python Programming By Prof.N.S.Raote


# Count

# Output: 2

print(my_tuple.count('p'))

# Index

# Output: 3

print(my_tuple.index('l'))

Built-in Functions with Tuple

Built-in functions like all(), any(), enumerate(), len(), max(), min(), sorted(),
tuple() etc. are commonly used with tuple to perform different tasks.

Built-in Functions with Tuple

Function Description

Return True if all elements of the tuple are true (or if the tuple is
all()
empty).

Return True if any element of the tuple is true. If the tuple is empty,
any()
return False.

Return an enumerate object. It contains the index and value of all the
enumerate()
items of tuple as pairs.

len() Return the length (the number of items) in the tuple.

max() Return the largest item in the tuple.

min() Return the smallest item in the tuple

Notes on Python Programming By Prof.N.S.Raote


Take elements in the tuple and return a new sorted list (does not sort
sorted()
the tuple itself).

sum() Retrun the sum of all elements in the tuple.

tuple() Convert an iterable (list, string, set, dictionary) to a tuple.

A string is a sequence of characters.

A character is simply a symbol. For example, the English language has 26


characters.

Computers do not deal with characters, they deal with numbers (binary). Even
though you may see characters on your screen, internally it is stored and
manipulated as a combination of 0's and 1's.

This conversion of character to a number is called encoding, and the reverse


process is decoding. ASCII and Unicode are some of the popular encoding used.

In Python, string is a sequence of Unicode character. Unicode was introduced to


include every character in all languages and bring uniformity in encoding. You can
learn more about Unicode from here.

How to create a string?

Strings can be created by enclosing characters inside a single quote or double


quotes. Even triple quotes can be used in Python but generally used to represent
multiline strings and docstrings.

# all of the following are equivalent

my_string = 'Hello'

print(my_string)

my_string = "Hello"

print(my_string)

Notes on Python Programming By Prof.N.S.Raote


my_string = '''Hello'''

print(my_string)

# triple quotes string can extend multiple lines

my_string = """Hello, welcome to

the world of Python"""

print(my_string)

When you run the program, the output will be:

Hello
Hello
Hello
Hello, welcome to
the world of Python

How to access characters in a string?

We can access individual characters using indexing and a range of characters using
slicing. Index starts from 0. Trying to access a character out of index range will
raise an IndexError. The index must be an integer. We can't use float or other
types, this will result into TypeError.

Python allows negative indexing for its sequences.

The index of -1 refers to the last item, -2 to the second last item and so on. We can
access a range of items in a string by using the slicing operator (colon).

str = 'programiz'

print('str = ', str)

Notes on Python Programming By Prof.N.S.Raote


#first character

print('str[0] = ', str[0])

#last character

print('str[-1] = ', str[-1])

#slicing 2nd to 5th character

print('str[1:5] = ', str[1:5])

#slicing 6th to 2nd last character

print('str[5:-2] = ', str[5:-2])

If we try to access index out of the range or use decimal number, we will get
errors.

# index must be in range


>>> my_string[15]
...
IndexError: string index out of range

# index must be an integer


>>> my_string[1.5]
...
TypeError: string indices must be integers

Slicing can be best visualized by considering the index to be between the elements
as shown below.

If we want to access a range, we need the index that will slice the portion from the
string.

Notes on Python Programming By Prof.N.S.Raote


How to change or delete a string?

Strings are immutable. This means that elements of a string cannot be changed
once it has been assigned. We can simply reassign different strings to the same
name.

>>> my_string = 'programiz'


>>> my_string[5] = 'a'
...
TypeError: 'str' object does not support item assignment
>>> my_string = 'Python'
>>> my_string
'Python'

We cannot delete or remove characters from a string. But deleting the string
entirely is possible using the keyword del.

>>> del my_string[1]


...
TypeError: 'str' object doesn't support item deletion
>>> del my_string
>>> my_string
...
NameError: name 'my_string' is not defined

Python String Operations

There are many operations that can be performed with string which makes it one of
the most used datatypes in Python.

Concatenation of Two or More Strings

Notes on Python Programming By Prof.N.S.Raote


Joining of two or more strings into a single one is called concatenation.

The + operator does this in Python. Simply writing two string literals together also
concatenates them.

The * operator can be used to repeat the string for a given number of times.

str1 = 'Hello'

str2 ='World!'

# using +

print('str1 + str2 = ', str1 + str2)

# using *

print('str1 * 3 =', str1 * 3)

Writing two string literals together also concatenates them like + operator.

If we want to concatenate strings in different lines, we can use parentheses.

>>> # two string literals together


>>> 'Hello ''World!'
'Hello World!'

>>> # using parentheses


>>> s = ('Hello '
... 'World')
>>> s
'Hello World'

Iterating Through String

Using for loop we can iterate through a string. Here is an example to count the
number of 'l' in a string.

Notes on Python Programming By Prof.N.S.Raote


count = 0

for letter in 'Hello World':

if(letter == 'l'):

count += 1

print(count,'letters found')

Built-in functions to Work with Python

Various built-in functions that work with sequence, works with string as well.

Some of the commonly used ones are enumerate() and len(). The enumerate()
function returns an enumerate object. It contains the index and value of all the
items in the string as pairs. This can be useful for iteration.

Similarly, len() returns the length (number of characters) of the string.

str = 'cold'

# enumerate()

list_enumerate = list(enumerate(str))

print('list(enumerate(str) = ', list_enumerate)

#character count

print('len(str) = ', len(str))

he format() Method for Formatting Strings

Notes on Python Programming By Prof.N.S.Raote


The format() method that is available with the string object is very versatile and
powerful in formatting strings. Format strings contains curly braces {} as
placeholders or replacement fields which gets replaced.

We can use positional arguments or keyword arguments to specify the order.

# default(implicit) order

default_order = "{}, {} and {}".format('John','Bill','Sean')

print('\n--- Default Order ---')

print(default_order)

# order using positional argument

positional_order = "{1}, {0} and {2}".format('John','Bill','Sean')

print('\n--- Positional Order ---')

print(positional_order)

# order using keyword argument

keyword_order = "{s}, {b} and {j}".format(j='John',b='Bill',s='Sean')

print('\n--- Keyword Order ---')

print(keyword_order)

The format() method can have optional format specifications. They are separated
from field name using colon. For example, we can left-justify <, right-justify > or
center ^ a string in the given space. We can also format integers as binary,
hexadecimal etc. and floats can be rounded or displayed in the exponent format.
There are a ton of formatting you can use. Visit here for all the string formatting
available with the format() method.

>>> # formatting integers

Notes on Python Programming By Prof.N.S.Raote


>>> "Binary representation of {0} is {0:b}".format(12)
'Binary representation of 12 is 1100'

>>> # formatting floats


>>> "Exponent representation: {0:e}".format(1566.345)
'Exponent representation: 1.566345e+03'

>>> # round off


>>> "One third is: {0:.3f}".format(1/3)
'One third is: 0.333'

>>> # string alignment


>>> "|{:<10}|{:^10}|{:>10}|".format('butter','bread','ham')
'|butter | bread | ham|'

A set is an unordered collection of items. Every element is unique (no duplicates) and must be
immutable (which cannot be changed).

However, the set itself is mutable. We can add or remove items from it.

Sets can be used to perform mathematical set operations like union, intersection, symmetric
difference etc.

Notes on Python Programming By Prof.N.S.Raote


SET

How to create a set?


A set is created by placing all the items (elements) inside curly braces {}, separated by comma or
by using the built-in function set().

It can have any number of items and they may be of different types (integer, float, tuple, string
etc.). But a set cannot have a mutable element, like list, set or dictionary, as its element.

# set of integers

my_set = {1, 2, 3}

print(my_set)

# set of mixed datatypes

my_set = {1.0, "Hello", (1, 2, 3)}

print(my_set)

# set do not have duplicates

# Output: {1, 2, 3, 4}

my_set = {1,2,3,4,3,2}

print(my_set)

# set cannot have mutable items

# here [3, 4] is a mutable list

# If you uncomment line #12,

# this will cause an error.

Notes on Python Programming By Prof.N.S.Raote


# TypeError: unhashable type: 'list'

#my_set = {1, 2, [3, 4]}

# we can make set from a list

# Output: {1, 2, 3}

my_set = set([1,2,3,2])

print(my_set)

Creating an empty set is a bit tricky.

Empty curly braces {} will make an empty dictionary in Python. To make a set without any
elements we use the set() function without any argument.

# initialize a with {}

a = {}

# check data type of a

# Output: <class 'dict'>

print(type(a))

# initialize a with set()

a = set()

# check data type of a

Notes on Python Programming By Prof.N.S.Raote


# Output: <class 'set'>

print(type(a))

How to change a set in Python?


Sets are mutable. But since they are unordered, indexing have no meaning.

We cannot access or change an element of set using indexing or slicing. Set does not support it.

We can add single element using the add() method and multiple elements using the update()
method. The update() method can take tuples, lists, strings or other sets as its argument. In all
cases, duplicates are avoided.

# initialize my_set

my_set = {1,3}

print(my_set)

# if you uncomment line 9,

# you will get an error

# TypeError: 'set' object does not support indexing

#my_set[0]

# add an element

Notes on Python Programming By Prof.N.S.Raote


# Output: {1, 2, 3}

my_set.add(2)

print(my_set)

# add multiple elements

# Output: {1, 2, 3, 4}

my_set.update([2,3,4])

print(my_set)

# add list and set

# Output: {1, 2, 3, 4, 5, 6, 8}

my_set.update([4,5], {1,6,8})

print(my_set)

When you run the program, the output will be:

{1, 3}
{1, 2, 3}
{1, 2, 3, 4}
{1, 2, 3, 4, 5, 6, 8}

How to remove elements from a set?


A particular item can be removed from set using methods, discard() and remove().

The only difference between the two is that, while using discard() if the item does not exist in
the set, it remains unchanged. But remove() will raise an error in such condition.

The following example will illustrate this.

# initialize my_set

Notes on Python Programming By Prof.N.S.Raote


my_set = {1, 3, 4, 5, 6}

print(my_set)

# discard an element

# Output: {1, 3, 5, 6}

my_set.discard(4)

print(my_set)

# remove an element

# Output: {1, 3, 5}

my_set.remove(6)

print(my_set)

# discard an element

# not present in my_set

# Output: {1, 3, 5}

my_set.discard(2)

print(my_set)

# remove an element

# not present in my_set

Notes on Python Programming By Prof.N.S.Raote


# If you uncomment line 27,

# you will get an error.

# Output: KeyError: 2

#my_set.remove(2)

Similarly, we can remove and return an item using the pop() method.

Set being unordered, there is no way of determining which item will be popped. It is completely
arbitrary.

We can also remove all items from a set using clear().

# initialize my_set

# Output: set of unique elements

my_set = set("HelloWorld")

print(my_set)

# pop an element

# Output: random element

print(my_set.pop())

# pop another element

# Output: random element

my_set.pop()

print(my_set)

Notes on Python Programming By Prof.N.S.Raote


# clear my_set

#Output: set()

my_set.clear()

print(my_set)

Python Set Operations


Sets can be used to carry out mathematical set operations like union, intersection, difference and
symmetric difference. We can do this with operators or methods.

Let us consider the following two sets for the following operations.

>>> A = {1, 2, 3, 4, 5}
>>> B = {4, 5, 6, 7, 8}

Set Union

Union of A and B is a set of all elements from both sets.

Union is performed using | operator. Same can be accomplished using the method union().

# initialize A and B

A = {1, 2, 3, 4, 5}

B = {4, 5, 6, 7, 8}

# use | operator

# Output: {1, 2, 3, 4, 5, 6, 7, 8}

print(A | B)

Try the following examples on Python shell.

Notes on Python Programming By Prof.N.S.Raote


# use union function
>>> A.union(B)
{1, 2, 3, 4, 5, 6, 7, 8}

# use union function on B


>>> B.union(A)
{1, 2, 3, 4, 5, 6, 7, 8}

Intersection of A and B is a set of elements that are common in both sets.

Intersection is performed using & operator. Same can be accomplished using the method
intersection().

# initialize A and B

A = {1, 2, 3, 4, 5}

B = {4, 5, 6, 7, 8}

# use & operator

# Output: {4, 5}

print(A & B)

Try the following examples on Python shell.

# use intersection function on A


>>> A.intersection(B)
{4, 5}

# use intersection function on B


>>> B.intersection(A)
{4, 5}

Difference of A and B (A - B) is a set of elements that are only in A but not in B. Similarly, B - A
is a set of element in B but not in A.

Difference is performed using - operator. Same can be accomplished using the method
difference().

# initialize A and B

Notes on Python Programming By Prof.N.S.Raote


A = {1, 2, 3, 4, 5}

B = {4, 5, 6, 7, 8}

# use - operator on A

# Output: {1, 2, 3}

print(A - B)

Try the following examples on Python shell.

# use difference function on A


>>> A.difference(B)
{1, 2, 3}

# use - operator on B
>>> B - A
{8, 6, 7}

# use difference function on B


>>> B.difference(A)
{8, 6, 7}

Different Python Set Methods


There are many set methods, some of which we have already used above. Here is a list of all the
methods that are available with set objects.

Python Set Methods

Method Description

add() Add an element to a set

clear() Remove all elements form a set

copy() Return a shallow copy of a set

difference() Return the difference of two or more sets as a new set

Notes on Python Programming By Prof.N.S.Raote


difference_update() Remove all elements of another set from this set

Remove an element from set if it is a member. (Do nothing if the


discard()
element is not in set)

intersection() Return the intersection of two sets as a new set

intersection_update() Update the set with the intersection of itself and another

isdisjoint() Return True if two sets have a null intersection

issubset() Return True if another set contains this set

issuperset() Return True if this set contains another set

Remove and return an arbitary set element. Raise KeyError if the set
pop()
is empty

Remove an element from a set. If the element is not a member, raise a


remove()
KeyError

symmetric_difference() Return the symmetric difference of two sets as a new set

symmetric_difference_update() Update a set with the symmetric difference of itself and another

union() Return the union of sets in a new set

update() Update a set with the union of itself and others

Built-in Functions with Set

Built-in functions like all(), any(), enumerate(), len(), max(), min(), sorted(), sum() etc.
are commonly used with set to perform different tasks.

Built-in Functions with Set

Function Description

all() Return True if all elements of the set are true (or if the set is empty).

any() Return True if any element of the set is true. If the set is empty, return False.

Notes on Python Programming By Prof.N.S.Raote


Return an enumerate object. It contains the index and value of all the items of set as a
enumerate()
pair.

len() Return the length (the number of items) in the set.

max() Return the largest item in the set.

min() Return the smallest item in the set.

sorted() Return a new sorted list from elements in the set(does not sort the set itself).

sum() Retrun the sum of all elements in the set.

Notes on Python Programming By Prof.N.S.Raote


Dictionary

Python dictionary is an unordered collection of items. While other compound data types have
only value as an element, a dictionary has a key: value pair.

Dictionaries are optimized to retrieve values when the key is known.

How to create a dictionary?


Creating a dictionary is as simple as placing items inside curly braces {} separated by comma.

An item has a key and the corresponding value expressed as a pair, key: value.

While values can be of any data type and can repeat, keys must be of immutable type (string,
number or tuple with immutable elements) and must be unique.

# empty dictionary
my_dict = {}

# dictionary with integer keys


my_dict = {1: 'apple', 2: 'ball'}

# dictionary with mixed keys


my_dict = {'name': 'John', 1: [2, 4, 3]}

# using dict()
my_dict = dict({1:'apple', 2:'ball'})

# from sequence having each item as a pair


my_dict = dict([(1,'apple'), (2,'ball')])

As you can see above, we can also create a dictionary using the built-in function dict().

How to access elements from a dictionary?


While indexing is used with other container types to access values, dictionary uses keys. Key can
be used either inside square brackets or with the get() method.

The difference while using get() is that it returns None instead of KeyError, if the key is not
found.

my_dict = {'name':'Jack', 'age': 26}

Notes on Python Programming By Prof.N.S.Raote


# Output: Jack

print(my_dict['name'])

# Output: 26

print(my_dict.get('age'))

# Trying to access keys which doesn't exist throws error

# my_dict.get('address')

# my_dict['address']

hen you run the program, the output will be:

Jack
26

How to change or add elements in a dictionary?


Dictionary are mutable. We can add new items or change the value of existing items using
assignment operator.

If the key is already present, value gets updated, else a new key: value pair is added to the
dictionary.

y_dict = {'name':'Jack', 'age': 26}

# update value

my_dict['age'] = 27

#Output: {'age': 27, 'name': 'Jack'}

Notes on Python Programming By Prof.N.S.Raote


print(my_dict)

# add item

my_dict['address'] = 'Downtown'

# Output: {'address': 'Downtown', 'age': 27, 'name': 'Jack'}

print(my_dict)

How to delete or remove elements from a dictionary?


We can remove a particular item in a dictionary by using the method pop(). This method
removes as item with the provided key and returns the value.

The method, popitem() can be used to remove and return an arbitrary item (key, value) form the
dictionary. All the items can be removed at once using the clear() method.

We can also use the del keyword to remove individual items or the entire dictionary itself.

Output: 16

print(squares.pop(4))

# Output: {1: 1, 2: 4, 3: 9, 5: 25}

print(squares)

# remove an arbitrary item

# Output: (1, 1)

print(squares.popitem())

Notes on Python Programming By Prof.N.S.Raote


# Output: {2: 4, 3: 9, 5: 25}

print(squares)

# delete a particular item

del squares[5]

# Output: {2: 4, 3: 9}

print(squares)

# remove all items

squares.clear()

# Output: {}

print(squares)

# delete the dictionary itself

del squares

# Throws Error

# print(squares)

Python Dictionary Methods


Methods that are available with dictionary are tabulated below. Some of them have already been
used in the above examples.

Notes on Python Programming By Prof.N.S.Raote


Python Dictionary Methods

Method Description

clear() Remove all items form the dictionary.

copy() Return a shallow copy of the dictionary.

fromkeys(seq[, v]) Return a new dictionary with keys from seq and value equal to v (defaults to None).

get(key[,d]) Return the value of key. If key doesnot exit, return d (defaults to None).

items() Return a new view of the dictionary's items (key, value).

keys() Return a new view of the dictionary's keys.

Remove the item with key and return its value or d if key is not found. If d is not
pop(key[,d])
provided and key is not found, raises KeyError.

Remove and return an arbitary item (key, value). Raises KeyError if the dictionary
popitem()
is empty.

If key is in the dictionary, return its value. If not, insert key with a value of d and
setdefault(key[,d])
return d (defaults to None).

update([other]) Update the dictionary with the key/value pairs from other, overwriting existing keys.

values() Return a new view of the dictionary's values

Here are a few example use of these methods.

marks = {}.fromkeys(['Math','English','Science'], 0)

# Output: {'English': 0, 'Math': 0, 'Science': 0}

print(marks)

for item in marks.items():

print(item)

Notes on Python Programming By Prof.N.S.Raote


# Output: ['English', 'Math', 'Science']

list(sorted(marks.keys()))

Iterating Through a Dictionary

Using a for loop we can iterate though each key in a dictionary.

squares = {1: 1, 3: 9, 5: 25, 7: 49, 9: 81}

for i in squares:

print(squares[i])

Notes on Python Programming By Prof.N.S.Raote


Built-in Functions with Dictionary

Built-in functions like all(), any(), len(), cmp(), sorted() etc. are commonly used with
dictionary to perform different tasks.

Built-in Functions with Dictionary

Function Description

all() Return True if all keys of the dictionary are true (or if the dictionary is empty).

any() Return True if any key of the dictionary is true. If the dictionary is empty, return False.

len() Return the length (the number of items) in the dictionary.

cmp() Compares items of two dictionaries.

sorted() Return a new sorted list of keys in the dictionary.

Here are some examples that uses built-in functions to work with dictionary.

# Output: 5

print(len(squares))

# Output: [1, 3, 5, 7, 9]

print(sorted(squares))

Notes on Python Programming By Prof.N.S.Raote


Programming Examples
Python Program to Find the Largest Number in a List

This is a Python Program to find the largest number in a list.

Problem Description

The program takes a list and prints the largest number in the list.

Problem Solution

1. Take in the number of elements and store it in a variable.


2. Take in the elements of the list one by one.
3. Sort the list in ascending order.
4. Print the last element of the list.
5. Exit.

Program/Source Code

Here is source code of the Python Program to find the largest number in a list. The
program output is also shown below.

a=[]
n=int(input("Enter number of elements:"))
for i in range(1,n+1):
b=int(input("Enter element:"))
a.append(b)
a.sort()
print("Largest element is:",a[n-1])
Program Explanation

1. User must enter the number of elements and store it in a variable.


2. User must then enter the elements of the list one by one using a for loop and
store it in a list.
3. The list should then be sorted.
4. Then the last element of the list is printed which is also the largest element of
the list.

Notes on Python Programming By Prof.N.S.Raote


Runtime Test Cases

Case 1:
Enter number of elements:3
Enter element:23
Enter element:567
Enter element:3
Largest element is: 567

Case 2:
Enter number of elements:4
Enter element:34
Enter element:56
Enter element:24
Enter element:54
Largest element is: 56

2. Python Program to Find the Second Largest Number in a List

This is a Python Program to find the second largest number in a list.

Problem Description

The program takes a list and prints the second largest number in the list.

Problem Solution

1. Take in the number of elements and store it in a variable.


2. Take in the elements of the list one by one.
3. Sort the list in ascending order.
4. Print the second last element of the list.
5. Exit.

Program/Source Code

Here is source code of the Python Program to find the second largest number in a
list. The program output is also shown below.

a=[]

Notes on Python Programming By Prof.N.S.Raote


n=int(input("Enter number of elements:"))
for i in range(1,n+1):
b=int(input("Enter element:"))
a.append(b)
a.sort()
print("Second largest element is:",a[n-2])
Program Explanation

1. User must enter the number of elements and store it in a variable.


2. User must then enter the elements of the list one by one using a for loop and
store it in a list.
3. The list should then be sorted.
4. Then the last element of the list is printed which is also the largest element o

3. Python Program to Put Even and Odd elements in a List into Two Different
Lists

This is a Python Program to put the even and odd elements in a list into two
different lists.

Problem Description

The program takes a list and puts the even and odd elements in it into two separate
lists.

Problem Solution

1. Take in the number of elements and store it in a variable.


2. Take in the elements of the list one by one.
3. Use a for loop to traverse through the elements of the list and an if statement to
check if the element is even or odd.
4. If the element is even, append it to a separate list and if it is odd, append it to a
different one.
5. Display the elements in both the lists.
6. Exit.

Program/Source Code

Notes on Python Programming By Prof.N.S.Raote


Here is source code of the Python Program to put the even and odd elements in a
list into two different lists. The program output is also shown below.

a=[]
n=int(input("Enter number of elements:"))
for i in range(1,n+1):
b=int(input("Enter element:"))
a.append(b)
even=[]
odd=[]
for j in a:
if(j%2==0):
even.append(j)
else:
odd.append(j)
print("The even list",even)
print("The odd list",odd)
Program Explanation

1. User must enter the number of elements and store it in a variable.


2. User must then enter the elements of the list one by one using a for loop and
store it in a list.
3. Another for loop is used to traverse through the elements of the list.
4. The if statement checks if the element is even or odd and appends them to
separate lists.
5. Both the lists are printed.

Runtime Test Cases

Case 1:
Enter number of elements:5
Enter element:67
Enter element:43
Enter element:44
Enter element:22
Enter element:455
The even list [44, 22]
The odd list [67, 43, 455]

Case 2:

Notes on Python Programming By Prof.N.S.Raote


Enter number of elements:3
Enter element:23
Enter element:44
Enter element:99
The even list [44]
The odd list [23, 99]

Python Program to Merge Two Lists and Sort it

This is a Python Program to merge two lists and sort it.

Problem Description

The program takes two lists, merges them and sorts the merged list.

Problem Solution

1. Take in the number of elements for the first list and store it in a variable.
2. Take in the elements of the list one by one.
3. Similarly, take in the elements for the second list also.
4. Merge both the lists using the ‘+’ operator and then sort the list.
5. Display the elements in the sorted list.
6. Exit.

Program/Source Code

Here is source code of the Python Program to merge two lists and sort it. The
program output is also shown below.

a=[]
c=[]
n1=int(input("Enter number of elements:"))
for i in range(1,n1+1):
b=int(input("Enter element:"))
a.append(b)
n2=int(input("Enter number of elements:"))
for i in range(1,n2+1):
d=int(input("Enter element:"))
c.append(d)

Notes on Python Programming By Prof.N.S.Raote


new=a+c
new.sort()
print("Sorted list is:",new)
Program Explanation

1. User must enter the number of elements for the first list and store it in a variable.
2. User must then enter the elements of the list one by one using a for loop and
store it in a list.
3. User must similarly enter the elements of the second list one by one.
4. The ‘+’ operator is then used to merge both the lists.
5. The sort function then sorts the list in ascending order.
6. The sorted list is then printed.

Runtime Test Cases

Case 1:
Enter number of elements:4
Enter element:56
Enter element:43
Enter element:78
Enter element:12
('Second largest number is:', 56)

Case 2:
Enter the number of elements in list 1 : 0

Enter the number of elements in list 2 : 3

Enter element 1 : 12

Enter element 2 : 12

Enter element 3 : 12

The union is :

[12]

Notes on Python Programming By Prof.N.S.Raote


Python Program to Sort the List According to the Second Element in Sublist

This is a Python Program to sort the list according to the second element in the
sublist.

Problem Description

The program takes a list of lists and sorts the list according to the second element
in the sublist.

Problem Solution

1. Take in a list containing sublists.


2. Using two for loops, use bubble sort to sort the sublists based on the second
value of the sublist.
3. If the second element of the first sublist is greater than the second element of the
second sublist, exchange the entire sublist.
4. Print the sorted list.
5. Exit.

Program/Source Code

Here is source code of the Python Program to sort the list according to the second
element in the sublist. The program output is also shown below.

a=[['A',34],['B',21],['C',26]]
for i in range(0,len(a)):
for j in range(0,len(a)-i-1):
if(a[j][1]>a[j+1][1]):
temp=a[j]
a[j]=a[j+1]
a[j+1]=temp

print(a)
Program Explanation

Notes on Python Programming By Prof.N.S.Raote


1. User must enter a list containing several sublists.
2. Then bubble sort is implemented to sort the list according to the second element
in the sublist.
3. If the second element of the first sublist is greater than the second element of the
second sublist, then the entire sublist is switched.
4. This process continues till the entire list has been sorted.
5. The sorted list is then printed.

Runtime Test Cases

Case 1:
[['B', 21], ['C', 26], ['A', 34]]

STRING

Python Program to Replace all Occurrences of ‘a’ with $ in a String

This is a Python Program to replace all occurrences of ‘a’ with ‘$’ in a string.

Problem Description

The program takes a string and replaces all occurrences of ‘a’ with ‘$’.

Problem Solution

1. Take a string and store it in a variable.


2. Using the replace function, replace all occurrences of ‘a’ and ‘A’ with ‘$’ and
store it back in the variable.
3. Print the modified string.
4. Exit.

Program/Source Code

Here is source code of the Python Program to replace all occurrences of ‘a’ with
‘$’ in a string. The program output is also shown below.

string=raw_input("Enter string:")
string=string.replace('a','$')
Notes on Python Programming By Prof.N.S.Raote
string=string.replace('A','$')
print("Modified string:")
print(string)
Program Explanation

1. User must enter the string and store it in a variable.


2. The replace function replaces all occurrences of ‘a’ and ‘A’ with ‘$’ and store it
back in the variable.
3. The modified string is printed

Runtime Test Cases

Case 1:
Enter string:Apple
Modified string:
$pple

Case 2:
Enter string:Asia
Modified string:
$si$

Python Program to Remove the nth Index Character from a Non-Empty


String

This is a Python Program to remove the nth index character from a non-empty
string.

Problem Description

The program takes a string and removes the nth index character from the non-
empty string.

Problem Solution

1. Take a string from the user and store it in a variable.


2. Take the index of the character to remove.

Notes on Python Programming By Prof.N.S.Raote


3. Pass the string and the index as arguments to a function named remove.
4. In the function, the string should then be split into two halves before the index
character and after the index character.
5. These two halves should then be merged together.
6. Print the modified string.
7. Exit.

Program/Source Code

Here is source code of the Python Program to remove the nth index character from
a non-empty string. The program output is also shown below.

def remove(string, n):


first = string[:n]
last = string[n+1:]
return first + last
string=raw_input("Enter the sring:")
n=int(input("Enter the index of the character to remove:"))
print("Modified string:")
print(remove(string, n))
Program Explanation

1. User must enter a string and store it in a variable.


2. User must also enter the index of the character to remove.
3. The string and the index of the character to remove are passed as arguments to
the remove function.
4. In the function, the string is split into two halves before the index character and
after the index character.
5. The first half and the last half is then merged together using the ‘+’ operator.
6. The modified string is printed.

Runtime Test Cases

Case 1:
Enter the sring:Hello
Enter the index of the character to remove:3
Modified string:
Helo

Case 2:

Notes on Python Programming By Prof.N.S.Raote


Enter the sring:Checking
Enter the index of the character to remove:4
Modified string:
Checing

Python Program to Detect if Two Strings are Anagrams

This is a Python Program to detect if two strings are anagrams.

Problem Description

The program takes two strings and checks if the two strings are anagrams.

Problem Solution

1. Take two strings from the user and store them in separate variables.
2. Then use sorted() to sort both the strings into lists.
3. Compare the sorted lists and check if they are equal.
4. Print the final result.
5. Exit.

Program/Source Code

Here is source code of the Python Program to detect if two strings are anagrams.
The program output is also shown below.

s1=raw_input("Enter first string:")


s2=raw_input("Enter second string:")
if(sorted(s1)==sorted(s2)):
print("The strings are anagrams.")
else:
print("The strings aren't anagrams.")
Program Explanation

1. User must enter both the strings and store them in separate variables.
2. The characters of both the strings are sorted into separate lists.
3. They are then checked whether they are equal or not using an if statement.
4. If they are equal, they are anagrams as the characters are simply jumbled in
anagrams.

Notes on Python Programming By Prof.N.S.Raote


5. If they aren’t equal, the strings aren’t anagrams.
6. The final result is printed.

Runtime Test Cases

Case 1:
Enter first string:anagram
Enter second string:nagaram
The strings are anagrams.

Case 2:
Enter first string:hello
Enter second string:world
The strings aren't anagrams.

Python Program to Count the Number of Vowels in a String

This is a Python Program to count the number of vowels in a string.

Problem Description

The program takes a string and counts the number of vowels in a string.

Problem Solution

1. Take a string from the user and store it in a variable.


2. Initialize a count variable to 0.
3. Use a for loop to traverse through the characters in the string.
4. Use an if statement to check if the character is a vowel or not and increment the
count variable if it is a vowel.
5. Print the total number of vowels in the string.
6. Exit.

Program/Source Code

Here is source code of the Python Program to remove the nth index character from
a non-empty string. The program output is also shown below.

string=raw_input("Enter string:")

Notes on Python Programming By Prof.N.S.Raote


vowels=0
for i in string:
if(i=='a' or i=='e' or i=='i' or i=='o' or i=='u' or i=='A' or i=='E' or i=='I' or
i=='O' or i=='U'):
vowels=vowels+1
print("Number of vowels are:")
print(vowels)
Program Explanation

1. User must enter a string and store it in a variable.


2. The count variable is initialized to zero.
3. The for loop is used to traverse through the characters in the string.
4. An if statement checks if the character is a vowel or not.
5. The count is incremented each time a vowel is encountered.
6. The total count of vowels in the string is printed.

Runtime Test Cases

Case 1:
Enter string:Hello world
Number of vowels are:
3

Case 2:
Enter string:WELCOME
Number of vowels are:
3

Python Program to Take in a String and Replace Every Blank Space with
Hyphen

This is a Python Program to take a string and replace every blank space with a
hyphen.

Problem Description

The program takes a string and replaces every blank space with a hyphen.

Problem Solution
Notes on Python Programming By Prof.N.S.Raote
1. Take a string and store it in a variable.
2. Using the replace function, replace all occurrences of ‘ ‘ with ‘-‘ and store it
back in the variable.
3. Print the modified string.
4. Exit.

Program/Source Code

Here is source code of the Python Program to take a string and replace every blank
space with a hyphen. The program output is also shown below.

string=raw_input("Enter string:")
string=string.replace(' ','-')
print("Modified string:")
print(string)
Program Explanation

1. User must enter the string and store it in a variable.


2. The replace function replaces all occurrences of ‘ ‘ with ‘-‘ and store it back in
the same variable.
3. The modified string is printed.

Runtime Test Cases

Case 1:
Enter string:hello world
Modified string:
hello-world

Case 2:
Enter string:apple orange banana
Modified string:
apple-orange-banana

Python Program to Calculate the Length of a String Without Using a Library


Function

This is a Python Program to calculate the length of a string without using library
functions.

Notes on Python Programming By Prof.N.S.Raote


Problem Description

The program takes a string and calculates the length of the string without using
library functions.

Problem Solution

1. Take a string from the user and store it in a variable.


2. Initialize a count variable to 0.
3. Use a for loop to traverse through the characters in the string and increment the
count variable each time.
4. Print the total count of the variable.
5. Exit.

Program/Source Code

Here is source code of the Python Program to calculate the length of a string
without using library functions. The program output is also shown below.

string=raw_input("Enter string:")
count=0
for i in string:
count=count+1
print("Length of the string is:")
print(count)
Program Explanation

1. User must enter a string and store it in a variable.


2. The count variable is initialized to zero.
3. The for loop is used to traverse through the characters in the string.
4. The count is incremented each time a character is encountered.
5. The total count of characters in the string which is the length of the string is
printed.

Runtime Test Cases

Case 1:
Enter string:Hello
Length of the string is:
5

Notes on Python Programming By Prof.N.S.Raote


Case 2:
Enter string:Bangalore
Length of the string is:
9

DICTIONARY

Python Program to Add a Key-Value Pair to the Dictionary

This is a Python Program to add a key-value pair to a dictionary.

Problem Description

The program takes a key-value pair and adds it to the dictionary.

Problem Solution

1. Take a key-value pair from the user and store it in separate variables.
2. Declare a dictionary and initialize it to an empty dictionary.
3. Use the update() function to add the key-value pair to the dictionary.
4. Print the final dictionary.
5. Exit.

Program/Source Code

Here is source code of the Python Program to add a key-value pair to a dictionary.
The program output is also shown below.

key=int(input("Enter the key (int) to be added:"))


value=int(input("Enter the value for the key to be added:"))
d={}
d.update({key:value})
print("Updated dictionary is:")
print(d)
Program Explanation

1. User must enter a key-value pair and store it in separate variables.


2. A dictionary is declared and initialized to an empty dictionary.
3. The update() function is used to add the key-value pair to the dictionary.
4. The final dictionary is printed.

Notes on Python Programming By Prof.N.S.Raote


Runtime Test Cases

Case 1:
Enter the key (int) to be added:12
Enter the value for the key to be added:34
Updated dictionary is:
{12: 34}

Case 2:
Enter the key (int) to be added:34
Enter the value for the key to be added:29
Updated dictionary is:
{34: 29}

Python Program to Concatenate Two Dictionaries Into One

This is a Python Program to concatenate two dictionaries into one dictionary.

Problem Description

The program takes two dictionaries and concatenates them into one dictionary.

Problem Solution

1. Declare and initialize two dictionaries with some key-value pairs


2. Use the update() function to add the key-value pair from the second dictionary to
the first dictionary.
3. Print the final dictionary.
4. Exit.

Program/Source Code

Here is source code of the Python Program to add a key-value pair to a dictionary.
The program output is also shown below.

d1={'A':1,'B':2}
d2={'C':3}
d1.update(d2)
print("Concatenated dictionary is:")

Notes on Python Programming By Prof.N.S.Raote


print(d1)
Program Explanation

1. User must enter declare and initialize two dictionaries with a few key-value
pairs and store it in separate variables.
2. The update() function is used to add the key-value pair from the second to the
first dictionary.
3. The final updated dictionary is printed.

Runtime Test Cases

Case 1:
Concatenated dictionary is:
{'A': 1, 'C': 3, 'B': 2}

Python Program to Check if a Given Key Exists in a Dictionary or Not

This is a Python Program to check if a given key exists in a dictionary or not.

Problem Description

The program takes a dictionary and checks if a given key exists in a dictionary or
not.

Problem Solution

1. Declare and initialize a dictionary to have some key-value pairs.


2. Take a key from the user and store it in a variable.
3. Using an if statement and the in operator, check if the key is present in the
dictionary using the dictionary.keys() method.
4. If it is present, print the value of the key.
5. If it isn’t present, display that the key isn’t present in the dictionary.
6. Exit.

Program/Source Code

Here is source code of the Python Program to check if a given key exists in a
dictionary or not. The program output is also shown below.

Notes on Python Programming By Prof.N.S.Raote


d={'A':1,'B':2,'C':3}
key=raw_input("Enter key to check:")
if key in d.keys():
print("Key is present and value of the key is:")
print(d[key])
else:
print("Key isn't present!")
Program Explanation

1. User must enter the key to be checked and store it in a variable.


2. An if statement and the in operator is used check if the key is present in the list
containing the keys of the dictionary.
3. If it is present, the value of the key is printed.
4. If it isn’t present, “Key isn’t present!” is printed.
5. Exit.

Runtime Test Cases

Case 1:
Enter key to check:A
Key is present and value of the key is:
1

Case 2:
Enter key to check:F
Key isn't present!

Python Program to Generate a Dictionary that Contains Numbers (between 1


and n) in the Form (x,x*x).

This is a Python Program to generate a dictionary that contains numbers (between


1 and n) in the form (x,x*x).

Problem Description

The program takes a number from the user and generates a dictionary that contains
numbers (between 1 and n) in the form (x,x*x).

Problem Solution
Notes on Python Programming By Prof.N.S.Raote
1. Take a number from the user and store it in a separate variable.
2. Declare a dictionary and using dictionary comprehension initialize it to values
keeping the number between 1 to n as the key and the square of the number as their
values.
3. Print the final dictionary.
4. Exit.

Program/Source Code

Here is source code of the Python Program to generate a dictionary that contains
numbers (between 1 and n) in the form (x,x*x). The program output is also shown
below.

n=int(input("Enter a number:"))
d={x:x*x for x in range(1,n+1)}
print(d)
Program Explanation

1. User must enter a number and store it in a variable.


2. A dictionary is declared and initialized to values using dictionary
comprehension.
3. The numbers between 1 to n are kept as keys while the squares of the numbers
are made their values.
4. The final dictionary is printed.

Runtime Test Cases

Case 1:
Enter a number:5
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

Case 2:
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10: 100, 11: 121, 12: 144,
13: 169, 14: 196, 15: 225, 16: 256, 17: 289, 18: 324, 19: 361}

Notes on Python Programming By Prof.N.S.Raote


Python Program to Sum All the Items in a Dictionary

This is a Python Program to find the sum all the items in a dictionary.

Problem Description

The program takes a dictionary and prints the sum of all the items in the dictionary.

Problem Solution

1. Declare and initialize a dictionary to have some key-value pairs.


2. Find the sum of all the values in the dictionary.
3. Print the total sum.
4. Exit.

Program/Source Code

Here is source code of the Python Program to find the sum all the items in a
dictionary. The program output is also shown below.

d={'A':100,'B':540,'C':239}
print("Total sum of values in the dictionary:")
print(sum(d.values()))
Program Explanation

1. The sum() function is used to find the sum of all the values in the dictionary.
2. The total sum of all the values in the dictionary is printed.
3. Exit.

Runtime Test Cases

Case 1:
Total sum of values in the dictionary:
879

Python Program to Multiply All the Items in a Dictionary

Notes on Python Programming By Prof.N.S.Raote


This is a Python Program to multiply all the items in a dictionary.

Problem Description

The program takes a dictionary and multiplies all the items in the dictionary.

Problem Solution

1. Declare and initialize a dictionary to have some key-value pairs.


2. Initialize a variable that should contain the total multiplied value to 1.
3. Use the for loop to traverse through the values of the dictionary.
4. Then multiply all the values in the dictionary against each other.
5. Print the total multiplied value.
6. Exit.

Program/Source Code

Here is source code of the Python Program to multiply all the items in a dictionary.
The program output is also shown below.

d={'A':10,'B':10,'C':239}
tot=1
for i in d:
tot=tot*d[i]
print(tot)
Program Explanation

1. A dictionary is declared and initialized to have some key-value pairs.


2. The total variable is initialized to 1.
3. The for loop is used to traverse through the values of the dictionary.
4. Then all the values in the dictionary are multiplied against each other.
5. The total multiplied value is printed.

Runtime Test Cases

Case 1:
23900

Python Program to Remove the Given Key from a Dictionary

Notes on Python Programming By Prof.N.S.Raote


This is a Python Program to remove the given key from a dictionary.

Problem Description

The program takes a dictionary and removes a given key from the dictionary.

Problem Solution

1. Declare and initialize a dictionary to have some key-value pairs.


2. Take a key from the user and store it in a variable.
3. Using an if statement and the in operator, check if the key is present in the
dictionary.
4. If it is present, delete the key-value pair.
5. If it isn’t present, print that the key isn’t found and exit the program.
6. Exit.

Program/Source Code

Here is source code of the Python Program to remove the given key from a
dictionary. The program output is also shown below.

d = {'a':1,'b':2,'c':3,'d':4}
print("Initial dictionary")
print(d)
key=raw_input("Enter the key to delete(a-d):")
if key in d:
del d[key]
else:
print("Key not found!")
exit(0)
print("Updated dictionary")
print(d)
Program Explanation

1. User must enter the key to be checked and store it in a variable.


2. An if statement and the in operator is used check if the key is present in the
dictionary.
3. If it is present, the key-value pair is deleted.
4. If it isn’t present, “Key not found!” is printed and the program is exited.

Runtime Test Cases

Notes on Python Programming By Prof.N.S.Raote


Case 1:
Initial dictionary
{'a': 1, 'c': 3, 'b': 2, 'd': 4}
Enter the key to delete(a-d):c
Updated dictionary
{'a': 1, 'b': 2, 'd': 4}

Case 2:
Initial dictionary
{'a': 1, 'c': 3, 'b': 2, 'd': 4}
Enter the key to delete(a-d):g
Key not found!

SET

Python Program to Check Common Letters in Two Input Strings

This is a Python Program to check common letters in the two input strings.

Problem Description

The program takes two strings and checks common letters in both the strings.

Problem Solution

1. Enter two input strings and store it in separate variables.


2. Convert both of the strings into sets and find the common letters between both
the sets.
3. Store the common letters in a list.
4. Use a for loop to print the letters of the list.
5. Exit.

Program/Source Code

Here is source code of the Python Program to check common letters in the two
input strings. The program output is also shown below.

s1=raw_input("Enter first string:")


s2=raw_input("Enter second string:")

Notes on Python Programming By Prof.N.S.Raote


a=list(set(s1)&set(s2))
print("The common letters are:")
for i in a:
print(i)
Program Explanation

1. User must enter two input strings and store it in separate variables.
2. Both of the strings are converted into sets and the common letters between both
the sets are found using the ‘&’ operator.
3. These common letters are stored in a list.
4. A for loop is used to print the letters of the list.

Runtime Test Cases

Case 1:
Enter first string:Hello
Enter second string:How are you
The common letters are:
H
e
o

Case 2:
Enter first string:Test string
Enter second string:checking
The common letters are:
i
e
g
n

Python Program that Displays which Letters are in the First String but not in
the Second

This is a Python Program to display which letters are in the first string but not in
the second string.

Problem Description

The program takes two strings and displays which letters are in the first string but
not in the second string.
Notes on Python Programming By Prof.N.S.Raote
Problem Solution

1. Enter two input strings and store it in separate variables.


2. Convert both of the strings into sets and find which letters are present in the first
string but not in the second string.
3. Store the letters in a list.
4. Use a for loop to print the letters of the list.
5. Exit.

Program/Source Code

Here is source code of the Python Program to display which letters are in the first
string but not in the second string. The program output is also shown below.

s1=raw_input("Enter first string:")


s2=raw_input("Enter second string:")
a=list(set(s1)-set(s2))
print("The letters are:")
for i in a:
print(i)
Program Explanation

1. User must enter two input strings and store it in separate variables.
2. Both of the strings are converted into sets and the letters which are in the first
string but not in the second string are found using the ‘-‘ operator.
3. These letters are stored in a list.
4. A for loop is used to print the letters of the list.

Runtime Test Cases

Case 1:
Enter first string:Hello
Enter second string:world
The letters are:
H
e

Case 2:
Enter first string:Python
Enter second string:Programming language
The letters are:
Notes on Python Programming By Prof.N.S.Raote
y
h
t

Python Program that Displays which Letters are Present in Both the Strings

This is a Python Program to display which letters are present in both the strings.

Problem Description

The program takes two strings and displays which letters are present in both the
strings.

Problem Solution

1. Enter two input strings and store it in separate variables.


2. Convert both of the strings into sets and find the union between both the sets.
3. Store the letters in a list.
4. Use a for loop to print the letters of the list.
5. Exit.

Program/Source Code

Here is source code of the Python Program to display which letters are present in
both the strings. The program output is also shown below.

s1=raw_input("Enter first string:")


s2=raw_input("Enter second string:")
a=list(set(s1)|set(s2))
print("The letters are:")
for i in a:
print(i)
Program Explanation

1. User must enter two input strings and store it in separate variables.
2. Both of the strings are converted into sets and the union of both the sets are
found using the ‘|’ operator.
3. These letters are stored in a list.
4. A for loop is used to print the letters of the list.

Runtime Test Cases

Notes on Python Programming By Prof.N.S.Raote


Case 1:
Enter first string:hello
Enter second string:world
The letters are:
e
d
h
l
o
r
w

Case 2:
Enter first string:test
Enter second string:string
The letters are:
e
g
i
n
s
r
t

Python Program that Displays which Letters are in the Two Strings but not in
Both

This is a Python Program to display which letters are in the two strings but not in
both.

Problem Description

The program takes two strings and displays which letters are in the two strings but
not in both.

Problem Solution

1. Enter two input strings and store it in separate variables.


2. Convert both of the strings into sets and find which of the letters are in the two
Notes on Python Programming By Prof.N.S.Raote
strings but not in both.
3. Store the letters in a list.
4. Use a for loop to print the letters of the list.
5. Exit.

Program/Source Code

Here is source code of the Python Program to display which letters are in the two
strings but not in both. The program output is also shown below.

s1=raw_input("Enter first string:")


s2=raw_input("Enter second string:")
a=list(set(s1)^set(s2))
print("The letters are:")
for i in a:
print(i)
Program Explanation

1. User must enter two input strings and store it in separate variables.
2. Both of the strings are converted into sets and the letters which are present in the
two strings but not in both are found using the ‘^’ operator.
3. These letters are stored in a list.
4. A for loop is used to print the letters of the list.

Runtime Test Cases

Case 1:
Enter first string:hello
Enter second string:world
The letters are:
e
d
h
r
w

Case 2:
Enter first string:Test
Enter second string:string
The letters are:

Notes on Python Programming By Prof.N.S.Raote


r
e
g
i
T
n

RECURSION

Python Program to Determine Whether a Given Number is Even or Odd


Recursively

This is a Python Program to determine whether a given number is even or odd


recursively.

Problem Description

The program takes a number and determines whether a given number is even or
odd recursively.

Problem Solution

1. Take a number from the user and store it in a variable.


2. Pass the number as an argument to a recursive function.
3. Define the base condition as the number to be lesser than 2.
4. Otherwise call the function recursively with the number minus 2.
5. Then return the result and check if the number is even or odd.
6. Print the final result.
7. Exit.

Program/Source Code

Here is source code of the Python Program to determine whether a given number is
even or odd recursively. The program output is also shown below.

def check(n):
if (n < 2):
return (n % 2 == 0)
return (check(n - 2))
n=int(input("Enter number:"))

Notes on Python Programming By Prof.N.S.Raote


if(check(n)==True):
print("Number is even!")
else:
print("Number is odd!")
Program Explanation

1. User must enter a number and store it in a variable.


2. The number is passed as an argument to a recursive function.
3. The base condition is that the number has to be lesser than 2.
4. Otherwise the function is called recursively with the number minus 2.
5. The result is returned and an if statement is used to check if the number is odd or
even.
6. The final result is printed.

Runtime Test Cases

Case 1:
Enter number:124
Number is even!

Case 2:
Enter number:567
Number is odd!

Python Program to Determine How Many Times a Given Letter Occurs in a


String Recursively

This is a Python Program to determine how many times a given letter occurs in a
string recursively.

Problem Description

The program takes a string and determines how many times a given letter occurs in
a string recursively.

Problem Solution

Notes on Python Programming By Prof.N.S.Raote


1. Take a string and a character from the user and store it in different variables.
2. Pass the string and the characters as arguments to a recursive function.
3. Pass the base condition that the string isn’t empty.
4. Check if the first character of the string is equal to the character taken from the
user and if it is equal, increment the count.
5. Progress the string either wise and print the number of times the letter occurs in
the string.
6. Exit.

Program/Source Code

Here is source code of the Python Program to determine how many times a given
letter occurs in a string recursively. The program output is also shown below.

def check(string,ch):
if not string:
return 0
elif string[0]==ch:
return 1+check(string[1:],ch)
else:
return check(string[1:],ch)
string=raw_input("Enter string:")
ch=raw_input("Enter character to check:")
print("Count is:")
print(check(string,ch))
Program Explanation

1. User must enter a string and a character and store it in separate variables.
2. The string and the character is passed as arguments to the recursive function.
3. The base condition defined is that the string isn’t empty.
4. If the first character of the string is equal to the character taken from the user,
the count is incremented.
5. The string is progressed by passing it recursively back to the function.
6. The number of times the letter is encountered in the string is printed.

Runtime Test Cases

Case 1:
Enter string:abcdab
Enter character to check:b

Notes on Python Programming By Prof.N.S.Raote


Count is:
2

Case 2:
Enter string:hello world
Enter character to check:l
Count is:
3

Python Program to Find the Fibonacci Series Using Recursion

This is a Python Program to find the fibonacci series using recursion.

Problem Description

The program takes the number of terms and determines the fibonacci series using
recursion upto that term.

Problem Solution

1. Take the number of terms from the user and store it in a variable.
2. Pass the number as an argument to a recursive function named fibonacci.
3. Define the base condition as the number to be lesser than or equal to 1.
4. Otherwise call the function recursively with the argument as the number minus 1
added to the function called recursively with the argument as the number minus 2.
5. Use a for loop and print the returned value which is the fibonacci series.
6. Exit.

Program/Source Code

Here is source code of the Python Program to find the fibonacci series using
recursion. The program output is also shown below.

def fibonacci(n):
if(n <= 1):
return n
else:
return(fibonacci(n-1) + fibonacci(n-2))
n = int(input("Enter number of terms:"))

Notes on Python Programming By Prof.N.S.Raote


print("Fibonacci sequence:")
for i in range(n):
print fibonacci(i),
Program Explanation

1. User must enter the number of terms and store it in a variable.


2. The number is passed as an argument to a recursive function.
3. The base condition is that the number has to be lesser than or equal to 1.
4. Otherwise the function is called recursively with the argument as the number
minus 1 added to the function called recursively with the argument as the number
minus 2.
5. The result is returned and a for statement is used to print the fibonacci series.

Runtime Test Cases

Case 1:
Enter number of terms:5
Fibonacci sequence:
01123

Case 2:
Enter number of terms:7
Fibonacci sequence:
0112358

Python Program to Find the Factorial of a Number Using Recursion

This is a Python Program to find the factorial of a number using recursion.

Problem Description

The program takes a number and determines the factorial of the number using
recursion.

Problem Solution

1. Take a number from the user and store it in a variable.


2. Pass the number as an argument to a recursive factorial function.

Notes on Python Programming By Prof.N.S.Raote


3. Define the base condition as the number to be lesser than or equal to 1 and
return 1 if it is.
4. Otherwise call the function recursively with the number minus 1 multiplied by
the number itself.
5. Then return the result and print the factorial of the number.
6. Exit.

Program/Source Code

Here is source code of the Python Program to find the factorial of a number using
recursion. The program output is also shown below.

def factorial(n):
if(n <= 1):
return 1
else:
return(n*factorial(n-1))
n = int(input("Enter number:"))
print("Factorial:")
print(factorial(n))
Program Explanation

1. User must enter a number and store it in a variable.


2. The number is passed as an argument to a recursive factorial function.
3. The base condition is that the number has to be lesser than or equal to 1 and
return 1 if it is.
4. Otherwise the function is called recursively with the number minus 1 multiplied
by the number itself.
5. The result is returned and the factorial of the number is printed.

Runtime Test Cases

Case 1:
Enter number:5
Factorial:
120

Case 2:
Enter number:9
Factorial:

Notes on Python Programming By Prof.N.S.Raote


362880

Python Program to Find the Sum of Elements in a List Recursively

This is a Python Program to find the sum of elements in a list recursively.

Problem Description

The program takes a list and finds the sum of elements in a list recursively.

Problem Solution

1. Define a recursive function which takes an array and the size of the array as
arguments.
2. Declare an empty list and initialize it to an empty list.
3. Consider a for loop to accept values for the list.
4. Take the number of elements in the list and store it in a variable.
5. Accept the values into the list using another for loop and insert into the list.
6. Pass the list and the size of the list as arguments to the recursive function.
7. If the size of the list is zero, return 0.
8. Otherwise return the sum of the last element of the list along with the recursive
function call (with the size reduced by 1).
9. The returned value is stored in a variable and the final sum is printed.
9. Exit.

Program/Source Code

Here is source code of the Python Program to find the sum of elements in a list
recursively. The program output is also shown below.

def sum_arr(arr,size):
if (size == 0):
return 0
else:
return arr[size-1] + sum_arr(arr,size-1)
n=int(input("Enter the number of elements for list:"))
a=[]
for i in range(0,n):
element=int(input("Enter element:"))

Notes on Python Programming By Prof.N.S.Raote


a.append(element)
print("The list is:")
print(a)
print("Sum of items in list:")
b=sum_arr(a,n)
print(b)
Program Explanation

1. User must enter the number of elements in the list and store it in a variable.
2. User must enter the values to the same number of elements into the list.
3. The append function obtains each element from the user and adds the same to
the end of the list as many times as the number of elements taken.
4. The list and the size of the list are passed as arguments to a recursive function.
5. If the size of the function reduces to 0, 0 is returned.
6. Otherwise the sum of the last element of the list along with the recursive
function call (with the size reduced by 1) is returned.
7. The returned values are stored in a list and the sum of the elements in the list is
printed.

Runtime Test Cases

Case 1:
Enter the number of elements for list:3
Enter element:3
Enter element:56
Enter element:7
The list is:
[3, 56, 7]
Sum of items in list:
66

Case 2:
Enter the number of elements for list:5
Enter element:23
Enter element:45
Enter element:62
Enter element:10
Enter element:56
The list is:
[23, 45, 62, 10, 56]

Notes on Python Programming By Prof.N.S.Raote


Sum of items in list:
196

Python Program to Find the LCM of Two Numbers Using Recursion

This is a Python Program to find the LCM of two numbers using recursion.

Problem Description

The program takes two numbers and finds the LCM of two numbers using
recursion.

Problem Solution

1. Take two numbers from the user.


2. Initialize the multiple variable with the maximum value among two given
numbers.
3. Check whether the multiple variable clearly divides both the number or not.
4. If it does, then end the process and return the multiple as the LCM.
5. If multiple doesn’t clearly divides both given numbers then increment the
multiple by the max values among both the given numbers.
5. Return the multiple variable and print the LCM of the two variables.
6. Exit.

Program/Source Code

Here is source code of the Python Program to find the LCM of two numbers using
recursion. The program output is also shown below.

def lcm(a,b):
lcm.multiple=lcm.multiple+b
if((lcm.multiple % a == 0) and (lcm.multiple % b == 0)):
return lcm.multiple;
else:
lcm(a, b)
return lcm.multiple
lcm.multiple=0
a=int(input("Enter first number:"))
b=int(input("Enter second number:"))
if(a>b):
LCM=lcm(b,a)

Notes on Python Programming By Prof.N.S.Raote


else:
LCM=lcm(a,b)
print(LCM)
Program Explanation

1. User must take two numbers from the user.


2. The multiple variable are initialized with the maximum value among two given
numbers.
3. The multiple variable is checked if clearly divides both the numbers or not.
4. If it does, then the process is ended and the multiple is returned as the LCM.
5. If multiple doesn’t clearly divides both given numbers then the multiple variable
is returned by the max values among both the given numbers.
5. The multiple variable is returned and the LCM of the two variables is printed.

Runtime Test Cases

Case 1:
Enter first number:126
Enter second number:12
LCM is:
252

Case 2:
Enter first number:25
Enter second number:5
LCM is:
25

Python Program to Find the GCD of Two Numbers Using Recursion

This is a Python Program to find the GCD of two numbers using recursion.

Problem Description

The program takes two numbers and finds the GCD of two numbers using
recursion.

Problem Solution
Notes on Python Programming By Prof.N.S.Raote
1. Take two numbers from the user.
2. Pass the two numbers as arguments to a recursive function.
3. When the second number becomes 0, return the first number.
4. Else recursively call the function with the arguments as the second number and
the remainder when the first number is divided by the second number.
5. Return the first number which is the GCD of the two numbers.
6. Print the GCD.
7. Exit.

Program/Source Code

Here is source code of the Python Program to find the GCD of two numbers using
recursion. The program output is also shown below.

def gcd(a,b):
if(b==0):
return a
else:
return gcd(b,a%b)
a=int(input("Enter first number:"))
b=int(input("Enter second number:"))
GCD=gcd(a,b)
print("GCD is: ")
print(GCD)
Program Explanation

1. User must enter two numbers.


2. The two numbers are passed as arguments to a recursive function.
3. When the second number becomes 0, the first number is returned.
4. Else the function is recursively called with the arguments as the second number
and the remainder when the first number is divided by the second number.
5. The first number is then returned which is the GCD of the two numbers.
6. The GCD is then printed.

Runtime Test Cases

Case 1:
Enter first number:5
Enter second number:15
GCD is:

Notes on Python Programming By Prof.N.S.Raote


5

Case 2:
Enter first number:30
Enter second number:12
GCD is:
6

Python Program to Find if a Number is Prime or Not Prime Using Recursion

This is a Python Program to find if a number is prime or not using recursion.

Problem Description

The program takes a number and finds if the number is prime or not using
recursion.

Problem Solution

1. Take a number from the user.


2. Pass the number as an argument to a recursive function and initialize the divisor
count to NULL.
3. Then check the number of divisors of the number using recursion and either
True or False is returned.
4. The final result is printed.
5. Exit.

Program/Source Code

Here is source code of the Python Program to find if a number is prime or not
using recursion. The program output is also shown below.

def check(n, div = None):


if div is None:
div = n - 1
while div >= 2:
if n % div == 0:
print("Number not prime")
return False

Notes on Python Programming By Prof.N.S.Raote


else:
return check(n, div-1)
else:
print("Number is prime")
return 'True'
n=int(input("Enter number: "))
check(n)
Program Explanation

1. User must enter a number.


2. The number is passed as an argument to a recursive function and the divisor
count is initialized to NULL.
3. The divisor is initialized to the number minus 1.
4. The number of divisors of the number is checked using recursion and either True
or False is returned.
5. Final result is printed.

Runtime Test Cases

Case 1:
Enter number: 13
Number is prime

Case 2:
Enter number: 30
Number not prime

Python Program to Find the Product of two Numbers Using Recursion

This is a Python Program to find the product of two numbers using recursion.

Problem Description

The program takes two numbers and finds the product of two numbers using
recursion.

Problem Solution

Notes on Python Programming By Prof.N.S.Raote


1. Take two numbers from the user.
2. Pass the numbers as arguments to a recursive function to find the product of the
two numbers.
3. Give the base condition that if the first number is lesser than the second,
recursively call the function with the arguments as the numbers interchanged.
4. If the second number isn’t equal to 0, again call the function recursively, else
return 0.
5. Print the final product of the two numbers.
6. Exit.

Program/Source Code

Here is source code of the Python Program to find the binary equivalent of a
number using recursion. The program output is also shown below.

def product(a,b):
if(a<b):
return product(b,a)
elif(b!=0):
return(a+product(a,b-1))
else:
return 0
a=int(input("Enter first number: "))
b=int(input("Enter second number: "))
print("Product is: ",product(a,b))
Program Explanation

1. User must enter two numbers.


2. The two numbers are passed as arguments to a recursive function to find the
product of the two numbers.
3. The base condition that if the first number is lesser than the second, the function
is recursively called with the arguments as the numbers interchanged.
4. If the second number isn’t equal to 0, the function is called recursively, else 0 is
returned.
5. The final product of the two numbers is printed.

Runtime Test Cases

Case 1:
Enter first number: 12

Notes on Python Programming By Prof.N.S.Raote


Enter second number: 10
Product is: 120

Case 2:
Enter first number: 12
Enter second number: 11
Product is: 132

Python Program to Find the Power of a Number Using Recursion

This is a Python Program to find the power of a number using recursion.

Problem Description

The program takes a base and a power and finds the power of the base using
recursion.

Problem Solution

1. Take the base and exponential value from the user.


2. Pass the numbers as arguments to a recursive function to find the power of the
number.
3. Give the base condition that if the exponential power is equal to 1, return the
base number.
4. If the exponential power isn’t equal to 1, return the base number multiplied with
the power function called recursively with the arguments as the base and power
minus 1.
5. Print the final result.
6. Exit.

Program/Source Code

Here is source code of the Python Program to find the power of a number using
recursion. The program output is also shown below.

def power(base,exp):
if(exp==1):
return(base)
if(exp!=1):
return(base*power(base,exp-1))
base=int(input("Enter base: "))

Notes on Python Programming By Prof.N.S.Raote


exp=int(input("Enter exponential value: "))
print("Result:",power(base,exp))
Program Explanation

1. User must enter the base and exponential value.


2. The numbers are passed as arguments to a recursive function to find the power
of the number.
3. The base condition is given that if the exponential power is equal to 1, the base
number is returned.
4. If the exponential power isn’t equal to 1, the base number multiplied with the
power function is called recursively with the arguments as the base and power
minus 1.
5. The final result is printed.

Runtime Test Cases

Case 1:
Enter base: 2
Enter exponential value: 5
Result: 32

Case 2:
Enter base: 5
Enter exponential value: 3
Result: 125

Notes on Python Programming By Prof.N.S.Raote

You might also like