Python NSR Notes
Python NSR Notes
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
a=1+2+3+\
4+5+6+\
7+8+9
a = (1 + 2 + 3 +
4+5+6+
7 + 8 + 9)
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
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.
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.
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:
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
def double(num):
return 2*num
>>> print(double.__doc__)
Function to double the value
Python Variables
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"
Multiple assignments
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"
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
a = 2.0
a = 1+2j
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
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 [ ].
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
>>> a = [1,2,3]
>>> a[2]=4
Python Tuple
Tuples are used to write-protect data and are usually faster than list as it cannot
change dynamically.
We can use the slicing operator [] to extract items but we cannot change its value.
t = (5,'program', 1+3j)
# t[1] = 'program'
# Generates error
t[0] = 10
Python Strings
s = 'Hello world!'
# s[4] = 'o'
# s[6:11] = 'world'
# Generates error
s[5] ='d'
Python Set
a = {5,2,3,1,4}
print("a = ", 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}
>>> 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
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))
# Generates error
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
>>> 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'
>>> set([1,2,3])
{1, 2, 3}
>>> tuple({5,6,7})
(5, 6, 7)
>>> list('hello')
['h', 'e', 'l', 'l', 'o']
>>> dict([[1,2],[3,4]])
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.
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.
a=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.
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).
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])
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.
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:
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.
Arithmetic operators
x = 15
y=4
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)
x + y = 19
x - y = 11
Comparison operators
Comparison operators are used to compare values. It either returns True or False
according to the condition.
x = 10
y = 12
print('x == y is',x==y)
# Output: x != y is True
print('x != y is',x!=y)
Logical operators
x = True
y = False
Notes on Python Programming By Prof.N.S.Raote
# Output: x and y is False
# Output: x or y is True
print('x or y is',x or y)
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.
In the table below: Let x = 10 (0000 1010 in binary) and y = 4 (0000 0100 in
binary)
Assignment operators
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.
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.
x1 = 5
y1 = 5
x2 = 'Hello'
y2 = 'Hello'
x3 = [1,2,3]
y3 = [1,2,3]
# Output: False
# 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).
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.
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.
if test expression:
statement(s)
Here, the program evaluates the test expression and will execute statement(s) only
if the text expression is True.
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.
num = 3
if num > 0:
if num > 0:
3 is a positive number
This is always printed
This is also always printed.
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.
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.
num = 3
# 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:
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.
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,
num = 3.4
# num = 0
# num = -4.5
if num > 0:
print("Positive number")
elif num == 0:
else:
print("Negative number")
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.
Output 1
Output 2
Enter a number: -1
Negative number
Output 3
Enter a number: 0
Zero
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.
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.
# List of numbers
sum = 0
sum = sum+val
The sum is 48
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().
# 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)))
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.
for i in range(len(genre)):
I like pop
I like rock
I like jazz
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.
digits = [0, 1, 5]
for i in digits:
print(i)
else:
0
1
5
No items left.
No items left.
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.
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.
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.
# numbers upto
# sum = 1+2+3+...+n
# n = int(input("Enter n: "))
n = 10
sum = 0
i=1
sum = sum + i
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).
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.
# Example to illustrate
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.
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.
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.
if val == "i":
break
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.
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
if val == "i":
continue
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
Functions help break our program into smaller and modular chunks. As our
program grows larger and larger, functions make it more organized and
manageable.
Syntax of Function
def function_name(parameters):
"""docstring"""
statement(s)
Example of a function
def greet(name):
parameter"""
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.
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 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
Example of return
def absolute_value(num):
Notes on Python Programming By Prof.N.S.Raote
"""This function returns the absolute
if num >= 0:
return num
else:
return -num
# Output: 2
print(absolute_value(2))
# Output: 4
print(absolute_value(-4))
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.
def my_func():
x = 10
my_func()
Output
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
Python Recursion
A physical world example would be to place two parallel mirrors facing each
other. Any object in between them would be reflected recursively.
We know that in Python, a function can call other functions. It is even possible for
the function to call itself. These type of construct are termed as recursive functions.
Factorial of a number is the product of all the integers from 1 to that number. For
example, the factorial of 6 (denoted as 6!) is 1*2*3*4*5*6 = 720.
def calc_factorial(x):
if x == 1:
return 1
else:
return (x * calc_factorial(x-1))
num = 4
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.
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
Disadvantages of recursion
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.
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.
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.
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.
>>> example.add(4,5.5)
9.5
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.
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 math
import math as m
Note that the name math is not recognized in our scope. Hence, math.pi is invalid,
m.pi is the correct implementation.
We can import specific names form a module without importing the module as a
whole. Here is an example.
In such case we don't use the dot operator. We could have imported multiple
attributes as follows.
We can import all names(definitions) form a module using the following construct.
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.
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.
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.
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.
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__',
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.
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']
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]
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']]
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.
# Output: p
print(my_list[0])
# Output: o
print(my_list[2])
# Output: e
print(my_list[4])
# my_list[4.0]
# Nested List
# Nested indexing
# Output: a
print(n_list[0][1])
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])
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']
print(my_list[2:5])
print(my_list[:-5])
print(my_list[5:])
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.
List are mutable, meaning, their elements can be changed unlike string or tuple.
# mistake values
odd = [2, 4, 6, 8]
odd[0] = 1
# Output: [1, 4, 6, 8]
print(odd)
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)
We can also use + operator to combine two lists. This is also called concatenation.
odd = [1, 3, 5]
# Output: [1, 3, 5, 9, 7, 5]
print(odd + [9, 7, 5])
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)
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']
del my_list[2]
print(my_list)
del my_list[1:5]
print(my_list)
del my_list
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).
my_list = ['p','r','o','b','l','e','m']
my_list.remove('p')
print(my_list)
# Output: 'o'
print(my_list.pop(1))
print(my_list)
# Output: 'm'
print(my_list.pop())
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.
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.
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 is an elegant and concise way to create new list from an
existing list in Python.
Here is an example to make a list with each item being increasing power of 2.
print(pow2)
pow2 = []
for x in range(10):
pow2.append(2 ** x)
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
Built-in functions like all(), any(), enumerate(), len(), max(), min(), list(), sorted()
etc. are commonly used with list to perform different tasks.
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.
sorted() Return a new sorted list (does not sort the list itself).
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)
# Output: (1, 2, 3)
my_tuple = (1, 2, 3)
print(my_tuple)
print(my_tuple)
# nested tuple
print(my_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.
my_tuple = ('p','e','r','m','i','t')
# Output: 'p'
print(my_tuple[0])
# Output: 't'
print(my_tuple[5])
#print(my_tuple[6])
# nested tuple
# nested index
# Output: 's'
print(n_tuple[0][3])
# nested index
# Output: 4
print(n_tuple[1][1])
p
t
s
4
2. Negative Indexing
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])
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')
print(my_tuple[1:4])
print(my_tuple[:-7])
print(my_tuple[7:])
# Output: ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')
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
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.
#my_tuple[1] = 9
my_tuple[3][0] = 9
print(my_tuple)
# 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.
# Concatenation
# Output: (1, 2, 3, 4, 5, 6)
# 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.
my_tuple = ('p','r','o','g','r','a','m','i','z')
#del my_tuple[3]
del my_tuple
my_tuple
Methods that add items or remove items are not available with tuple. Only the
following two methods are available.
Method Description
my_tuple = ('a','p','p','l','e',)
# Output: 2
print(my_tuple.count('p'))
# Index
# Output: 3
print(my_tuple.index('l'))
Built-in functions like all(), any(), enumerate(), len(), max(), min(), sorted(),
tuple() etc. are commonly used with tuple to perform different tasks.
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.
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.
my_string = 'Hello'
print(my_string)
my_string = "Hello"
print(my_string)
print(my_string)
print(my_string)
Hello
Hello
Hello
Hello, welcome to
the world of Python
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.
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'
#last character
If we try to access index out of the range or use decimal number, we will get
errors.
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.
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.
We cannot delete or remove characters from a string. But deleting the string
entirely is possible using the keyword del.
There are many operations that can be performed with string which makes it one of
the most used datatypes in Python.
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 +
# using *
Writing two string literals together also concatenates them like + operator.
Using for loop we can iterate through a string. Here is an example to count the
number of 'l' in a string.
if(letter == 'l'):
count += 1
print(count,'letters found')
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.
str = 'cold'
# enumerate()
list_enumerate = list(enumerate(str))
#character count
# default(implicit) order
print(default_order)
print(positional_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.
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.
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)
print(my_set)
# Output: {1, 2, 3, 4}
my_set = {1,2,3,4,3,2}
print(my_set)
# Output: {1, 2, 3}
my_set = set([1,2,3,2])
print(my_set)
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 = {}
print(type(a))
a = set()
print(type(a))
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)
#my_set[0]
# add an element
my_set.add(2)
print(my_set)
# Output: {1, 2, 3, 4}
my_set.update([2,3,4])
print(my_set)
# Output: {1, 2, 3, 4, 5, 6, 8}
my_set.update([4,5], {1,6,8})
print(my_set)
{1, 3}
{1, 2, 3}
{1, 2, 3, 4}
{1, 2, 3, 4, 5, 6, 8}
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.
# initialize my_set
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
# Output: {1, 3, 5}
my_set.discard(2)
print(my_set)
# remove an element
# 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.
# initialize my_set
my_set = set("HelloWorld")
print(my_set)
# pop an element
print(my_set.pop())
my_set.pop()
print(my_set)
#Output: set()
my_set.clear()
print(my_set)
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 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)
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}
# Output: {4, 5}
print(A & B)
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
B = {4, 5, 6, 7, 8}
# use - operator on A
# Output: {1, 2, 3}
print(A - B)
# use - operator on B
>>> B - A
{8, 6, 7}
Method Description
intersection_update() Update the set with the intersection of itself and another
Remove and return an arbitary set element. Raise KeyError if the set
pop()
is empty
symmetric_difference_update() Update a set with the symmetric difference of itself and another
Built-in functions like all(), any(), enumerate(), len(), max(), min(), sorted(), sum() etc.
are commonly used with set to perform different tasks.
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.
sorted() Return a new sorted list from elements in the set(does not sort the set itself).
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.
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 = {}
# using dict()
my_dict = dict({1:'apple', 2:'ball'})
As you can see above, we can also create a dictionary using the built-in function dict().
The difference while using get() is that it returns None instead of KeyError, if the key is not
found.
print(my_dict['name'])
# Output: 26
print(my_dict.get('age'))
# my_dict.get('address')
# my_dict['address']
Jack
26
If the key is already present, value gets updated, else a new key: value pair is added to the
dictionary.
# update value
my_dict['age'] = 27
# add item
my_dict['address'] = 'Downtown'
print(my_dict)
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))
print(squares)
# Output: (1, 1)
print(squares.popitem())
print(squares)
del squares[5]
# Output: {2: 4, 3: 9}
print(squares)
squares.clear()
# Output: {}
print(squares)
del squares
# Throws Error
# print(squares)
Method Description
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).
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.
marks = {}.fromkeys(['Math','English','Science'], 0)
print(marks)
print(item)
list(sorted(marks.keys()))
for i in squares:
print(squares[i])
Built-in functions like all(), any(), len(), cmp(), sorted() etc. are commonly used with
dictionary to perform different tasks.
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.
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))
Problem Description
The program takes a list and prints the largest number in the list.
Problem Solution
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
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
Problem Description
The program takes a list and prints the second largest number in the list.
Problem Solution
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=[]
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
Program/Source Code
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
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:
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)
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.
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 element 1 : 12
Enter element 2 : 12
Enter element 3 : 12
The union is :
[12]
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
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
Case 1:
[['B', 21], ['C', 26], ['A', 34]]
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
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
Case 1:
Enter string:Apple
Modified string:
$pple
Case 2:
Enter string:Asia
Modified string:
$si$
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
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.
Case 1:
Enter the sring:Hello
Enter the index of the character to remove:3
Modified string:
Helo
Case 2:
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.
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.
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.
Problem Description
The program takes a string and counts the number of vowels in a string.
Problem Solution
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:")
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
Case 1:
Enter string:hello world
Modified string:
hello-world
Case 2:
Enter string:apple orange banana
Modified string:
apple-orange-banana
This is a Python Program to calculate the length of a string without using library
functions.
The program takes a string and calculates the length of the string without using
library functions.
Problem Solution
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
Case 1:
Enter string:Hello
Length of the string is:
5
DICTIONARY
Problem Description
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.
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}
Problem Description
The program takes two dictionaries and concatenates them into one dictionary.
Problem Solution
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:")
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.
Case 1:
Concatenated dictionary is:
{'A': 1, 'C': 3, 'B': 2}
Problem Description
The program takes a dictionary and checks if a given key exists in a dictionary or
not.
Problem Solution
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.
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!
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
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}
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
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.
Case 1:
Total sum of values in the dictionary:
879
Problem Description
The program takes a dictionary and multiplies all the items in the dictionary.
Problem Solution
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
Case 1:
23900
Problem Description
The program takes a dictionary and removes a given key from the dictionary.
Problem Solution
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
Case 2:
Initial dictionary
{'a': 1, 'c': 3, 'b': 2, 'd': 4}
Enter the key to delete(a-d):g
Key not found!
SET
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
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.
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.
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
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.
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.
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
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.
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.
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
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.
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.
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:
RECURSION
Problem Description
The program takes a number and determines whether a given number is even or
odd recursively.
Problem Solution
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:"))
Case 1:
Enter number:124
Number is even!
Case 2:
Enter number:567
Number is odd!
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
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.
Case 1:
Enter string:abcdab
Enter character to check:b
Case 2:
Enter string:hello world
Enter character to check:l
Count is:
3
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:"))
Case 1:
Enter number of terms:5
Fibonacci sequence:
01123
Case 2:
Enter number of terms:7
Fibonacci sequence:
0112358
Problem Description
The program takes a number and determines the factorial of the number using
recursion.
Problem Solution
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
Case 1:
Enter number:5
Factorial:
120
Case 2:
Enter number:9
Factorial:
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:"))
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.
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]
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
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)
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
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
Case 1:
Enter first number:5
Enter second number:15
GCD is:
Case 2:
Enter first number:30
Enter second number:12
GCD is:
6
Problem Description
The program takes a number and finds if the number is prime or not using
recursion.
Problem Solution
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.
Case 1:
Enter number: 13
Number is prime
Case 2:
Enter number: 30
Number not prime
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
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
Case 1:
Enter first number: 12
Case 2:
Enter first number: 12
Enter second number: 11
Product is: 132
Problem Description
The program takes a base and a power and finds the power of the base using
recursion.
Problem Solution
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: "))
Case 1:
Enter base: 2
Enter exponential value: 5
Result: 32
Case 2:
Enter base: 5
Enter exponential value: 3
Result: 125