Module1-8 9 19
Module1-8 9 19
Introduction to Python: Features of Python, How to run Python, identifiers, reserved keywords,
variables, input, output & import functions, operators
Data types: numbers, strings, list, tuple, set, dictionary, data type conversions.
Decision making, loops, nested loops, control statements, types of loops. (8 hrs)
Applications:
Page 1
Module I RLMCA369 - Elective II- Python Programming
5 Scalable:
Python provides a better structure & support for large programs than shell scripting, it can
be used as a scripting language or can be compiled to bytecode (intermediate code ie,
platform independent) for building large applications.
6 Extendable:
You can add low level modules to the python interpreter. These modules enable programmers
to add to or customize their tools to be more efficient. It can be easily integrated with C,
C++, COM, ActiveX, CORBA & Java.
7 Dynamic:
Python provides very high level dynamic data types & supports dynamic type checking. It
also supports automatic garbage collection.
9 Graphical user interfaces (GUI)Programming & Databases:
Python GUI applications that can be created & ported to many libraries & windows
systems, such as Windows Microsoft Foundation Classes(MFC) Macintosh & the X
Window system of Unix. Python also provides interfaces to all major commercial databases.
X is used in networks of interconnected mainframes, minicomputers, workstations, and X Terminals.
X window system consists of a number of interacting components
X server: Manages the display & input hardware
Windows manager: Is the client application that manages client windows. It controls the general operations of the window system like geom
10 Broad Standard Library:
Python’s library is portable & cross platform compatible on Windows, Linux, Unix &
Macintosh. This helps in the support & development of a wide range of applications from
simple text processing to browsers & complex games.
How to run Python
Python is an interpreted language i.e. interpreter executes the code line by line at a time.
There are 3different ways to start Python.
➢ Interactive interpreter
➢ Script from the command line
➢ Integrated Development Environment
➢ Using interactive interpreter
You can start Python from UNIX, DOS or any other system that provides you a command-line
interpreter or shell window. Get into the command line of python.
• For Unix/Linux, you can get into interactive mode by typing $python or python%
• For Windows /Dos it is C:>python
>>> print( “Programming in Python”)
Programming in Python
>>>1+1
2
>>>
➢ Script from the Command Line
This method invokes the interpreter with a script parameter which begins the execution of the
script & continues until the script is finished. When the script is finished, the interpreter is no
longer active. A python script can be executed at command line by invoking the interpreter on
your application, a s follows:
For Unix/ Linux,
Page 2
Module I RLMCA369 - Elective II- Python Programming
$ python script1.py or python% script1.py
For windows/Dos,
Let us write a simple Python program in a script. Python files have extension .py.
Type the following source code in a first.py file.
print “Programming in Python”
To run this program as follows,
$ python first.py
o/p
Programming in Python
➢ Integrated Development Environment (IDE)
You can run Python from a Graphical User Interface (GUI) environment as well, if you have a
GUI application on your system that supports Python. IDLE (Integrated Development Learning
Environment) is the IDE for UNIX, LINUX, Windows or DOS.
Identifiers
A Python identifier is a name used to identify a variable, function, class, module or any
other object. Python is a case sensitive programming language.
Naming conventions for Python identifiers-
• Identifiers can be a combination of letters in lowercase (a to z) or uppercase (A to Z) or
digits (0 to 9) or an underscore (_).
• Reserved keywords cannot be used as an identifier.
• Identifiers cannot begin with a digit.
• Class names start with an uppercase letter. All other identifiers start with a lowercase
letter.
• Starting an identifier with a single leading underscore (eg: _abcd) indicates that the
identifier is private.
• Starting an identifier with 2 leading underscores (eg: _ _abcd) indicates a strong private
identifier.
• If the identifier also ends with 2 trailing underscores (abcd_ _), the identifier is a
language defined special name.
Reserved keywords
Keywords are the reserved words in Python. We cannot use a keyword as variable
name, function name or any other identifier. All the Python keywords contain lowercase letters
only. There are 33 keywords in Python 3.3. This number can vary slightly in course of time. All
the keywords except True, False and None are in lowercase and they must be written as it is.
Page 3
Module I RLMCA369 - Elective II- Python Programming
# display all keywords
>>> import keyword
>>> print(keyword.kwlist)
Variables
Variables are reserved memory locations to store values based on the data type of a
variable. The interpreter allocates memory & decides what can be stored in the reserved
memory. Therefore, by assigning different data types to variables, we can store integers, decimals
or characters in these variables.
• Python variables do not need explicit declaration to reserve memory space.
• The equal sign (=) is used to assign values to variables.
• The operand to the left of the = operator is the name of the variable.
• The operand to the right of the = operator is the value stored in the variable.
• To assign a single value to several variables simultaneously.
➢ Eg: a=b=c=1
❖ Here, an integer object is created with the value 1, & all 3 variables are
assigned to the same memory location.
• We can also assign multiple objects to multiple variables.
➢ Eg: a, b, c=1, 2,”Sonu”
❖ Here, 2 integer objects with values 1 & 2 are assigned to variables a & b
respectively, & 1 string object with the value “Sonu” is assigned to the
variable c.
1 >>> str = “sheena jabbar” assigns the string “sheena jabbar” to a new variable named
sheena jabbar str
2 >>> n = 17 Gives the integer 17 to n
17
3 >>> pi = 3.14159 Gives the floating point number 3.14159 to pi.
3.14159
• Programmers generally choose names for their variables that are meaningful.
• Variable names can be by chance long.
• They can contain both letters and numbers, but they have to begin with a letter.
• It is legal to use uppercase letters, but it is a good idea to begin variable names with a
lowercase letter.
• The underscore character (_) can appear in a name. It is often used in names with
multiple words, eg: my_name = 7.
Comments
• Comments are for programmers for better understanding of a program.
• Python Interpreter ignores comment.
Page 4
Module I RLMCA369 - Elective II- Python Programming
Multi-line comments
• To use hash (#) in the beginning of each line
or
• To use triple quotes, either ``` ``` or “ ” ” ”””
Eg:
#This is also a """This is also a ‘ ‘ ‘ This is also a
#perfect example of perfect example of perfect example of
#multi-line comments multi-line comments""" multi-line comments ‘ ‘ ‘
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 & ends with the
1st unindented line.
• The amount of indentation can be decided by the programmer, but it must be consistent
throughout the block.
• Generally 4 whitespaces are used indentation & is preferred over tab.
Eg:
if True: if True:
print “Correct” print “Answer”
else: print “Correct”
print “wrong” else:
print “Answer”
print “wrong”
Statements
Instructions that a Python interpreter can execute are called statements.
Eg: a = 1 is an assignment statement.
• Multi-line statement
• Multiple statement group (Suite)
• 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 (\).
Eg:
>>> a = 1 + 2 + 3 + \
4+5+6+\
7+8+9
>>> print (a)
45
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 + >>> colors = ['red',
4+5+6+ 'blue',
7 + 8 + 9) 'green']
Page 5
Module I RLMCA369 - Elective II- Python Programming
>>> print (a) >>> print (colors)
45 ['red', 'blue', 'green']
Here, the surrounding parentheses ( ) do the line continuation implicitly.
Same is the case with [ ] & { }.
• Multiple statement group (Suite)
➢ A group of individual statements, which make a single code block is called a suite.
➢ Compound or complex statements, such as if, while, def & class require a header line &
a suite.
➢ Header lines begin the statement (with the keyword) & terminate with a colon (:) &
followed by one or more lines which make up the suite.
if expression:
suite
elif expression:
else:
suite
We could also put multiple statements in a single line using semicolons.
Eg:
>>> a = 1; b = 2; c = 3
>>> print(a,b,c)
123
Quotes in Python
Python accepts single (‘), double (“) & triple(“”” or ‘’’) quotes to denote string literals.
• The same type of quote should be used to start & end the string.
• The triple quotes are used to span the string across multiple lines.
str=’ilahia’
sentence = “Ilahia college of Engineeing”
multi = “ ” ”Ilahia college of Engineeing and
Technology, Mulavoor” ” ”
Input, output and Import functions
Page 6
Module I RLMCA369 - Elective II- Python Programming
print (‘welcome to 1 program ’)
st
output
a= 20 run → run module/ F5
print(‘age :’,a) welcome to 1st program
age :20
Syntax,
Import function
When the program grows bigger or when there are segments of code that is frequently
used, it can be stored in different modules.
• A module is a file containing Python definitions & statements.
Page 7
Module I RLMCA369 - Elective II- Python Programming
• Python modules have a filename & 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.
Eg: we can import the math module by typing in import math.
import math
print(math.pi)
output
3.141592653589793
Operators
• Operators are the constructs which can manipulate the value of operands.
• Consider the expression c = a + b. Here, a, b and c are called operands and + , = are
called operators.
The following are the types of operators
• Arithmetic Operators • Special operators
• Assignment Operators ➢ Membership Operators
• Bitwise Operators ➢ Identity Operators
• Comparison (Relational) Operators
• Logical (Boolean) Operators
• Arithmetic Operators
➢ Arithmetic operators are used for performing basic arithmetic operations.
a=10 & b=20
Operator Operation Description Example
// Floor Division ➢ The division of operands where the result is the 9//2 = 4
(integer quotient in which the digits after the decimal 9.0//2.0 =
division) point are removed. 4.0
➢ If one of the operands is -ve, the result is
Page 8
Module I RLMCA369 - Elective II- Python Programming
floored, i.e., rounded away from zero (towards -11//3 = -4,
negative infinity) -11.0//3
= -4.0
x = 15, y = 4
print('x + y =', x+y) x + y = 19
print('x / y =',x/y) x / y = 3.75
print('x // y =',x//y) #floor division x // y = 3
print('x ** y =',x**y) #exponent x ** y = 50625
> If the value of left operand is greater than the value of right 10>20
operand, then condition becomes true. (a > b) is
not true.
< If the value of left operand is less than the value of right 10<20
operand, then condition becomes true. (a < b) is
true.
>= If the value of left operand is greater than or equal to the 10>=20
value of right operand, then condition becomes true. (a >= b)
is not
true.
<= If the value of left operand is less than or equal to the value 10<=20
of right operand, then condition becomes true. (a <= b)
is true.
x = 10
y = 12
print('x > y is', x>y) x > y is False
print('x < y is', x<y) x < y is True
Page 9
Module I RLMCA369 - Elective II- Python Programming
• Assignment Operators
Various shorthand operators for addition, subtraction, multiplication, division, modulus, exponent
& floor division are also supported by python.
Eg: x= 5 , y= 20
Operator Description Example
Page 10
Module I RLMCA369 - Elective II- Python Programming
effect of ‘flipping’ bits
• Logical Operators
➢ Membership Operators
There are 2 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 etc)
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 same
is not x is not True
object)
() Parentheses
** Exponent
~x, +x, -x Complement, Unary plus, Unary minus
Multiplication, Division, Floor division,
*, /, //, % Modulus
+, - Addition, Subtraction
<<, >> Bitwise shift operators
&, ^ , | Bitwise AND, Bitwise XOR, Bitwise OR
<=, < >, > = Comparison
Page 12
Module I RLMCA369 - Elective II- Python Programming
<>,==, != Equality
=, %=, /=, //=, -=, +=, *=, **= Assignment
is, is not Identity
in, not in Membership operator
not, and, or Logical operators
Operator associativity determines:
• More than one operator exists in the same group. These operators have the same
precedence.
• When 2 operators have the same precedence, associativity helps to determine which the
order of operations.
• Associativity is the order in which an expression is evaluated that has multiple operator of
the same precedence. Almost all the operators have left-to-right associativity.
• = and ** are right-associative while all other operators are left-
associative.
1. List some of the features
2. Is Python a case sensitive language?
3. How can you run python?
4. Give the rules for naming an identifier.
5. How can you give comments in Python?
6. What are multi-line statements?
7. What do you mean by suite in Python?
8. Briefly explain the input and output functions used in python.
9. What is the purpose of import function?
10. What is the purpose of // operator?
11. What is the purpose of ** operator?
12. What is the purpose of is operator?
13. What is the purpose of not in operator?
14. Briefly explain the various types of operators.
15. List out the operator precedence in Python
Data types
o The data is stored in memory can be of many types.
For eg: Salary is stored as a numeric value.
o Python has the following standard data types:
• Numbers • List • Set
• String • Tuple • dictionary
1) Numbers
Page 13
Module I RLMCA369 - Elective II- Python Programming
del var1[,var2[,var3[....,varn]]]
• del a
• del a, b
o You can delete a single object or multiple objects by using the del
statement.
Python supports 4 different numerical types:
o int (signed integers)
o long (long integers, they can also be represented in octal & hexadecimal)
o float (floating point real values)
o complex (complex numbers)
a = 1234567890123456789
print ('a = ',a) #a = 1234567890123456789
#float variable b got truncated
b=1.123456789123456789
print('''b=''',b) # b=1.1234567891234568
c=1.12345678912345612110
print('''c=''',c) #c=1.1234567891234561
a=5
print(type(a)) # <class 'int'>
d = (2+9j)
print(d) #d = (2+9j)
Page 14
Module I RLMCA369 - Elective II- Python Programming
a) Mathematical functions
import math
math.functionname()
Function Description
Page 15
Module I RLMCA369 - Elective II- Python Programming
Returns the integer & decimal part as a tuple.
The integer part is returned as a decimal.
modf(x) eg: math.modf(17.090876)=0.09087599999973, 17.0
b) Trigonometric functions
import math
math.functionname
Function Description
import random
random.function name()
Function Description
Page 16
Module I RLMCA369 - Elective II- Python Programming
To generate 1 random number from a
sequence like list, tuple, string etc
eg:
choice(sequence)
s="abcde"
print(“choice(abcde):”,random.choice(s))
#d
2) Strings
Page 17
Module I RLMCA369 - Elective II- Python Programming
str="welcome to python programming"
print (str) #welcome to python programming
print(str[0]) #w
print(str[0:3]) #wel
print(str[3:6]) #com
print(str[8:]) #to python programming
print(str[7:]) # to python programming
print(str*2) #welcome to python programming welcome to python programming
a) Escape Characters
An escape character is a character that gets interpreted when placed in single or double quotes.
They are represented using backslash notation.
Escape Description Escape Description
Characters Characters
\a Bell or alert \r carriage return
\b Backspace \s space
\f Form feed \t tab
\n newline \v vertical tab
b) String Formatting Operator
This operator is unique to strings and is similar to the formatting operations of the printf()
function of the C language.
Format Symbols Conversion
%c Character
%s String
%i or %d Signed decimal integer
%u Unsigned decimal integer
%o octal integer
%x or %X Hexadecimal (lowercase or uppercase)
%e or %E Exponential notation with lowercase ‘e’ or
uppercase ‘E’
%f floating point real number
Eg:
a="sheena"
b='s' print("%.2f"%(14.579))
print('string is %s and character is %c ' %(a,b)) 14.58
#string is sheena and character is s
a='sheena' a=14.579
b="a" print("%.2f"%(a)) #14.58
print('string is %s and character is %c ' %(a,b))
string is sheena and character is a
print("%.2f" %(32.1274)) #32.13 a=567.895
print("%.2f" %(a)) # 567.89
a=567.881 a=567.889
print("%.2f" %(a)) #567.88 print("%.2f" %(a)) #567.89
a=567.831 a=567.881
print("%.2f" %(a)) #567.83 print("%.2f" %(a)) #567.88
Page 18
Module I RLMCA369 - Elective II- Python Programming
3. List
List is an ordered sequence of items. It is one of the most used data type in
python and is very flexible. All the items in a list do not need to be of the same type.
Items separated by commas are enclosed within brackets [ ]. Index starts from 0 in Python.
The values stored in a list can be accessed using the slice operator([ ] and [:]).
All lists have index values 0 to n-1, where n is the number of elements in the list.
The plus(+) sign is the list concatenation operator, and the asterstik (*) is the repetition
operator.
Page 22
Module I RLMCA369 - Elective II- Python Programming
✓ Lists are similar to arrays in C.
a = [1, 2.2, 'python'] a = [5,10,15,20,25,30,35,40]
print ("a = ",a) print(“a = “,a) # a = [5,10,15,20,25,30,35,40]
# a = [1, 2.2,
'python'] print("a[2] = ", a[2]) # a[2] = 15
print ("a = ",a[0]) # a = 1 print("a[0:3] = ", a[0:3]) # a[0:3] = [5, 10, 15]
print("a[5:] = ", a[5:]) # a[5:] = [30, 35, 40]
• Lists are mutable, meaning; value of elements of a list can be
altered.
a = [1,2,3] list1=[‘abcd’,130,3.6,’TOM’,74.9]
print (‘a = ‘,a) # a=[1, 2, 3] list2=[1000,’manu’]
a[2]=4 print(list1+list2)
print (‘a = ‘,a) # a=[1, 2, 4] # ['abcd', 130, 3.6, 'TOM', 74.9, 1000, 'manu']
Page 23
Module I RLMCA369 - Elective II- Python Programming
7 list.insert(index,obj) list1=['abc',45,60,78,45,45]
Returns a list with object inserted at the given print(list1)
index list1.insert(3,1000)
print(list1)
#['abc', 45, 60, 1000, 78, 45, 45]
8 list.sort([Key=None,Reverse=Fals list1=[445,60,78,145,45]
e]) print(list1) #[445, 60, 78, 145, 45]
Sorts the items in a list & returns list1.sort()
the list. If a function is provided, it print(list1) #[45, 60, 78, 145, 445]
will compare using the function
provided
9 list.pop([index]) list1=[10,15,25,60,100,12,4]
Removes or returns the last object list1.pop(1)
obj from a list. We can even pop print(list1) #[10, 25, 60, 100, 12, 4]
out any item in a list with the index list1.pop(0)
specified. print(list1) # [25, 60, 100, 12, 4]
push – insert list1.pop(4)
pop – read &delete print(list1) # [25, 60, 100, 12]
pop removes the top of the stack list1.pop(-1)
a=[10, 15, 25, 60, 100, 12, 4] print(list1) # [25, 60, 100]
a[0]=10; a[1]=15;a[2]=25; list1.pop(-2)
a[3]=60;a[4]=100;a[5]=12; a[6]=4 print(list1) # [25, 100]
1 list.clear() list1=[10,15,25,60,100,12,4]
0 Removes all items in the list print(list1) #[10, 15, 25, 60, 100, 12, 4]
list1.clear()
print(list1) # []
1 list.copy()
1 Returns a copy of the list list1=[10,15,25,60,100,12,4]
print(list1) #[10, 15, 25, 60, 100, 12, 4]
list2=list1.copy()
print(list2) #[10, 15, 25, 60, 100, 12, 4]
1 Using List as Stacks
2 Stack – Last in First out(LIFO)
Stack is a data structure where the list1=[10,15,25,60,100,12,4]
last element added is the 1st list1.append(500)
element retrieved. The list methods print(list1) #[10, 15, 25, 60, 100, 12, 4, 500]
make it very easy to use a list as a list1.pop() list1.pop(-1)
stack. print(list1) #[10, 15, 25, 60, 100, 12,
To add an item to the top of the 4]
stack, use append().
To retrieve an item from the top of
the stack, use pop() without a
explicit index.
1 Using List as Queues
3 Queues - First in First Out(FIFO) from collections import deque
To implement a queue, python list1=deque(["apple","orange","grape
provides a module called collections s"])
in which a method called deque is print(list1) # deque(['apple', 'orange',
designed to have fast appends & 'grapes'])
pops from both sides. list1.append("cherry")
print(list1) #deque(['apple', 'orange', 'grapes',
'cherry'])
Page 24
Module I RLMCA369 - Elective II- Python Programming
eg: list1.popleft()
from collections import deque print(list1) #deque(['orange', 'grapes',
list1=deque([60, 78, 45, 45]) ‘cherry'])
list1.popleft()
print(list1) #deque([78, 45, 45])
fruit=['banana','apple','cherry'] fruit.insert(2,'pear')
print(fruit) #['banana', 'apple', 'cherry'] print(fruit) #['banana', 'mango', 'pear']
fruit[2]='mango' fruit.append('grapes')
print(fruit) #['banana', 'apple', 'mango'] print(fruit) #['banana', 'mango', 'pear',
del fruit[1] 'grapes']
print(fruit) #['banana', 'mango'] fruit.sort()
print(fruit) #['banana', 'grapes', 'mango',
'pear']
fruit.reverse()
print(fruit) #['pear', 'mango', 'grapes',
'banana']
4. Tuple
• Tuple is an ordered sequence of items, same as list.
• A tuple consists of a number of values separated by commas.
• A tuple is an immutable ie, it cannot be altered.
List Tuple
List is a mutable linear data structure, Tuple is immutable linear data structure,
denoted by comma-separated list of denoted by comma-separated list of elements
elements within square brackets [ ], allowing within parenthesis ( ), allowing mixed-type
mixed-type elements & their elements and elements & cannot be updated. It can be
size can be changed. considered as read-only lists.
a=[10,12.6,'ammu'] a=(10,8,12.6,'ammu')
print(a) # [10, 12.6, 'ammu'] print(a) # [10, 8,12.6, 'ammu']
b=[190] b=(190)
print(b) # [190] print(b) # [190]
List Tuple
a = [5,10,15,20,25,30,35,40] a = (5,10,15,20,25,30,35,40)
print("a = ",a) # a = [5,10,15,20,25,30,35,40] print("a = ",a) #a=
print("a[2] = ", a[2]) # a[2] = 15 [5,10,15,20,25,30,35,40]
print("a[0:3] = ", a[0:3]) # a[0:3] = [5, 10, 15] print("a[2] = ", a[2]) # a[2] = 15
print("a[5:] = ", a[5:]) # a[5:] = [30, 35, 40] print("a[0:3] = ", a[0:3])
print("a[5:] = ", a[2:5]) #a[2:5] =[15, 20, 25] # a[0:3] = (5, 10, 15)
list1= [5,'pgm', 1+3j] print("a[5:] = ", a[5:])
print("list1 =",list1) # list1 = [5, 'pgm', (1+3j)] # a[5:] = (30, 35, 40)
print("a[5:] = ", a[2:5])
#a[2:5] =(15, 20, 25)
tup = (5,'program', 1+3j)
print("tup=",tup)
# tup = (5, 'pgm', (1+3j))
Page 25
Module I RLMCA369 - Elective II- Python Programming
We can use the slicing operator [] to extract items but we cannot change its value.
a = [5,10,15] a = (5,10,15)
print("a= ", a) # a = [5,10,15] print("a= ", a) # a= (5,10,15)
a[1]=100
a[1]=100 print("a= ",a)
print("a= ",a) #a= ‘’’Traceback (most recent call last):
[5,100,15] File "C:/Python34/test.py", line 3, in <module>
a[1]=100
TypeError: 'tuple' object does not support item
assignment ‘’’
a = [5,10,15] a = (5,10,15)
print("a= ", a) # a= [5,10,15] print("a= ", a) # a= (5,10,15)
del(a[1]) del(a[1])
print("a= ",a) # a= [5,15] print("a= ",a)
'''a= (5, 10, 15)
Traceback (most recent call last):
File "C:/Python34/test.py", line 3, in <module>
del(a[1])
TypeError: 'tuple' object doesn't support item deletion'''
list1=['abcd',1000] tuple1=('abcd',1000)
print("tuple1 = ",tuple(list1)) print("list1 = ",list(tuple1))
#tuple1 = ('abcd', 1000) #list1 = ['abcd', 1000]
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 ‘’’
list1=[2,30,10] list1=[2,30,10,2,2,2]
tuple1=tuple(list1) tuple1=tuple(list1)
print('tuple1= ',tuple1) #tuple1=(2, 30, 10) print('tuple1= ',tuple1) #tuple1=(2, 30, 10)
set1=set(list1) set1=set(list1)
print('set1= ',set1) #set1= {2, 10, 30} print('set1= ',set1) # set1= {2, 10, 30}
list1=list(tuple1) list1=list(tuple1)
print('list1= ',list1) #list1= [2, 30, 10] print('list1= ',list1) # list1= [2, 30, 10]
➢ Built-in Set functions
1 len(set)- Gives the total length of the set1={1000,’manu’}
tuple print(len(set1)) #2
2 max(set) – Returns item from the set with set1={ 1000,5,6000,8,7.9,7000.5}
maximum value print(max(set1)) # 7000.5
3 min(set) – Returns item from the set with set1={1000,15.9,6000,8}
minimum value print(min(set1)) #8
4 sum(set) – Returns the sum of all set1={1000,5,6000,8,7.9,7000.5}
items in the set print(sum(set1)) #14021.4
5 sorted(set)- Returns a new sorted set. set1={100, 5, 600, 8, 5, 7.9, 700.5, 8}
The set does sort itself. print(set1) #{100, 5, 8, 600, 7.9, 700.5}
set2=sorted(set1)
print(set2) # [5, 7.9, 8, 100, 600, 700.5]
6 enumerate(set) grocery = ['bread', 'milk', 'butter']
Returns an enumerate object. It enum1 = enumerate(grocery)
contains the index & value of all the print(enum1)
items of set as a pair. # <enumerate object at
0x03899F80>
print(list(enum1))
# [(0, 'bread'), (1, 'milk'), (2,
'butter')]
#print(tuple(enum1))
# ((0, 'bread'), (1, 'milk'), (2, butter'))
Page 27
Module I RLMCA369 - Elective II- Python Programming
7 any(set) set1=set()
Returns True, if the set contains at set2={1,2,3,4}
least 1 item, False otherwise. print(any(set1)) #False
print(any(set2)) #True
8 all(set) set1=set()
Returns True, if all the elements are set2={1,2,3,4}
true or the set is empty print(all(set1)) #True
print(all(set2)) #True
Page 28
Module I RLMCA369 - Elective II- Python Programming
8 set1.intersection_update() set1={3, 8, 2, 6}
Update the set with the
set2={4,2,1,9}
intersection of itself & another.set1.intersection_update(set2)
The result will be stored in set1.
print(set1) #{8,2,3,6}
9 set1.difference(set2) set1={3, 8, 2, 6}
Returns the difference of 2 or set2={4,2,1,9}
more sets into a new set. set3=set1.difference(set2)
print(set3) #{8,3,6}
10 set1.difference_update(set2) - set1={3, 8, 2, 6}
Remove all elements of another set2={4,2,1,9}
set set2 from set1 & the result is set1.difference_update(set2)
stored in set1 print(set1) #{8,3,6}
11 set1.symmetric_difference(set2) set1={3, 8, 2, 6}
Return the symmetric difference of set2={4,2,1,9}
2 sets as a new set set3=set1.symmetric_difference(set2)
print(set3) #{1, 3, 4, 6, 8, 9}
Frozenset
Frozenset is a new class that has the characteristics of a set, but its
elements cannot be changed once assigned.
• Tuples are immutable lists
• Frozensets are immutable sets
• Frozensets can be created using the function frozenset()
• This datatype supports methods like difference(), intersection(),
union(), isdisjoint() etc.
• It does not support add(), remove(), update() etc
set1=frozenset({3,8, 2,6}
print(set1) #frozenset({8, 2, 3, 6})
set2=frozenset({4,2,1,9})
print(set2) #frozenset({9, 1, 2, 4})
set3=set1.union(set2)
print(set3) #frozenset({1, 2, 3, 4, 6, 8, 9})
6. Dictionary
• Dictionary is an unordered collection of key-value pairs.
• It is generally used when we have a huge amount of data.
• Dictionaries are defined within curly braces { } with each item being
a pair in the form key : value.
• Key & value can be any type.
• Keys are usually numbers or strings.
• Values can be any arbitrary Python object.
• We use key to retrieve the respective value.
• Each key is separated from its value by a colon (:)
• Dictionaries are enclosed by curly braces { }
• Values can assigned & accessed using square brackets [ ]
eg:
KEY VALUE
Page 29
Module I RLMCA369 - Elective II- Python Programming
dict1 = {'Name': 'Sonu', 'Age': 17, 'Class': '+2'}
print ("dict1['Name']: ", dict1['Name']) # dict['Name']: Sonu
print ("dict1['Age']: ", dict1['Age']) # dict['Age']: 17
print(dict1) # {'Name': 'Sonu', 'Class': '+2', 'Age': 17}
print(dict1.keys()) # dict_keys(['Name', 'Class', 'Age'])
print(dict1.values()) # dict_values(['Sonu', '+2', 17])
type(dict1) # <class 'dict'>
dict1 = { }
dict1['one']="This is one"
dict1[2]='This is two'
print ("dict1['one']: ", dict1['one']) #dict1['one']: This is one
print ("dict1['2']: ", dict1[2]) # dict1['2']: This is two
print(dict1) # {'one': 'This is one', 2: 'This is two'}
print(dict1.keys()) # dict_keys(['one', 2])
print(dict1.values()) #dict_values(['This is one', 'This is two'])
#updating existing values in key-value pair
dict1 = {'Name': 'sonu', 'Age': 17, 'Class': '+2'}
print(dict1) # {'Name': 'Sonu', 'Class': '+2', 'Age': 17}
dict1['Name']='Tony'
dict1['Age']=18
print(dict1) # {'Name': 'Tony' ,'Class': '+2','Age': 18 }
Properties of Dictionary keys
1. More than 1 entry per key is not allowed. ie, no duplicate key is
allowed.
2. When duplicate keys are encountered during assignment, the last
assignment is taken.
3. Keys are immutable. This means keys can be numbers, strings or
tuple. But it does not permit mutable objects like lists.
➢ Built-in Dictionary Functions
1 len(dict)- Gives the length of the dict1 = {'Name': 'Sonu', 'Age': 17}
dictionary print(len(dict1)) #2
2 str(dict) – Produces a printable string dict1 = {'Name': 'Sonu', 'Age': 17}
representation of the dictionary print(str(dict1))
# {'Name': 'Sonu', 'Age':
17}
3 type(dict) – Returns the type of the dict1 = {'Name': 'Sonu', 'Age': 17}
variable. print(type(dict1)) #<class 'dict'>
➢ Built-in Dictionary Methods
1 dict.clear()
Removes all elements of dictionary dict
2 dict.copy() dict1 = {'Name': 'Sonu', 'Age': 17}
Returns a copy of the dictionary dict() dict2=dict1.copy()
print(dict2)
# dict2 = {'Name': 'Sonu', 'Age': 17}
Page 30
Module I RLMCA369 - Elective II- Python Programming
3 dict.keys() dict1 = {'Name': 'Sonu', 'Age': 17}
Returns a list of keys in dictionary dict print(dict1.keys())
***The values of the keys will be
displayed in a random order. # dict_keys(['Age', 'Name'])
4 dict.values() dict1 = {'Name': 'Sonu', 'Age': 17}
Returns list of all values available in a print(dict1.values())
dictionary # dict_values(['Sonu', 17])
5 dict.items() dict1 = {'Name': 'Sonu', 'Age': 17}
Returns a list of dict’s (key, value) tuple print(dict1.items())
pairs #dict_items([('Name', 'Sonu'), ('Age',
17)])
6 dict1.update(dict2) dict1 = {'Name': 'Sonu', 'Age': 17}
The dictionary dict2’s key-value pair dict2={'weight': 70}
will be updated in dictionary dict1 dict1.update(dict2)
print(dict1)
#{'Age': 17, 'weight': 70, 'Name': 'Sonu'}
Page 31
Module I RLMCA369 - Elective II- Python Programming
• (12)base 5 = 1*(5 ^ 1) + 2*(5 ^ 0) =5+2 =7
• int("A",16) # 10
long(x [,base] ) Converts x to a long integer. base specifies the base if x is a string.
a = int("34") # a = 34
b = long("0xfe76214", 16) # b = 266822164L (0xfe76214L)
b = float("3.1415926") # b = 3.1415926
c = eval("3, 5, 6") # c = (3,5,6)
• Conversion from float to int will truncate the value (make it closer to zero).
>>> int(10.6) 10
>>> int(-10.6) -10
Page 32
Module I RLMCA369 - Elective II- Python Programming
• Conversion to and from string must contain compatible values.
>>> float('2.5') # 2.5 >>> str(25) # '25'
Conversion Functions
Function Converting what to what Example
>>> int('2014') #2014
int() string, floating point → integer >>> int(3.141592) #3
>>> float('1.99') # 1.99
float() string, integer → floating point number >>> float(5) #5.0
>>> str(3.141592) # '3.141592'
str() integer, float, list, tuple, dictionary → string >>> str([1,2,3,4]) # '[1, 2, 3, 4]'
>>> list('Mary') # ['M', 'a', 'r', 'y']
list() string, tuple, dictionary → list >>> list((1,2,3,4)) # [1, 2, 3, 4]
>>> tuple('Mary') # ('M', 'a', 'r', 'y')
tuple() string, list → tuple >>> tuple([1,2,3,4]) # (1, 2, 3, 4)
Decision Making
Decision making is required when we want to execute a code only if a certain condition is
satisfied.
• 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 with the first unindented line.
• Python interprets non-zero values as True. None and 0 are interpreted as False.
print(“enter num :”)
if expression: if num > 10: output
statement(s)
print("a is greater") a is greater
Page 33
Module I RLMCA369 - Elective II- Python Programming
#to check no: is even
num = int(input("Enter a number: "))
if (num % 2) == 0:
print(num, " is Even") #10 is Even
Page 34
Module I RLMCA369 - Elective II- Python Programming
4. Nested if statements(Nested conditionals)
• We can have a if...elif...else statement inside another if...elif...else statement. This is
called nesting.
• 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.
Syntax, num = float(input("Enter a number: Enter a number: 5
if expression1: ")) Positive number
statement(s) if num >= 0:
if expression2: if num == 0: Enter a number: 0
statement(s) print("Zero") zero
elif expression3: else:
print("Positive number") Enter a number: -15
statement(s)
else: Negative number
else:
print("Negative number")
statement(s)
elif expression4:
statement(s)
else:
statement(s)
• Python Program to Check if a Number is Odd or Even
• Python Program to Check Leap Year
• Largest of 3 nos
#Largest of 3 nos
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
num3 = float(input("Enter third number: "))
if (num1 >= num2) and (num1 >= num3):
largest = num1
elif (num2 >= num1) and (num2 >= num3):
largest = num2
else:
largest = num3
print("The largest number is ",largest)
LOOPS
Generally, statements are executed sequentially. The 1st statement in a function is
executed 1st, followed by the 2nd, and so on. There will be situations when we need to execute a
block of code several number of times. Python provides various control structures that allow
for repeated execution. A loop statement allows us to execute a statement or group of
statements multiple times.
There are different types of loops depending on the position at which condition is
checked.
Page 35
Module I RLMCA369 - Elective II- Python Programming
Basic Structure of Loops
o Initialize loop control
o Check if the stopping condition has been met
▪ If it’s been met then the loop ends
▪ If it hasn’t been met then proceed to the next step
o Execute the body of the loop (the part to be repeated)
o Update the loop control
1.Pre-Test loops
o Check the stopping condition before executing the body of the loop.
o The loop executes zero or more times.
• while
• for
2.Post-Test loops (Not Implemented In Python)
• Initialize loop control (sometimes not needed because initialization occurs when the control
is updated)
• Execute the body of the loop (the part to be repeated)
• Update the loop control
• Check if the stopping condition has been met
▪ If it’s been met then the loop ends
▪ If it hasn’t been met then return to step 2.
1. for Loop
The ‘for loop’ is used to iterate over a sequence (list, tuple, string etc). Iterating over a
sequence is called traversal.
Syntax,
Here, item is the variable that takes the value of the item inside the sequence of 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.
Page 36
Module I RLMCA369 - Elective II- Python Programming
# sum of all numbers stored in a list
list1= [6, 5, 3, 8, 4, 2, 5, 4, 11] # List of numbers
sum = 0
for item in list1:
sum = sum+item
print("sum is ", sum) The sum is 48
tup1= (6, 5, 3, 8, 4, 2, 5, 4, 11)
sum = 0
for item in tup1:
sum = sum+item
print(" sum is", sum) sum is 48
flowers =[‘rose’, ‘lotus’, ‘jasmine’] current item :rose
for item in flowers: current item :lotus
print(‘current item :’,item) current item :jasmine
current letter : p
current letter : r
current letter : o
for letter in ‘program’:
current letter : g
print(‘current letter :’,letter)
current letter : r
current letter : a
current letter : m
a. 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 as range(start, stop, step). Default value of step is 1. 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().
Eg:
print(range(10)) #range(0 , 10)
print(list(range(10))) #[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(list(range(2, 8))) #[2, 3, 4, 5, 6, 7]
print(list(range(2, 20, 3))) #[2, 5, 8, 11, 14, 17]
Page 37
Module I RLMCA369 - Elective II- Python Programming
number:8
for i in range(5): for i in range(3,6): for i in range(4,10,2):
print(i) #0 1 2 3 4 print(i) #3 4 5 print(i) #4 6 8
for i in range(0,-10,-2):
print(i) #0 -2 -4 -6 -8
#sum of any n numbers '''How many numbers: 3
num = int(input('How many numbers: ')) enter nos
sum = 0 7
print("enter nos") 8
for i in range(num): 5
nos= int(input( )) Sum : 20
sum += nos Average :6.67 '''
avg = sum/num
print('Sum :', sum)
print('Average :%.2f '%(avg))
# to find the factorial of a number Enter a number: 5
num = int(input("Enter a number: ")) 5 ! = 120
fact = 1 Enter a number: 0
if num < 0:
0!= 1
print("please enter positive number ")
else: Enter a number: 1
for i in range(1,num+1): 1!= 1
fact= fact*i Enter a number: -3
print(num,"! = ",fact) please enter positive number
b. 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.
for i in range(1, 4):
for i in range(1, 4):
print(i)
print(i)
break
else: # Executed because no break in
else: # Not executed as there is a break
for
print("No Break")
print("No Break")
o/p
o/p
1 1
2
3
No Break
for n in range(2, 10):
for n in range(2, 10):
for x in range(2, n):
for x in range(2, n):
if n % x == 0:
if n % x == 0:
print(x,'*',n/x,'=',n)
print(x,'*',n/x,'=',n)
break
break
'''
else:
2 * 2.0 = 4
print(n, 'is a prime number')
2 * 3.0 = 6
'''2 is a prime number
2 * 4.0 = 8
3 is a prime number
3 * 3.0 = 9
Page 38
Module I RLMCA369 - Elective II- Python Programming
''' 2 * 2.0 = 4
5 is a prime number
2 * 3.0 = 6
7 is a prime number
2 * 4.0 = 8
3 * 3.0 = 9'''
Here, 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
Repeats a statement or group of statements while a given condition is TRUE. It tests the
condition before executing the loop body.
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.
Page 39
Module I RLMCA369 - Elective II- Python Programming
Here, we use a counter variable to print the string Inside loop 3 times.
On the 4th iteration, the condition in while becomes False. Hence, the else part is executed.
To display the Fibonacci sequence up to nth term where n is provided by the user
n = int(input("How many terms? ")) else:
n1 = 0 while count < n:
n2 = 1 print(n1,end=' ') How many terms? 10
count = 0 n3 = n1 + n2 0 1 1 2 3 5 8 13 21 34
if n <= 0: n1 = n2 How many terms? -5
print("Please enter a +ve integer") n2 = n3 Please enter a +ve integer
elif n == 1: count += 1 How many terms? 0
print(n1) Please enter a +ve integer
Nested loops
• Sometimes we need to place a loop inside another loop. This is called nested loop.
Page 40
Module I RLMCA369 - Elective II- Python Programming
Syntax,
for iterating_var in sequence: while expression:
for iterating_var in sequence: while expression:
statements(s) statement(s)
statements(s) statement(s)
A final note on loop nesting is that you can put any type of loop inside of any other type of loop.
1. break statement
• The break statement terminates the loop containing it. Control of the program flows to the
statement immediately after the body of the loop.
• If it is inside a nested loop (loop inside another loop), break will terminate the
innermost loop.
Page 41
Module I RLMCA369 - Elective II- Python Programming
Syntax,
break
s
t
r
The end
'''for i in range(2,10,2): i=2
if(i==6): break while(i<10):
print(i) if(i==6): break
print('end of the pgm') print(i)
i=i+2
output print('end of the pgm')
2 output
4 2
end of the pgm''' 4
end of the pgm
2. 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,
Page 42
Module I RLMCA369 - Elective II- Python Programming
continue
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.
3. pass statement
• In Python programming, pass is a null statement.
• The difference between a comment & pass statement in Python is that, while the
interpreter ignores a comment entirely, pass is not ignored.
• However, nothing happens when pass is executed. It results in no operation (NOP).
Syntax
pass
We generally use it as a placeholder. Suppose we have a loop or a function that is not implemented
yet, but we want to implement it in the future. They cannot have an empty body. The interpreter
would complain. So, we use the pass statement to construct a body that does nothing.
Page 43
Module I RLMCA369 - Elective II- Python Programming
for letter in 'Python': Current Letter : P
if letter == 'h': Current Letter : y
pass Current Letter : t
print ('This is pass block') This is pass block
print ('Current Letter :', letter) Current Letter : h
Current Letter : o
print ("Good bye!") Current Letter : n
Good bye!
Types of loops
There are different types of loops depending on the position at which condition is checked.
1.Infinite loop
A loop becomes infinite loop if a condition never becomes False. This results in a loop that
never ends. Such a loop is called an infinite loop.
If the condition of while loop is always True, we get an infinite loop.
while True: """
num = int(input("Enter an integer: ")) Enter an integer: 3
print("The double of",num,"is",2 * num) The double of 3 is 6
Enter an integer: 4
The double of 4 is 8
Enter an integer: clrl+c
*****This value continue running unless you Traceback (most recent call last):
give ctrl+c to exit from the loop File "D:/Python/infiniteloop.py", line 2, in
<module>
num = int(input("Enter an integer: "))
KeyboardInterrupt """
Page 44
Module I RLMCA369 - Elective II- Python Programming
#sum of n nos
n = int(input("Enter n: "))
sum = 0
i=1 Enter n: 10
while i <= n: sum : 55
sum = sum + i
i = i+1
print(" sum : ",sum)
This kind of loop can be implemented using an infinite loop along with a conditional
break in between the body of the loop.
Page 45
Module I RLMCA369 - Elective II- Python Programming
ch=0 break; 1. addition
a,b=6,3 # a=6;b=3 print("end of pgm") 2. subtraction
while ch !=3: output 3. exit
menu enter yr choice : 2
print ("menu")
1. addition difference= 3
print("1. addition") menu
2. subtraction
print("2. subtraction") 3. exit 1. addition
print("3. exit") enter yr choice : 1 2. subtraction
ch=int(input("enter yr choice : ")) sum= 9 3. exit
if ch==1: enter yr choice : 3
print ("sum= ",(a+b)) end of pgm
if ch==2:
print ("difference= ",(a-b))
Page 46
Module I RLMCA369 - Elective II- Python Programming
matrix=[[1,2,3],
[4,5,6], 147
[7,8,9]] 258
transpose=[[row[i] for row in matrix] for i in range(3)] 369
for i in range (len(matrix)):
for j in range (len(matrix[0])):
print(transpose[i][j],end=" ")
print()
3. SET Comprehensions
Sets support comprehensions in a similar way to lists.
s={x for x in 'sheenajabbar' if x not in 'aeiou'} {'h', 'b', 'r', 's', 'n', 'j'}
print(s)
4. Dictionary Comprehensions
Python support dictionaries nested one inside the other. Nesting involves putting a list or
dictionary inside another list or dictionary.
nestedDict = { 'dictA': {'key1': 'value1'},'dictB': {'key2': 'value2'}
Page 47