0% found this document useful (0 votes)
44 views47 pages

Module1-8 9 19

The document provides an overview of the Python programming language including its features, applications, history, data types, variables, operators, control flow statements, and integrated development environments. Key topics covered include Python's simplicity, interpretive nature, object-oriented approach, portability, extensibility, and large standard library.

Uploaded by

abzjkr
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
44 views47 pages

Module1-8 9 19

The document provides an overview of the Python programming language including its features, applications, history, data types, variables, operators, control flow statements, and integrated development environments. Key topics covered include Python's simplicity, interpretive nature, object-oriented approach, portability, extensibility, and large standard library.

Uploaded by

abzjkr
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 47

Module I RLMCA369 - Elective II- Python Programming

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:

• Web and Internet Development


• Database Access
• Desktop GUIs
• Scientific and Numeric Computing
• Education
• Network Programming
• Software Development
• Game and 3D Graphics
Companies using Python:
• Google, Yahoo, YouTube, NASA...
Introduction
• Python was developed by Guido van Rossum at the National Research Institute
for Mathematics & Computer Science, Netherlands during 1985- 1990.
• 1st release - 1990s.
• Its name comes from a 1970s British comedy sketch television show “Monty
Python’s Flying Circus”.)
• It is a general purpose, interpreted, interactive, objective oriented & high level
programming language.
• Runs on Windows, Linux/Unix, Mac, OS/2 etc
• Versions: 2.x and 3.x
Features of Python
1 Simple & easy to learn:
Python is a simple language with few keywords, simple structure & its syntax is also
clearly defined. This makes Python a beginner’s language.
2 Interpreted & Interactive Language:
Python is processed at runtime by the interpreter. We need not compile the program
before executing it. The python prompt interact with the interpreter to interpret the
programs that you have written. Python has an option namely interactive mode which allows
interactive testing & debugging of code.
3 Object-Oriented language:
Python supports object oriented programming (OOP) concepts that encapsulate code
within objects.
All concepts in OOPs like data hiding, operator overloading, inheritance etc can be well
written in Python.
It supports functional as well as structured programming.
4 Portable:
Python can run on a wide variety of hardware & software platforms & has the same
interface on all platforms.
All variants of Windows, Unix, Linux, Macintosh etc.

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.

False None True lamda raise


and del from nonlocal return
assert elif global not try
break else if or while
class except import pass yield
continue finally in as with
def for 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.

Single Line Comment


• In Python, we use the hash (#) symbol to start writing a comment.
• It extends up to the newline character.
#my first pgm o/p
print('Hello') Hello

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

Python provides numerous built-in functions. Some of the functions


like input() and print() are widely used for standard input and output operations respectively.

Output using print() function


The function used to print output on a screen is the print statement where you can pass
zero or more expressions separated by commas.
• The print () converts the expressions we pass into a string & writes the result to
the std output device.

Python 2.x Python 3.x


>>>print " Hello World " >>>print (" Hello World ")
Hello World Hello World

PythonIDLE  PYTHON3.6.1 Shell→file→new


script.py

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,

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

• objects are the values to be printed.


• sep is the separator used between the values. Space character is the default
separator.
• end is printed after printing all the values. The default value for end is the new
line.
• file is the object where the values are printed & its default value is
sys.stdout(screen).
• Flush determines whether the output stream needs to be flushed for any waiting
output. A True value forcibly flushes the stream.
Eg:
>>>print(1,2,3,4) 1234
>>>print(1,2,3,4,sep=’!‘) 1!2!3!4
>>>print(1,2,3,4,sep=’?’,end=’^’) 1?2?3?4^

Reading the Input


Python provides 2 built-in functions to read a line of text from standard input device (keyboard).

These functions are raw_input & input.


• raw_input function reads one line from standard input & returns it as a
string (removing the trailing newline)
str=raw_input(“enter your name : enter your name : Sheena Jabbar
”); Name is : Sheena Jabbar
print “Name is : ”,str
• input([prompt]) function is equivalent to raw_input, except that it assumes the input
is a valid Python expression & returns the evaluated result.
• The sequence \n at the end of the prompt represents a newline, which is a special
character that causes a line break
n=input(“enter a number “) enter a number 5
print (“number = “,n) number = 5
str=input(“enter your name”) enter your name sheena
print (“name is: “,str) name is sheena

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

+ Addition Adds values on either side of the operator. a + b = 30

- Subtraction Subtracts right hand operand from left hand a – b = -10


operand.

* Multiplication Multiplies values on either side of the operator a * b = 200

/ Division Divides left hand operand by right hand operand b / a = 2.0


a /b =.5

% Modulus Divides left hand operand by right hand operand b%a=0


and returns remainder

** Exponent Performs exponential (power) calculation on a**b =10 to


operators the power
20

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

• Comparison Operators(Relational operators)


These operators compare the values on either sides of them & decide the relation among
them.
Eg: a= 10 & b= 20
Operator Description Example

== If the values of 2 operands are equal, then the condition (10==20)


becomes true. (a == b)
is
not true.

!= If values of 2 operands are not equal, then condition becomes 10!=20


true. (a != b) is
true.

> 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

= Assigns values from right side operands to x=5


left side operand

+= It adds right operand to the left operand & x += 5


assign the result to left operand

-= It subtracts right operand from the left x -= 5


operand & assign the result to left operand

*= It multiplies right operand with the left x *= 5


operand & assign the result to left operand

/= It divides left operand with the right operand & x /= 5


assign the result to left operand

%= It takes modulus using 2 operands & assign the x %= 5


result to left operand

//= It performs floor division on operators & assign x//=5


values to the left operand 9//2 = 4
9.0//2.0 = 4.0
-11.0//3=-4.0
12//5=2

**= Performs exponential (power) calculation on x **= 5 or


operators & assign value to left operand x = x ** 5
• Bitwise Operators
Bitwise operator works on bits and performs bit by bit operation.
Let x = 10 (0000 1010 in binary) & y = 4 (0000 0100 in binary)
Operator Meaning Description Example

Operator copies a bit to


& Bitwise AND the result if it exists in x& y = 0 (0000 0000)
both operands

It copies a bit if it exists


| Bitwise OR x | y = 14 (0000 1110)
in either operand

~ Bitwise NOT It is unary and has the ~x = -11 (1111 0101)

Page 10
Module I RLMCA369 - Elective II- Python Programming
effect of ‘flipping’ bits

It copies the bit if it is set


in one operand but not
^ Bitwise XOR x ^ y = 14 (0000 1110)
both(0,0=0; 0,1=1;
1,0=1; 1,1 = 0)
shift right >> operator to shift the
bits right. 4>>1
>> Bitwise right shift x=410=01002 x>> 2 = 2 (0000 0010)

0100 >>1= 00102=210


shift left << operator to shift the bits
left. 4<<1
x=410=01002 x<< 2 = 40 (0010
<< Bitwise left shift
1000)
0100 <<1= 10002=810

• Logical Operators

Operator Meaning Example

and True if both the operands are true x and y

or True if either of the operands is true x or y

not True if operand is false (complements the operand) not x


• Special operators
➢ Membership Operators
➢ Identity 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

Evaluates to True if value/variable on either side of the


in 5 in x
operator point to the same object.

Evaluates to True if it does not find a value/variable in the


not in 5 not in x
specified sequence and false otherwise.
Eg:
Page 11
Module I RLMCA369 - Elective II- Python Programming
x = 'Hello world'
print('H' in x) True Here, 'H' is in x but 'hello' is not present in x (remember,
print('hello' not in x) True Python is case sensitive).
➢ Identity Operators
 is and is not are the identity operators in Python.
 Identity operators compare the memory locations of 2 objects.
Identity operators in Python

Operator Meaning Example

is True if the operands are identical (refer to the same object) x is True

True if the operands are not identical (do not refer to the same
is not x is not True
object)

>>> x1=8 True


>>> y1=8
>>> print(x1 is y1)
>>>x1 = 8 False
>>>y1 = 8 x1 and y1 are integers of same values, so
>>> print(x1 is not y1) they are equal as well as identical.
>>> x2 = 'Hello' False
>>> y2 = 'Hello' Same is the case with x2 and y2 (strings).
>>>print(x2 is not y2)
>>> x2 = 'Hello' True
>>> y2 = 'Hello'
>>>print(x2 is y2)
Operator Precedence
• Operators from highest precedence to lowest.
Operators Meaning

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

o Number data types store numeric values. Eg: a=10,b=40


o Number objects are created when you assign a value to them.
o Delete the reference to a number object by using the del statement.

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)

• Integers & floating points are separated by the presence or absence


of a decimal point. Eg: 5, 5.0
• Complex numbers are written in the form, x + iy, where x is the
real part and y is the imaginary part.
• We can use the type() function to know which class a variable or a
value belongs to.
• input() and raw_input() always return strings. Convert the result
to integer explicitly with int() or float().
• Integers can be of any length.
• Floating point number is accurate only up to 15 decimal places (the
16th place is inaccurate).

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

print(type(5.0)) # <class 'float'>

d = (2+9j)
print(d) #d = (2+9j)

print(type(d)) # <class ‘complex’>

Page 14
Module I RLMCA369 - Elective II- Python Programming
a) Mathematical functions

Python provides various built-in mathematical functions to perform


mathematical calculations.

All functions except abs(x), max(x1,x2,..xn), min(x1,x2,..xn),


round(),pow() need to import the math module because these functions
reside in the math module.

import math
math.functionname()

Function Description

Returns the absolute value of floating point or an integer


abs(x) value depending upon the argument.eg: abs(-150) = 150

Returns the absolute value of a floating point.


fabs(x) eg: math.fabs(-150)=150.0

ceil(x) The smallest integer not < x. Eg: math.ceil(12.2)=13

floor(x) The largest integer not > x. Eg: math.floor(12.2)=12

factorial(x) Returns the factorial of x. Eg: math.factorial(5)= 120

pow(x, y) Returns x raised to the power y. Eg: pow(2,3)=8

sqrt(x) Returns the square root of x

trunc(x) Returns the truncated integer value of x

exp(x) Returns e**x

log2(x) Returns the base-2 logarithm of x

log10(x) Returns the base-10 logarithm of x

max(x1,x2,..xn Returns the largest of its arguments


) eg: max(7,3,4)=7

Returns the smallest of its arguments


min(x1,x2,..xn) eg: min(7,3,4)=3

round(number, number of digits)


Rounds off to the given number of digits & returns the
round(x,[n]) floating point number. Eg: round(5.8694,2)=5.87
No number of digits is provided; it rounds off the number to
the nearest integer. Eg: round(5.8694)=6
round(5.1234)=5

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

Mathematical constant, the ratio of circumference of a


pi
circle to it's diameter (3.14159...)

e Mathematical constant e (2.71828...)

b) Trigonometric functions

import math
math.functionname
Function Description

sin(x) Returns the sine of x

cos(x) Returns the cosine of x

tan(x) Returns the tangent of x

asin(x) Returns the arc sine of x

acos(x) Returns the arc cosine of x

atan(x) Returns the arc tangent of x

tan2(y,x) Returns atan(y/x) in radian

sinh(x) Returns the hyperbolic cosine of x

cosh(x) Returns the hyperbolic cosine of x

tanh(x) Returns the hyperbolic tangent of x

degrees(x) Converts angle x from radians to degrees

radians(x) Converts angle x from degrees to radians

Returns the Euclidean form, sqrt(x*x +y*y)


hypot(x,y) Eg: math.hypot(3,4)=5
c) Random Number functions

Random numbers have applications in research, games, cryptography,


simulation & other applications.

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

Shuffles the items randomly in a list.


Returns none
shuffle(list)
list=[10,2,3,1,8,19]
print(random.shuffle(list)) # None

Returns a random floating-point number


which lies between 0 & 1.
random()
print(random.random()) #
0.144546784334

Gives the starting value for generating a


random number. Returns none.
seed([x]) This function is called before calling any other
random module function.
print(random.seed(20)) #None

Generates a random floating point number


that n>x & n<y
uniform(x,y)
print(random.uniform(2,3))
#2.7945582391423107

To generate random numbers but within a


range specified in its arguments. 3
arguments. Start(including generation),
randrange(start,
stop(excluding generation), & step (to skip
stop,step)
numbers in range while selecting)
eg: print(random.randrange(2,10,1)) #
8

2) Strings

• Strings are identified as a contiguous set of characters represented in the


quotation marks.
• Python allows for either pairs of single or double quotes.
• Subsets of strings can be taken using the slice operator ([ ] and [ : ] ) with
indexes starting at 0 in the beginning of the string & ending at -1.
• The plus (+) sign is the string concatenation operator
• The asterisk (*) is the repetition operator.
• The % operator is used for string formatting.
• list and tuple, slicing operator [ ] can be used with string.
• Strings are immutable.

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

c) String formatting functions


1 len(string)- Returns the length of string a='Sheena Jabbar'
print (len(a)) #13
2 lower() -Returns a copy of the string in which all s='ShEEna'
uppercase alphabets in a string are converted to print(s.lower()) # sheena
lowercase alphabets.
3 upper()- Returns a copy of the string in which all s='ShEEna'
lowercase alphabets in a string are converted to print(s.upper())#SHEENA
uppercase alphabets.
4 swapcase()- Returns a copy of the string in which s='ShEEna'
the case of all the alphabets are swapped. All the print(s.swapcase())
lowercase alphabets are converted to uppercase & # sHeeNA
vice versa.
5 capitalize() -Returns a copy of the string with s='ShEEna Jabbar'
only its 1st character capitalized. print(s.capitalize())
# Sheena jabbar
6 title()-Returns a copy of the string in which 1st s='ShEEna jaBBar'
characters of all the words are capitalized. print(s.title())
Sheena Jabbar
7 lstrip()-Returns a copy of the string in which all the s=' Sheena jabbar'
characters have been removed from the beginning. print(s.lstrip())
The default character is whitespaces. #Sheena jabbar
8 rstrip()-Returns a copy of the string in which all s=’Sheena jabbar '
the characters have been removed from the end. print(s.rstrip())
The default character is whitespaces. #Sheena jabbar
9 strip()-Returns a copy of the string in which all the s=' Sheena jabbar '
characters have been removed from the beginning & print(s.strip())
end. It performs both lstrip() & rstrip(). #Sheena jabbar
The default character is whitespaces. s='*****Sheenajabbar****'
print(s.strip('*'))
#Sheena jabbar
10 max(str)-Returns the maximum alphabetical s='sheena jabbar '
character from string str. print(max(s)) #s
s='Sheena jabbar '
print(max(s)) #r
11 min(str)-Returns the minimum alphabetical s='shee)na-jab+bar'
character from string str. print(min(s)) # )
s='sheena'
print(min(s)) #a
12 replace(old, new[,max])-Returns a copy of s='This is new. This is good'
the string with all the occurrences of substring old is print(s.replace('is','was'))
#Thwas was new. Thwas was good
replaced by new. The max is optional and if it is
print(s.replace('is','was',1))
specified, the 1st occurrences specified in max are #Thwas is new. This is good
replaced. print(s.replace('is','was',2))
#Thwas was new. This is good
print(s.replace('is','was',3))
Page 19
Module I RLMCA369 - Elective II- Python Programming
#Thwas was new. Thwas is
good
13 center(width, fillchar)-Returns a string s='This is python programming'
centred in a length specified in a width variable. print(s.center (30,'*'))
Padding is done using the character specified in the print(s.center (30))
print(s.center (50))
fillchar.
**This is python programming**
Default padding is space. This is python programming
This is python programming
14 ljust(width[,fillchar])-Returns a string left- s='This is python programming'
justified in a length specified in the width variable. print(s.ljust (30,'*'))
Padding is done using the character specified in the print(s.ljust (30))
fillchar. print(s.ljust (35))
Default padding is space. This is python programming****
This is python programming
This is python programming
15 rjust(width[,fillchar])-Returns a string right- s='This is python programming'
justified in a length specified in the width variable. print(s.rjust (28,'*'))
Padding is done using the character specified in the print(s.rjust (28))
fillchar. print(s.rjust (30))
Default padding is space. **This is python programming
This is python programming
This is python programming
16 zfill(width)-The method zfill() pads string on the s='This is python programming'
left with 0s to fill width. print(s.zfill(32))
print(s.zfill (35))
000000This is python programming
000000000This is python programming
17 count(str, beg=0, end=len(string))- s='This is python is is is
Returns the number of occurrences of str in the programming'
range beg & end. print(s.count('i',0,10)) #2
print(s.count ('i',0,28)) #5
18 find(str, beg=0, end=len(string))- s='This is python programming'
Returns the index of str occurs in the range beg & print(s.find('thon',0,25)) #10
end and returns -1 if it is not found. print(s.find('thy')) #-1
print(s.find('is',0,25)) #2
print(s.find('p',0,25)) #8
19 rfind(str, beg=0, end=len(string))-Same s='This is python programming'
as find, but searches backward in a string. print(len(s)) # 26
print(s.rfind('thon',0,26)) # 10
print(s.rfind('is',0,26)) # 5
print(s.rfind('p',0,26)) # 15
20 index (str, beg=0, end=len(string))- s='This is python programming'
Same as that of find but raises an exception if the print(s.index('thon',1,26)) # 10
item is not found. print(s.index('is',0,26)) # 2
print(s.index('the',0,26))
Traceback (most recent call last):
File "C:/Python34/test2.py", line 6,
in <module>
print(s.index('the',0,26)) # 15
ValueError: substring not found
Page 20
Module I RLMCA369 - Elective II- Python Programming
21 rindex (str, beg=0, end=len(string))- s='This is python programming'
Same as index but searches backward in a string. print(s.rindex('thon',1,26)) # 10
print(s.rindex('is',0,26)) # 5
print(s.rindex('the',0,26))
Traceback (most recent call last):
File "C:/Python34/test2.py", line 6,
in <module>print(s.rindex
('the',0,26))
ValueError: substring not found
22 startswith (suffix, beg=0, s='python programming is fun'
end=len(string))- It returns True if the string print(s.startswith('gram',0,26))
begins with the specified siffix otherwise return False. # False
print(s.startswith('py',0,24))
# True
23 endswith(suffix, beg=0, s='python programming is fun'
end=len(string))- print(s.endswith('is',10,21)) # True
It returns True if the string ends with the specified print(s.endswith('is',0,25)) # False
suffix, otherwise False.
24 isdecimal()-Returns True if a Unicode string s=u"sheena 1234"
contains only decimal characters & False otherwise. print(s.isdecimal()) #False
To define a string as Unicode string, prefix ‘u’ to the s=u"1234"
front of the quotation marks. print(s.isdecimal()) #True
25 isalpha()- Returns True if string has at least 1 s="s"
character & all characters are alphabetic & False print(s.isalpha()) #True
otherwise. s="abcd"
print(s.isalpha()) #True
s="abcd12"
print(s.isalpha()) #False
26 isalnum()- Returns True if string has at least 1 s="abcd1237dfff"
character & all characters are alphanumeric & False print(s.isalnum()) #True
otherwise. s="****abcd167"
print(s.isalnum()) #False
27 isdigit()-Returns True if string contains only s="1237"
digits & False otherwise. print(s.isdigit()) #True
s="****abcd167"
print(s.isalnum()) #False
28 islower()- Returns True if string has at least 1 s=”Sheena K M”
character & all characters are in lowercase and False print(s.islower()) #FALSE
otherwise, s=”sheena k m”
print(s.islower()) #TRUE
29 isupper()- Returns True if string has at least 1 s=”sheena k m”
character & all characters are in uppercase and print(s.isupper()) #FALSE
False otherwise, s=”SHEENA K M”
print(s.islower()) #TRUE
30 isnumeric()-Returns True if Unicode string s=u”SHEENA K M 567”
contains only numeric characters & False otherwise. print(s.isnumeric()) #FALSE
s=u” 567”
print(s.isnumeric()) #true
31 isspace()- Returns True if string contains only s=” Sheena K M”
whitespace characters & False otherwise. print(s.isspace()) #false
s=” ”
Page 21
Module I RLMCA369 - Elective II- Python Programming
print(s.isspace()) #TRUE
32 istitle()- Returns True if string is properly s=”python programming”
“titlecased” & False otherwise. print(s.istitle()) #false
Title case means each word in a sentence begins s=”Python Programming”
uppercase letter. print(s.istitle()) #true
33 expandtabs(tabsize=8)- It returns a copy of s="python\tprogramming\tis\tfun"
the string in which tab characters ie. ‘\t’ are print(s.expandtabs())
expanded using spaces using the given tab space. #python programming is fun
The default tab size is 8. s="python\tprogramming\tis\tfun"
print(s.expandtabs(12))
s="python\tprogramming\tis\tfun"
#python programming is
fun
print(s.expandtabs(3))
#python programming is fun
34 join(seq)-Returns a string in which the string s="-"
elements of sequence have been joined by a seq=("Python", "programming")
separator. print(s.join(seq))
#Python-programming
s="@"
print(s.join(seq))
#Python@programming
35 split(str=””,num=string.count(str))- s="python programming is fun"
Returns a list of all the words in the print(s.split(' '))
string using str as the separator (splits on #['python', 'programming', 'is', 'fun']
all whitespace if left unspecified),optionally s="python*programming*is*fun"
limiting the number of splits to num. print(s.split('*'))
# ['python', 'programming', 'is', 'fun']
print(s.split('*',2))
#['python', 'programming', 'is*fun']
s="pythonaprogrammingaisafun"
print(s.split('a'))
['python', 'progr', 'mming', 'is', 'fun']
36 splitlines(num=string.count(‘\n’)- s="python\nprogramming\nis\nfun"
Splits string at all (or num) newlines and print(s.splitlines())
returns a list of each line with newlines #['python', 'programming', 'is', 'fun']
(or\n)removed. print(s.splitlines(0))
If num is specified, it is assumed that #['python', 'programming', 'is', 'fun']
line breaks need to be included in the print(s.splitlines(5))
#['python\n', 'programming\n', 'is\n',
lines. 'fun']

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']

➢ Built-in list functions


1 len(list)- Gives the total length of the list2=[1000,’manu’]
list print(len(list2)) #2
2 max(list) – Returns item from the list with list1=[1000,5,6000,8]
maximum value print(max(list1)) # 6000
3 min(list) – Returns item from the list with list1=[1000,15,6000,8]
minimum value print(min(list1)) #8
4 list(seq) – Returns a tuple into a list tuple1=(‘abcd’,1000,5.78,’minnu’)
print(“list1= “,list(tuple1))
# list1 = [‘abcd’,1000,5.78,’minnu’]
➢ Built-in List Methods
1 list.append(obj) list1=['abc',60,78.45,'manu']
This method appends an object obj print(list1) #['abc', 60, 78.45, 'manu']
passed to the existing list. list1.append(70)
print(list1) #['abc', 60, 78.45, 'manu', 70]
2 list.count(obj) list1=['abc',45,60,78,45,45]
Returns how many times the object print(list1.count(45)) # 3
3 list.remove(obj) list1=['abc',45,60,78,45,45]
Removes object obj from the list list1.remove(60)
print(list1) #['abc', 45, 78, 45, 45]
4 list.index(obj) list1=['abc',45,60,78,45,45]
Returns index of the object obj if print(list1.index(78)) #3
found, otherwise raise an exception list1=['abc',45,60,78,45,45]
that value does not exist print(list1.index('ab'))
"""Traceback (most recent call last):
File "C:/Python34/test.py", line 2, in <module>
print(list1.index('ab'))
ValueError: 'ab' is not in list """
5 list.extend(seq) list1=['abc',45,60,78,45,45]
Appends the contents in a list2=[50,'lee']
sequence seq passed to a list list1.extend(list2)
print(list1)
#['abc', 45, 60, 78, 45, 45, 50, 'lee']
6 list.reverse() list1=['abc',45,60,78,45,45]
Reverses objects in a list list1.reverse()
print(list1) #[45, 45, 78, 60, 45, 'abc']

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]

➢ Built-in tuple functions


1 len(tuple)- Gives the total length of the list2=[1000,’manu’]
tuple print(len(list2)) #2
2 max(tuple) – Returns item from the tuple list1=[1000,5,6000,8]
with maximum value print(max(list1)) # 6000
3 min(tuple) – Returns item from the tuple list1=[1000,15,6000,8]
with minimum value print(min(list1)) #8
4 tuple(seq) – Returns a list into a tuple list1=[‘abcd’,1000,5.78,’minnu’]
print(“tuple1= “,tuple(list1))
# tuple1 = (‘abcd’,1000,5.78,’minnu’)
5. Set
• Set is an unordered collection of unique items.
• Set is defined by values separated by comma inside braces { }.
• It can have any number of items & they may be of different types (number, tuple, string,
list etc)
• Items in a set are not ordered. Since they are unordered we cannot access or change an
element (immutable) of set using indexing or slicing.
• The set itself is mutable. We can add or remove items from it.
• We can perform set operations like union, intersection, difference on 2 sets.
• Set have unique values. They eliminate duplicates.
• The slicing operator [ ] does not work with sets.
• An empty set is created by the function set ( ).
Page 26
Module I RLMCA369 - Elective II- Python Programming
a = {5,2,3,1,4} a = {5,2,3} #set
print("a = ", a) #a = {1, 2, 3, 4, print("a = ", a) #a = {2, 3,5}
5} a = {5, 2, 3, 5, 2, 2, 2}
print("a = ", a) #a = {2, 3,5}
print(type(a)) # <class 'set'>
a = {1, 2.6, "lee", 3}
print("a = ", a) # a = {'lee', 1, 3, 2.6}

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

➢ Built-in Set Methods


1 set.add(obj) set1={45,60,78,45,45}
Adds an element obj to a set print(set1) #{60, 45, 78}
set1.add(65)
print(set1) #{65, 60, 45, 78}
2 set.remove(obj) set1={45,60,78,45,45}
print(set1) #{60, 45, 78}
Removes an element obj from the set1.remove(60)
set. Raises KeyError if the set is print(set1) #{45, 78}
empty. set1.remove(160)
print(set1)
"""Traceback (most recent call last):
File "C:/Python34/test.py", line 5, in
<module> set1.remove(160)
KeyError: 160 """
3 set.discard(obj) set1={45,60,78,45,45}
Removes an element obj from the print(set1) #{60, 45, 78}
set. Nothing happens if the set1.discard(60)
element to be deleted is not in the print(set1) #{45, 78}
set. set1.discard(65)
set1={45,60,78,45,45} print(set1)
print(set1) #{60, 45,
78}
set1.discard(65) #no output
print(set1)
4 set.pop() set1={45,60,78,45,45}
Removes & returns an arbitrary print(set1) #{60, 45, 78}
set element. Raises KeyError if set1.pop()
the set is empty print(set1) #{45, 78}
5 set1.union(set2) set1={78,45,45}
Returns the union of 2 sets as a set2={50,25}
new set. set3=set1.union(set2)
print(set3) #{25, 50, 45, 78}
6 set1.update(set2) set1={78,45,45}
Update a set with the union of itself set2={50,25}
& others. The result will be stored set1.update(set2)
in set1. print(set1) #{25, 50, 45, 78}
7 set1.intersection(set2) set1={78,45,45}
Return the intersection of 2 sets as a set2={45,78,50,25}
new set. The result will be stored in set3=set1.intersection(set2)
set1. print(set3) #{45, 78}

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'}

a = ("RegNo : ", "Name : ", "Total : ")


b = (11111, "Christy", 450)
tuple1 = zip(a, b)
print("tuple1 :",tuple(tuple1))
list1 = zip(a, b)
print("list1 :",list(list1))
dict1 = zip(a, b)
print("dict1 :",dict(dict1))
output
tuple1 : (('RegNo : ', 11111), ('Name : ', 'Christy'), ('Total : ', 450))
list1 : [('RegNo : ', 11111), ('Name : ', 'Christy'), ('Total : ', 450)]
dict1 : {'Name : ': 'Christy', 'Total : ': 450, 'RegNo : ': 11111}

Mutable & Immutable Objects


• Objects whose value can change are said to be mutable & objects
whose value is unchangeable once they are created are called
immutable.
• An object’s mutability is determined by its type.
• numbers, strings, & tuples are immutable
• lists, sets & dictionaries are mutable
***The values of numbers & strings are not changed even after applying a
function or operation.
Data type conversion
We may need to perform conversions between the built-in types. To convert between
different data types, use the type name as a function. There are several built in functions to
perform conversion from one data type to another. These functions return a new object
representing the converted value.
Function Description

int(x [,base]) Converts x to an integer. base specifies the base if x is a string.

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.

float(x) Converts x to a floating-point number.

complex(real [,imag]) Creates a complex number.

str(x) Converts object x to a string representation.

repr(x) Converts object x to an expression string.

eval(str) Evaluates a string and returns an object.

tuple(s) Converts s to a tuple.

list(s) Converts s to a list.

set(s) Converts s to a set.

dict(d) Creates a dictionary. d must be a sequence of (key, value) tuples.

frozenset(s) Converts s to a frozen set.

chr(x) Converts an integer to a character.

unichr(x) Converts an integer to a Unicode character.

ord(x) Converts a single character to its integer value.

hex(x) Converts an integer to a hexadecimal string.

oct(x) Converts an integer to an octal string.


You also can write the repr(x) function using backquotes as ´x´. Note that
the str() and repr()functions may return different results.
repr() typically creates an expression string that can be evaluated with eval() to re-create
the object.

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)

Integer to float conversion


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

• Convert one sequence to another.


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

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.

1. Simplest form of if Statement (conditional execution)

• 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

2. if...else Statement (Alternative execution)


• The if..else statement evaluates test expression and will execute
body of if only when test condition is True.
• If the condition is False, body of else is executed.
• Indentation is used to separate the blocks.
num = int(input("Enter a number: '''Enter a number: 5
if expression: ")) 5 is odd number
Body if (num % 2) == 0: Enter a number: 6
else: print(num," is Even number") 6 is Even number '''
Body else:
print(num," is odd number")
3. if...elif...else (Chained conditionals)
• The elif is short for else if.
• It allows us to check for multiple expressions.
• If the condition for if is False, it checks the condition of the next elif block
and so on.
• If all the conditions are False, body of else is executed. Only one block
among the several if...elif...else blocks is executed according to the
condition. The if block can have only one else block. But it can have
multiple elif blocks.

print("enter 5 marks") elif(average>=40 and


if test_expr: m1=int(input()) average<50):
Body m2 = int(input()); print("Grade : C");
elif test_expr: m3 = int(input()); else:
Body m4 = int(input()); print("Grade : F");
m5 = int(input());
else: sum = m1 + m2 + m3 + m4 + m5;
Body average = sum/5;
if (m1 < 40 or m2<40 or m3<40 or
m4<40 or m5<40):
print("Grade : E")

elif(average>=91 and average<=100):


print(" Grade : A+");
elif(average>=80 and average<=90):
print("Grade : A");
elif(average>=60 and average<80):
print("Grade :B");
elif(average>=50 and average<60):
print("Grade : C+");

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,

for item in sequence:


Body

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]

• 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.
# Program to iterate through a list using indexing
I like pop
gen = ['pop', 'rock', 'jazz']
I like rock
for i in range (len(gen)):
I like jazz
print("I like", gen[i])

for num in range(2,10,2): number:2


print(“number :”,num) number:4
number:6

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

Enumerate (iterable, start=0) function


This is one of the built-in Python functions. Returns an enumerate object. The parameter
iterable must be a sequence, an iterator, some other object like list which supports iteration.
flowers=['rose','lotus','jasmine','sun flower'] flowers=['rose','lotus','jasmine','sun flower']
print(list(enumerate(flowers))) print(list(enumerate(flowers)))
for item in enumerate(flowers): for index,item in enumerate(flowers):
print(item) print(index,item)
output output
[(0, 'rose'), (1, 'lotus'), (2, 'jasmine'), (3, 'sun flower')] [(0, 'rose'), (1, 'lotus'), (2, 'jasmine'), (3, 'sun flower')]
(0, 'rose') 0 rose
(1, 'lotus') 1 lotus
(2, 'jasmine') 2 jasmine
(3, 'sun flower') 3 sun flower
while Loop

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

Write a program to add natural numbers up to n. sum = 1+2+3+...+n


n = int(input("Enter n: "))
sum = 0 Enter n: 10
i=1
while i <= n: sum : 55
sum = sum + i
i = i+1
print("sum : ", sum)
while loop with else
Same as that of for loop, we can have an optional else block with while loop as well.
• The else part is executed if the condition in the while loop evaluates to False.
• The while loop can be terminated with a break statement.
• In such case, the else part is ignored. Hence, a while loop's else part runs if no break occurs
and the condition is false.
i=0
while i < 3: i=0
print("Inside loop") while (i < 3):
i= i + 1 print("Inside loop")
else: i= i + 1
print("Inside else") if(i==2):
print("end of the pgm") break
output else:
Inside loop print("Inside else")
Inside loop print ("end of the pgm")
Inside loop output
Inside else Inside loop
end of the pgm Inside loop
end of the pgm

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.

Eg: for loop can be inside a while loop or vice versa.

#prime nos n=int(input("enter limit : "))


n=int(input("enter limit : ")) i=2
for i in range(2,n): while(i < n):
j=2 j=2
k=int(i/j) while(j <= (i/j)):
for j in range(2, k+1): if i%j==0:
if (i%j==0): break
break j=j+1
else: else:
print (i,end=' ') print (i, end=' ')
output i=i+1
enter limit : 25 output
2 3 5 7 11 13 17 19 23 enter limit : 25
2 3 5 7 11 13 17 19 23
Control Statements
• Control statements change execution from its normal sequence.
• 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 checking test
expression.
• The break and continue statements are used in these cases.
1. break
2. continue
3. pass

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

# Use of break statement inside loop


for letter in "Python"
if letter == "h”
break
print(letter)
print("The end")
output

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

# Program to show the use of continue statement inside loops


# Use of continue statement inside loop output
for letter in "Python" :
P
if letter == "h” :
y
continue t
print(letter) o
print("The end") n
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.
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 """

2.Loop with condition at the top


This is a normal while loop without break statements. The condition of the while loop is at the
top and the loop terminates when this condition is False.
We can create an infinite loop using while statement. If the condition of while loop is always
True, we get an infinite loop. We must use while loops with caution because of the possibility that
the condition may never resolves to a False value.

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)

3. Loop with condition in the middle

This kind of loop can be implemented using an infinite loop along with a conditional
break in between the body of the loop.

# To illustrate a loop with condition in the middle.


# Take input from the user untill a vowel is entered Enter a vowel: r
vowels = "aeiouAEIOU" That is not a vowel. Try again!
while True: # infinite loop Enter a vowel: 6
v = input("Enter a vowel: ") That is not a vowel. Try again!
if v in vowels: # condition in the middle Enter a vowel: t
break That is not a vowel. Try again!
print("That is not a vowel. Try again!") Enter a vowel: u
print("Thank you!") Thank you!

4. Loop with condition at the bottom


This kind of loop ensures that the body of the loop is executed at least once. It can be
implemented using an infinite loop along with a conditional break at the end. This is similar to
the do...while loop in C.

#loop with condition at the bottom if ch==3: menu

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

n=int(input("enter n ")) n=int(input("enter n "))


for i in range (0, n, 5): i=0
print (i,end=' ') while (i <= n):
print (i,end=' ')
i=i+5
output output
enter n 30 enter n 30
0 5 10 15 20 25 0 5 10 15 20 25 30
List Comprehensions
• List comprehensions provide a concise way to create lists.
• Common applications are to make new lists where each element is the result of some
operations applied to each member of another sequence or iterable, or to create a
subsequence of those elements that satisfy a certain condition.
#Generation of squares using list comprehension
squares=[x**2 for x in range(10)] output
print(squares) [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
1. Nested List
➢ We can implement a matrix as nested list (list inside a list)
➢ We can treat each element as a row of the matrix.
 For eg: x=[[1,2],[4,5],3,6]] would represent a 3x2 matrix
 1st row can be selected as x[0] &
 the element in the 1st row,1st column can be selected as x[0][0]
matrix=[[1,2,3], output
[4,5,6], 123
[7,8,9]] 456
for i in range (len(matrix)): 789
for j in range (len(matrix[0])):
print(matrix[i][j],end=" ")
print()
2. Nested List Comprehensions
➢ The initial expression in a list comprehension can be any arbitrary expression,
including another list comprehension.

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

Dictionaries also support comprehension like lists & sets.


s={x : x**2 for x in range (1,11)}
print(s)
#{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10: 100}

5. Nested 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'}

student = {1: {'name': 'Abi', 'age': '22', 'sex': 'Male'},


2: {'name': 'Athira', 'age': '22', 'sex': 'Female'}}
print(student)
#{1: {'sex': 'Male', 'age': '22', 'name': 'Abi'}, 2: {'sex': 'Female', 'age': '22', 'name': 'Athira'}}

Page 47

You might also like