Module1 Python Programming
Module1 Python Programming
MODULE I
SYLLABUS
Module I: Introduction to Python - Features of Python, Identifiers, Reserved Keywords, Variables,
Comments in Python, Input, Output and Import Functions, Operators; Data Types and Operations - int,
float, complex, Strings, List, Tuple, Set, Dictionary, Mutable and Immutable Objects, Data Type
Conversion; Flow control - Decision Making, Loops-for, range() while, break, continue, pass;
INTRODUCTION TO PYTHON
Python was developed by Guido van Rossum at the National Research Institute for Mathematics
and Computer Science in Netherlands during 1985-1990. Python is derived from many other languages,
including ABC, Modula-3, C, C++, Algol-68, SmallTalk, Unix shell and other scripting languages.
Rossum was inspired by Monty Python's Flying Circus, a BBC Comedy series and he wanted the name of
his new language to be short, unique and mysterious. Hence he named it Python. It is a general-purpose
interpreted, interactive, object-oriented, and high-level programming language. Python source code is
available under the GNU General Public License (GPL) and it is now maintained by a core development
team at the National Research Institute.
FEATURES OF PYTHON
a) Simple and easy-to-learn - Python is a simple language with few keywords, simple structure and
its syntax is also clearly defined. This makes Python a beginner's language.
b) Interpreted and Interactive - 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 we have written. Python has an option namely interactive mode which
allows interactive testing and debugging of code.
c) Object-Oriented - 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.
d) Portable - Python can run on a wide variety of hardware and software platforms, and
has the same interface on all platforms. All variants of Windows, Unix, Linux and
Macintosh are to name a few.
e) Scalable - Python provides a better structure and support for large programs than shell
scripting. It can be used as a scripting language or can be compiled to bytecode (intermediate
code that is platform independent) for building large applications.
f) 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, and Java.
g) Dynamic - Python provides very high-level dynamic data types and supports dynamic type
checking. It also supports automatic garbage collection.
h) GUI Programming and Databases - Python supports GUI applications that can created
and ported to many libraries and windows systems, such as Windows Microsoft
Foundation Classes (MFC), Macintosh, and the X Window system of Unix. Python also
provides interfaces to all major commercial databases.
1
CP1442 PYTHON PROGRAMMING Module 1
i) Broad Standard Library - Python's library is portable and cross platform compatible, on
UNIX, Linux, Windows and Macintosh. This helps in the support and development of a wide
range of applications from simple text processing to browsers and complex games.
HOW TO RUN PYTHON
There are three different ways to start Python.
You can start Python from Unix, DOS, or any other system that provides you
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. >pyt ho n.
Invoking the interpreter without passing a script file as a parameter brings up the following
prompt.
$ p ython
Type the following text at the Python prompt and press the Enter: >>>
print("Programming in Python!")
Programming in Python!
>>>
b) Script from the Command Line
This method invokes the interpreter with a script parameter which begins the execution of
the script and 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, as follows.
For Unix/Linux it is$pythonscript .pyor python% script . py. For Windows/ Dos it is c : >pyt ho n scr ip t .py
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 inPython!")
Now, try to run this program as follows.
$ p yt h o n f i r s t . p y
Programming in Python!
2
CP1442 PYTHON PROGRAMMING Module 1
c) Integrated Development Environment
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 is the Integrated Development Environment (IDE)
for UNIX and PythonWin is the first Windows interface for Python.
IDENTIFIERS
A Python identifier is a name used to identify a variable, function, class, module or any other
object. Python is case sensitive and hence uppercase and lowercase letters are considered distinct. The
following are the rules for naming an identifier in Python.
Class names start with an uppercase letter. All other identifiers start with a lowercase letter.
Eg: Person
Starting an identifier with a single leading underscore indicates that the identifier is private.
Eg: _sum
Starting an identifier with two leading underscores indicates a strongly private
identifier. Eg: _sum
If the identifier also ends with two trailing underscores, the identifier is a language-defined
special name. foo
RESERVED KEYWORDS
These are keywords reserved by programming language and prevent the user or the
programmer from using it as an identifier in a program. There are 33 keywords in python.
This number can vary with different versions. To retrieve the keywords in python the
following code can be given at the prompt. All keywords except True, False and None are in
lowercase. The following list in Table 1.1 shows the python keywords.
>>> print(keyword.kwlist)
[ „False‟, „None‟, „True‟, 'and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif',
'else', 'except', 'finally', 'for', 'from', 'global', ' if', 'import', 'in', 'is', 'lambda', ‟nonlocal‟,
'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
3
CP1442 PYTHON PROGRAMMING Module 1
Table 1.1 Python Keywords
VARIABLES
Variables are reserved memory locations to store values. Based on the data type of a variable, the
interpreter allocates memory and decides what can be stored in the reserved memory. Therefore, by
assigning different data types to variables, you can store integers, decimals or characters in these
variables.
Python variables do not need explicit declaration to reserve memory space. The declaration happens
automatically when you assign a value to a variable. The equal sign (=) is used to assign values to
variables. The operand to the left of the = operator is the name of the variable and the operand to the
right of the = operator is the value stored in the variable.
Example Program
print(a)
print(b)
print(name)
Here, 100, 1000.0 and "John" are the values assigned to a, b, and name variable respectively.
This produces the following result.
100
1000.0
John
Python allows you to assign a single value to several variables simultaneously. For example
a=b=c=1
Here, an integer object is created with the value 1, and all three variables are assigned to the same memory
location. You can also assign multiple objects to multiple variables. For example,
4
CP1442 PYTHON PROGRAMMING Module 1
a,b,c=1,2,”Tom”
Here, two integer objects with values 1 and 2 are assigned to variables a and b respectively, and one
string object with the value "Tom" is assigned to the variable c.
COMMENTS IN PYTHON
Comments are very important while writing a program. It describes what the source code has
done. Comments are for programmers for better understanding of a program. In Python, we use the
hash (#) symbol to start writing a comment. A hash sign (#) that is not inside a string literal begins a
comment. All characters after the # and up to the end of the physical line are part of the comment. It
extends up to the newline character. Python interpreter ignores comment.
Example Program
>»#DisplayHello
>»print("Hello")
For multiline comments one way is to use (#) symbol at the beginning of each line. The following
example shows a multiline comment. Another way of doing this is to use triple quotes, either '" or """.
Example 1
>>>#Threelines
Example 2
>>>and it endsafter
>>>Threelines"""
Both Example 1 and Example 2 given above produces the same result.
INDENTATION IN PYTHON
Most of the programming languages like C, C++ and Java use braces { } to define a block of code.
Python uses indentation. A code block (body of a function, loop etc.) starts with indentation and ends
with the first unindented line. The amount of indentation can be decided by the programmer, but it must
be consistent throughout the block. Generally four whitespaces are used for indentation and is preferred
over tabspace.
For example
5
CP1442 PYTHON PROGRAMMING Module 1
if True:
print("Correct”)
else:
print("Wrong”)
But the following block generates error as indentation is not properly followed.
if True:
print("Answer")
print("Correct")
else:
print("Answer")
print("Wrong")
MULTI-LINE STATEMENTS
Instructions that a Python interpreter can execute are called statements. For example a=1 is an
assignment statement. if statement, for statement, while statement etc. are other kinds of statements.
In Python, end of a statement. is marked by a newline character. But we can make a statement extend
over multiple line with the line continuation character(\). For example:
second item+ \
third item
Statements contained within the [],{ }or () brackets do not need to use the lin e
We could also put multiple statements in a single line using semicolons, as follows a = 1 ; b
= 2; c = 3
6
CP1442 PYTHON PROGRAMMING Module 1
MULTIPLE STATEMENT GROUP (SUITE)
A group of individual statements, which make a single code block is called a suite Python.
Compound or complex statements, such as if, while, def, and class require a head line and a suite.
Header lines begin the statement (with the keyword) and terminate with colon ( : ) and are followed by
one or more lines which make up the suite. For example
if expression :
suite
elif expression:
Suite
else :
suite
QUOTES IN PYTHON
Python accepts single („), double (") and triple ("' or “””) quotes to denote string literals. The same type
of quote should be used to start and end the string. The triple quotes, are used to span the string across
multiple lines. For example, all the following are legal.
INPUT, OUTPUTANDIMPORTFUNCTIONS
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 function converts the expressions you pass into a
string and writes the result to standard output.
Example 1
7
CP1442 PYTHON PROGRAMMING Module 1
Example 2
›››a=2
›››print ( "The value of a is" , a)
The value of a is 2
By default a space is added after the text and before the value of variable a. The syntax of print
function is given below.
Here, 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 and 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. The following shows an example for the above
syntax.
Example
>>>print(1,2,3,4)
>>>print(1,2,3,4,sep= „+')
1234
1+2+3+4
1+2+3+4%
The output can also be formatted to make it attractive according to the wish of a user.
8
CP1442 PYTHON PROGRAMMING Module 1
Example
p r in t ( " Yo u r n a me is : " , st r )
Output
E nt e r yo ur na me : Co l l in
M a r k Yo u r na me is : Co l l in
Mark
input function
The input([prompt]) function is equivalent to raw_input, except that it assumes the input is a
valid Python expression and returns the evaluated result to you.
Example 1
Output
E nt e r a nu mb e r : 5
T h e nu mb e r is : 5
Example 2
n = i np u t ( " E nt e r a n e xp r e s s io n: " ) ;
p r i n t ( " T h e r e s u l t i s : “, eval(n))
Output
Ent er an e xp re ssio n : 5* 2
T he r esu lt is : 10
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 and statements. Python
modules have a filename and end with the extension .py. Definitions inside a module can be imported to
another module or the interactive interpreter in Python. We use the import keyword to do this. For
example, we can import the math module by typing in import math.
9
CP1442 PYTHON PROGRAMMING Module 1
>>> import math
>>> print(math.pi )
3.141592653589793
OPERATORS
Operators are the constructs which can manipulate the value of operands. Consider the expression a =
b + c. Here a, b and c are called the operands and +, = , are called the operators. There are different types
of operators. The following are the types of operators supported by Python.
Arithmetic Operators
Comparison (Relational) Operators
Assignment Operators
Logical Operators
Bitwise Operators
Membership Operators
Identity Operators
Arithmetic Operators
Arithmetic operators are used for performing basic arithmetic operations. The following are the arithmetic operators
supported byPython. Table 1.2 showsthe arithmetic operators in Python.
Example Program
a, b, c = 10, 5, 2
print("Sum.",(a+b))
print("Difference=",(a-b))
10
CP1442 PYTHON PROGRAMMING Module 1
p r int ( " P r o d u c t =” , ( a * b) )
print ( "Quotient=”,(a/b) )
print (" Remainder=", ( b% c))
print ("Exponent=", ( b**2))
pr int ( " Flo o r D iv is io n= " , ( b/ / c) )
Output
Sum= 15
Difference= 5
pro duct = 50
Quo t ie nt = 2
Remainder= 1
E xpo nent = 25
F lo o r D iv is io n= 2
Comparison operators
These operators compare values on either sides of them and decide the relation among them. They are also
called relational operators. Python supports the following relational operators. Python supports the
following relational operators. Table 1.3 shows the comparison or relational operators in python.
Operator Description
Example Program
a, b=10,5
output
a==b is: False
Assignment Operators
Python provides various assignment operators. Various shorthand operators for addition,
subtraction, multiplication, division, modulus, exponent and floor division are also supported by Python.
Table 1.4 provides the various assignment operators.
Operator Description
*= It multiplies right operand withthe left operandand assign the result to left operand.
/= It divides left operand withthe right operand and assign the result to left operand.
%= It takes modulus using two operands and assign the result to left operand.
**= Performs exponential (power) calculation on operators and assign value to the left
operand.
//= It performs floor divisiononoperators and assign value to the left operand.
The assignment operator = is used to assign values or values of expressions to a variable. Example:
a = b+ c. For example c+=a is equivalent to c=c+a. Similarly c-=a is equivalent to c=c-a, c*=a is
equivalent to c=c*a, c/=a is equivalent to c=c/a, c%=a is equivalent to c=c%a, c**=a is equivalent to
c=c**a and c//=a is equivalent to c=c//a.
12
CP1442 PYTHON PROGRAMMING Module 1
Example Program
a, b=10, 5
a+=b
print(a)
a, b =10,5
a- =b
print(a)
a, b =10,5
a*=b
print(a)
a, b =10,5
a/=b
print(a)
b, c = 5, 2
b%=c
print(b)
b, c = 5, 2
b**=c
print(b)
b, c = 5, 2
b//=c
print(b)
output
15
50
13
CS1543: PYTHON PROGRAMMING Module 1
25
Bitwise Operators
Bitwise operator works on bits and performs bit by bit operation. The following are the bit wise operators
supported by python. Table 1.5 gives a description of bitwise operators in python.
» Binary Right The left operand's value is moved right bythe number of bits specified by
Shift the right operand.
Example Program
a, b = 60, 2
print(a&b)
print(a|b)
print(a^b)
print(~a)
print(a>>b)
print(a<<b)
output
62
14
CS1543: PYTHON PROGRAMMING Module 1
62
-61
15
240
b=0000 0010
Logical Operators
Table 1.6 shows the various logical operators supported by Python language.
and Logical AND If both the operands are true then condition becomes true.
or Logical OR If any of the operands are true then condition becomes true.
not Logical NOT Used to reverse the logical state of its operand.
Example Program
a, b, c, d=10, 5, 2, 1
Output
True
True
False
Membership operators
Python‟s membership operators test for membership in a sequence, such as strings, lists or tuples. There are
two membership operators.
15
CS1543: PYTHON PROGRAMMING Module 1
Table 1.7 shows the various membership operators supported by Python language.
Operator Description
Example Program
s=‟abcde‟
print(„a‟ in s)
print(„f‟ in s)
print(„f‟ not in s)
Output
True
False
True
Identity Operators
Identity operators compare the memory locations of two objects. There are two identity operators as given
below.
Operator Description
is It is evaluated to be true if the variables present on either sides of the operator point
to the same object and false otherwise.
is not It is evaluated to be false if the variables on either side of the operator point to the
same object and true otherwise.
Example Program
a,b,c=10,10,5
print(a is b)
print(a is c)
16
CS1543: PYTHON PROGRAMMING Module 1
print(a is not b)
Output
True
False
False
Operator Precedence
The following table lists all operators from highest precedence to lowest precedence. Operator
associativity determines the order of evaluation, when they are of the same precedence, and are not
grouped by parenthesis. An operator may be left-associative or right associative. In left associative, the
operator falling on the left side will be evaluated first, while in right- associative, operator falling on the
right will be evaluated first. In Python, ‘=’ and ‘**’ are right associative while all other operators are
left associative. The precedence of the operators is important to find out since it enables us to know which
operator should be evaluated first. The precedence table of the operators in python is given below.
Operator Description
** The exponent operator is given priority over all the others used in the expression.
~, +, - The negation(complement), unary plus and minus.
*, /, %, // The multiplication, divide, modules, reminder, and floor division.
+, - Binary plus and minus
>>, << Left shift and right shift
& Binary AND
^, | Binary XOR and OR
<=, < >, >= Comparison operators (less then, less then equal to, greater then, greater then
equal to).
<>, == ,!= Equality operators.
= ,%= ,/= ,//= Assignment operators
,-= ,+=
*= **=
is, is not Identity operators
in ,not in Membership operators
not , or and Logical operators
Numbers.
String
17
CS1543: PYTHON PROGRAMMING Module 1
List ·
Tuple
Set
Dictionary
NUMBERS
Number data types store numeric values. Number objects are created when you assign a value to them. For
example a = 1, b = 20. You can also delete the reference to a number object by using the del statement.
The syntax of the del statement is as follows.
You can delete a single object or multiple objects by using the del statement. For example
del a
del a,b
Python supports four different numerical types.
Integers can be of any length, it is only limited by the memory available. A floating point number is
accurate up to 15 decimal places. Integer and floating points are separated by decimal points. 1 is
integer, 1.0 is floating point number. Complex numbers are written in the form, x + yj , where x is the
real part and y is the imaginary part.
Example Program
Output
a=1
b= 1.5
c= 231456987
d= (2+9j)
Mathematical Functions
Python provides various built-in mathematical functions to perform mathematical calculations. The
following Table 2.1 provides various mathematical functions and its purpose. For using the below
18
CS1543: PYTHON PROGRAMMING Module 1
functions, all functions except abs(x), max(x1,x2,... xn), min(x1,x2,...xn), round(x[n]) and pow(x,y)
need to import the math module because these functions reside in the math module. The math module
also defines two mathematical constants pi and e.
Function Description
abs(x) Returns the absolute value of x.
sqrt(x) Finds the square root of x.
ceil(x) Finds the smallest integer not less than x.
floor(x) Finds the largest integer not greater than x
pow(x,y) Finds x raised to y
exp(x) Returns ex ie exponential of x.
fabs(x) Returns the absolute value of x.
log(x) Finds the natural logarithm of x for x>0.
log10(x) Finds the logarithm to the base 10 for x0.
max(x1,x2,...xn) Returns the largest of its arguments
min(x1,x2,... xn) Returns the smallest of its arguments
round(x,[n]) In case of decimal numbers, x will be rounded to n digits.
modf(x) Returns the integer and decimal part as a tuple. The integer
part is returned as a decimal
Example Program
import math
print("Absolute value of -120:", abs (-120))
print("Square root of 25:", math.sqrt (25))
print("Ceiling of 12.2:", math.ceil(12.2))
print("Floor of 12.2:", math.floor (12.2))
print("2 raised to 3:", pow (2,3))
print("Exponential of 3:", math.exp (3))
print("Absolute value of -123:", math.fabs (-123))
print("Natural Logarithm of 2:", math.log(2))
print("Logarithm to the Base 10 of 2:", math.log10 (2))
print("Largest among 10, 4, 2:", max (10,4,2))
print("Smallest among 10,4, 2:",min(10,4,2))
print("12.6789 rounded to 2 decimal places:", round (12.6789,2))
print("Decimal part and integer part of 12.090876:", math.modt
(12.090876))
Output
19
CS1543: PYTHON PROGRAMMING Module 1
Ceiling of 12.2: 13
Floor of 12.2: 12
2 raised to 3: 8
Exponential of 3: 20.085536923187668
Absolute value of -123: 123.0
Natural Logarithm of 2: 0.69314 71805599453
Logarithm to the Base 10 of 2: 0.3010299956639812
Largest among 10, 4, 2: 10
Smallest among 10,4, 2: 2
12.6789 rounded to 2 decimal places: 12.68
Decimal part and integer part of 12.090876: (0.09087599999999973,
12.0)
Trigonometric Functions
There are several built in trigonometric functions in Python. The function names and its purpose are
listed in Table 2.2
Function Description
sin(x) Returns the sine of x radians
cos(x) Returns the cosine of x radians
tan(x) Returns the tangent of x radians
asin(x) Returns the arc sine of x, in radians.
acos(x) Returns the arc cosine of x, in radians.
atan(x) Returns the arc tangent of x, in radians.
atan2(y,x) Returns atan(y/x ), in radians
hypot(y) Returns the Euclidean form, sqrt(x*x + y*y)
degrees(x) Converts angle x from radians to degrees
radians() Converts angle x from degrees to radians
Example Program
import math
print("Sin (90):", math.sin(90))
print("Cos (90):", math.cos(90))
print("Tan (90):", math. tan(90))
print("asin(1):", math.asin(1))
print("acos (1):", math.acos (1))
print("atan(l):",math.atan(1))
print("atan2 (3,2):",math.atan2 (3,2))
print("Hypotenuse of 3 and 4:", math.hypot (3,4))
print("Degrees of 90:", math. degrees (90))
20
CS1543: PYTHON PROGRAMMING Module 1
print("Radians of 90: , math.radians (90))
Output
Sin(90): 0.893996663601
Cos (90): -0.448073616129
Tan (90): -1.99520041221
asin(l): 1.57079632679
acos (1): 0.0
atan(1): 0.785398163397
atan2 (3,2): 0.992793723247
Hypotenuse of 3 and 4: 5.0
Degrees of 90: 5156.62015618
Radians of 90: 1.57079632679
There are several random number functions supported by Python. Random numbers have applications
in research games, cryptography, simulation and other applications. Table 2.3 shows the commonly
used random number functions in Python. For using the random number functions, we need to import
the module random because all these functions reside in the random module.
Function Description
choice (sequence) Returns a random value from a sequence like list, tuple, string etc
shuttle(list) Shuttles the items randomly in a list. Returns none.
random() Returns a random floating point number which lies between 0 and i
randrange([start,] Returns a randomly selected number from a range where start shows the
stop[,step]) starting of the range, stop shows the end of the range and step decides the
number to be added to decide a random number
seed([x]) Gives the starting value for generating a random number. Returns none.
This function is called before calling any other random module function.
uniform(xy) Generates a random floating point number n such that n>x and n<y
Example Program
import random
S=‟abcde'
print("choice (abcde):", random.choice(s))
list = [10,2,3,1, 8, 19]
print("shuffle (list):", random.shuffle(list))
print ("random.seed(20):", random.seed(20))
print("random():", random.random())
21
CS1543: PYTHON PROGRAMMING Module 1
print("uniform (2,3):", random.uniform(2,3))
print("randrange (2,10,1):", random.randrange (2,10,1))
Output
choice(abcde): b
shuffle (list): None
random.seed (20): None
random(): 0.905639676175
uniform (2,3): 2.68625415703
randrange (2,10,1): 8
STRINGS
Strings in Python 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 and ending at -1. The plus
(+) sign is the string concatenation operator and the asterisk (*) is the repetition operator. The %
operator is used for string formatting.
Example Program
Escape Characters
An escape character is a character that gets interpreted when placed in single or double quotes. They
are represented using backslash notation. These characters are non printable. The following Table 2.4
shows the most commonly used escape characters and their description.
22
CS1543: PYTHON PROGRAMMING Module 1
This operator is unique to strings and is similar to the formatting operations of the printf() function of the
C programming language. The following Table 2.5 shows various format symbols and their conversion.
23
CS1543: PYTHON PROGRAMMING Module 1
print("%x is the hexadecimal equivalent of %d" %(10,10)) #usage of %X
print("%e is the exponential equivalent of %f"
(10.98765432,10.98765432)) #usage of %e and %f
print("%E is the exponential equivalent of %f"
(10.98765432,10.98765432)) #usage of %E and %f
print ( “%.2f”, %(32.1274)) #usage of %f for printing upto two decimal
places
Output
The first letter of apple is a
The sum=-12
The sum=-12
The sum-12
10 is the octal octal equivalent of 8
a is the hexadecimal equivalent of 10
2. lower() - Returns a copy of the string in which all uppercase alphabets in a string are converted to
lowercase alphabets.
Example Program
#Demo of lower()
S='Learning Python is fun!‟
print(s.lower())
Output
learning python is fun!
24
CS1543: PYTHON PROGRAMMING Module 1
3.upper() - Returns a copy of the string in which all lowercase alphabets in a string are converted to
uppercase alphabets.
Example Program
#Demo of upper()
S='Learning Python is fun!‟
print(s.upper())
Output
LEARNING PYTHON IS PUN !
4. Swapcase() - Returns a copy of the string in which the case of all the alphabets are swapped. ie. all the
lowercase alphabets are converted to uppercase and vice versa.
Example Program
#Demo of swapcase ()
S="LEARNing PYTHON is fun!”
print(s.swapcase())
Output
learnING Python IS FUN!
5. capitalize() - Returns a copy of the string with only its first character capitalized.
Example Program
#Demo of capitalize()
s=' learning Python is fun!‟
print(s.capitalize())
Output
Learning python is fun!
6.title()- Returns a copy of the string in which first character of all the words are capitalized
Example Program
#Demo of title()
s=‟ learning Python is fun!‟
print(s.title())
Output
Learning Python Is Fun!
7.Istrip() - Returns a copy of the string in which all the characters have been stripped(removed) from the
beginning. The default character is whitespaces.
Example Program
#Demo of lstrip()
25
CS1543: PYTHON PROGRAMMING Module 1
s=‟ learning Python is fun!'
print(s.lstrip())
s=‟*********learning Python is fun!'
print(s.lstrip (**))
Output
learning Python is fun!
learning Python is fun!
8. rstrip()- Returns a copy of the string in which all the characters have been stripped(removed) from the
right end. The default character is whitespaces.
Example Program
#Demo of rstrip
S='learning Python is fun! ‟
print(s.rstrip())
S='learning Python is fun! ******‟
print(s.rstrip('*'))
Output
learning Python is fun!
learning Python is fun!
9. strip()- Returns a copy of the string in which all the characters have been stripped(removed) from the
beginning and end. It performs both lstrip() and rstrip (). The default character is whitespaces.
Example Program
#Demo of strip()
s=' learning Python is fun!‟
print(s.strip())
s='******learning Python is fun! ******‟
print(s.strip ('*'))
Output
learning Python is fun!
learning Python is fun!
Example Program
#Demo of max(str)
s=‟learning Python is fun!‟
print("Maximum character is , max(s))
Output
Maximum character is : y
26
CS1543: PYTHON PROGRAMMING Module 1
11. min(str) - Returns the minimum alphabetical character from string str
Example Program
#Demo of min(str)
s=' learning-Python-is-fun‟
print("Minimum character is :', min(s))
Output
Minimum character is : -
12. replace(old, new [,max] )- Returns a copy of the string with all the occurrences of substring old is
replaced by new. The max is optional and if it is specified, the first occurrences specified in max are
replaced.
Example Program
# Demo of replace (old, new [,max])
s="This is very new. This is good”
print(s.replace('is', 'was'))
print(s.replace('is', 'was', 2))
Output
Thwas was very new. Thwas was good
Thwas was very new. This is good
13. center(width, fillchar) - Returns a string centered in a length specified in the width variable. Padding
is done using the character specified in the fillchar. Default padding is space.
Example Program
# Demo of center (width, fillchar)
s="This is Python Programming"
print(s.center (30, '*'))
print(s.center (30)
Output
**This is Python Programming**
This is Python Programming
14. ljust(width[,fillchar]) - Returns a string left-justified in a length specified in the width variable.
Padding is done using the character specified in the fillchar. Default padding is space.
Example Program
# Demo of ljust (width[, fillchar))
s="This is Python Programming"
print(s. ljust (30,'*'))
print(s.ljust (30))
Output
This is Python Programming ****
This is Python Programming
27
CS1543: PYTHON PROGRAMMING Module 1
15. rjust(width[,fillchar]) - Returns a string right-justified in a length specified in the width variable.
Padding is done using the character specified in the fillchar. Default padding is space.
Example Program
# Demo of rjust (width[, fillchar])
s="This is Python Programming"
print(s.rjust (30, *'))
print(s.rjust (30))
Output
****This is Python Programming
This is Python Programming
16. zfill(width) - The method zfill() pads string on the left with zeros to fill width.
Example Program
# Demo of zfill(width)
S="This is Python Programming"
print(s.zfill(30))
Output
0000 This is Python Programming
17. count(str,beg=0,end=len(string)) - Returns the number of occurrences of str in the range beg and end.
Example Program
# Demo of count (str, beg=0, end=len(string))
S="This is Python Programming"
print(s.count('i', 0,10))
print(s.count('i', 0,25))
Output
18. find(str, beg=0,end=len(string)) - Returns the index of str if str occurs in the range beg and end and
returns -1 if it is not found.
Example Program
# Demo of find (str, beg=0, end=len(string) )
S="This is Python Programming"
print(s.find('thon', 0,25))
print(s.find('thy))
Output
10
-1
28
CS1543: PYTHON PROGRAMMING Module 1
Example Program
# Demo of rfind (str, beg=0, end=len(string))
S="This is Python Programming"
print(s.rfind('thon',0,25))
print(s.rfind('thy'))
Output
10
-1
20. index(str, beg=0,end=len(string)) - Same as that of find but raises an exception if the item is not
found
Example Program
# Demo of index (str, beg=0, end=len (string))
S="This is Python Programming"
print(s.index ('thon', 0,25))
print(s.index ('thy'))
Output
10
Traceback (most zecent call last):
File "main.py", line 4, in <module>
print s. index ('thy')
ValueError: substring not found
Example Program
# Demo of rindex (str, beg=0, end=len (string))
S="This is Python Programming"
print(s.rindex ('thon', 0,25))
print(s.rindex ('thy'))
Output
10
Traceback (most recent call last):
File "main.py", line 4, in <module>
print s.index ('thy')
ValueError: substring not found
22. startswith(suffix, beg=0,end=len(string))- It returns True if the string begins with the specified
suffix, otherwise return false.
29
CS1543: PYTHON PROGRAMMING Module 1
Example Program
# Demo of start with(suffix, beg=0, end=len (string))
s=”Python programming is fun”
print(s.startswith('is', 10, 21))
s="Python programming is fun"
print(s.startswith('is',19,25))
Output
False
True
23. endswith(suffix, beg=0,end=len(string))- It returns True if the string ends with the specified suffix,
otherwise return false.
Example Program
# Demo of endswith(suffix, beg=0, end=len(string)
S="Python programming is fun"
print(s.endswith('is',10,21))
S="Python programming is fun"
print(s.endswith('is', 0,25))
Output
True
False
24. isdecimal() - Returns True if a unicode string contains only decimal characters and False otherwise.
To define a string as unicode string, prefix 'u' to the front of the quotation marks.
Example Program
# Demo of isdecimal()
S="This is Python 1234"
print(s.isdecimal())
s=u"123456"
print(s.isdecimal())
Output
False
True
25. Isalpha() - Returns True if string has at least 1 character and all characters are alphabetic and False
otherwise.
Example Program
# Demo of isalpha()
s="This is Python1234"
print(s.isalpha())
S="Python"
print(s.isalpha())
30
CS1543: PYTHON PROGRAMMING Module 1
Output
False
True
26. isalnum()- Returns True if string has at least 1 character and all characters are alphanumeric and False
otherwise.
Example Program
# Demo of isalnum ()
S=”**** Python1234"
print(s.isalnum())
S=”Python1234"
print(s.isalnum())
Output
False
True
27.isdigit()- Returns True if string contains only digits and False otherwise
Example Program
# Demo of isdigit()
S*****Python1234"
print(s.isdigit())
S="123456"
print(s. isdigit())
Output
False
True
28. islower() - Returns True if string has at least 1 cased character and all cased characters are in
lowercase and False otherwise.
Example Program
# Demo of islower)
S="Python Programming"
print(s.islower())
s="python programming"
print(s.islower())
Output
False
True
29.isupper() - Returns True if string has at least one cased character and all cased characters are in
uppercase and False otherwise.
Example Program
# Demo of isupper()
31
CS1543: PYTHON PROGRAMMING Module 1
S="Python Programming
print(s.isupper())
S="PYTHON PROGRAMMING
print(s.isupper())
Output
False
True
30. isnumeric()- Returns True if a unicode string contains only numeric characters and False otherwise.
Example Program
# Demo of isnumeric()
s="Python Programming1234"
print(s.isnumeric())
s="12345"
print(s.isnumeric())
Output
False
True
31. isspace() - Returns True if string contains only whitespace characters and False otherwise.
Example Program
# Demo of isspace()
s="Python Programming"
print(s.isspace())
s=“ “
print (s.isspace())
Output
False
True
32. istitle() - Returns True if string is properly "titlecased" and False otherwise. Title case means each
word in a sentence begins with uppercase letter.
Example Program
#Demo of istitle()
$="Python programming is fun"
print(s.istitle())
S="Python Programming Is Fun"
print(s.istitle())
Output
False
True
32
CS1543: PYTHON PROGRAMMING Module 1
33. expandtabs(tabsize=8) - It returns a copy of the string in which tab characters ie.'\t are expanded
using spaces using the given tabsize. The default tabsize is 8.
Example Program
34.join(seq) - Returns a string in which the string elements of sequence have been joined by a separator.
Example Program
# Demo of join(seg)
s=”-“
seq= ("Python", "Programming")
print(s.join(seq))
s="*”
seq= ("Python", "Programming")
print(s.join(seq))
Output
Python-Programming
Python*Programming
35. split(str="", num=string.count(str)) - Returns a list of all the words in the string, using str as the
separator (splits on all whitespace if left unspecified), optionally limiting the number of splits to num.
Example Program
#Demo of split(str="", num=string.count (str))
S="Python programming is fun"
print(s.split(„ „))
s="Python*programming*is*fun"
print(s.split('*'))
s=”Python*programming*is*fun"
print(s.split('*‟,2))
Output
[„Python', 'programming', 'is', 'fun‟ ]
[„Python', 'programming', 'is', 'fun']
['Python', 'programming', 'is*fun']
36. Splitlines(num=string.count('\n') - Splits string at all (or num) NEWLINEs and returns a list of each
line with NEWLINEs removed. If num is specified, it is assumed that line breaks need to be included in
the lines.
33
CS1543: PYTHON PROGRAMMING Module 1
Example Program
#Demo of splitlines (num=string.count('\n')
S="Python\nprogramming\nis\nfun“
print(s.splitlines())
print(s.splitlines (0))
print(s.splitlines (1) )
Output
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 [ ]. To some extent, lists are similar to arrays in C. One difference between them is that all the
items belonging to a list can be of different data type. The values stored in a list can be accessed using the
slice operator ([ ] and [ : ]) with indices starting at 0 in the beginning of the list and ending with -1. The
plus (+) sign is the list concatenation operator and the asterisk (*) is the repetition operator.
Example Program
first_list = ['abcd', 147, 2.43, 'Tom', 74.9]
small_list = [111,'Tom']
We can update lists by using the slice on the left hand side of the assignment operator.
Updates can be done on single or multiple elements in a list.
Example Program
#Demo of List Update
34
CS1543: PYTHON PROGRAMMING Module 1
list = ['abcd', 147, 2.43,'Tom', 74.9]
print("Item at position 2", list[2] )
list[2]=500
print("Item at position 2", list[2])
print("Item at Position 0 and 1 is", list [0],list[1])
list[0]=20; list[1] ='apple'
Output
Item at position 2= 2.43
Item at position 2=500
Item at Position 0 and 1 is abcd 147
Item at Position 0 and 1 is 20 apple
To remove an item from a list, there are two methods. We can use del statement or remove() method.
Example Program
*Demo of List Deletion
list = ['abcd', 147, 2.43, 'Tom', 74.9]
print (list)
del list [2]
print("List after deletion:", list)
Output
['abcd', 147, 2.43. Tom]
List after deletion: ['abcd', 147, 'Tom', 74.9]
Example Program
#Demo of len(list)
list1=['abcd', 147, 2.43, 'Tom']
print(len(list1))
Output
Example Program
#Demo of max (list)
list1= [1200, 147, 2.43, 1.12]
list2 = [213, 100, 289]
print("Maximum value in: ", list1, "is", max(list1))
print("Maximum value in: , list2, "is", max(list2))
Output
35
CS1543: PYTHON PROGRAMMING Module 1
Maximum value in: [1200, 147, 2.43, 1.12] is 1200
Maximum value in: [213, 100, 289] is 289
Example Program
#Demo of min(list)
list1=[1200, 147, 2.43, 1.12]
list2 = [213, 100, 289]
5. map(aFunctionaSequence)-One of the common things we do with list and other sequences is applying
an operation to each item and collect the result. The map(aFunction, aSequence) function applies a passed-
in function to each item in an iterable object and returns a list containing all the function call results.
Example Program
str=input("Enter a list (space separated) :")
lis=list (map (int, str.split()))
print(lis)
Output
Enter a list (space separated) : 1 2 3 4
[1, 2, 3, 4]
In the above example, a string is read from the keyboard and each item is converted into int using
map(aFunction, aSequence) function.
Example Program
#Demo of list.append(obj)
list = ['abcd', 147, 2.43, 'Tom']
36
CS1543: PYTHON PROGRAMMING Module 1
print("old List before Append:", list)
list.append(100)
print("New List after Append :", list)
Output
old List before Append: ['abcd', 147, 2.43, 'Tom']
New List after Append: ["abcd', 147, 2.43, 'Tom', 100]
2. list.count(obj) - Returns how many times the object obj appears in a list:
Example Program
#Demo of list.count (obj)
List = ['abcd', 147, 2.43, 'Tom', 147,200, 147]
Example Program
#Demo of list.remove(obj)
list1 = ['abcd', 147, 2.43, 'Tom']
list1.remove( 'Tom')
print (list1)
Output
['abcd', 147, 2.43]
4. list.index(obj) - Returns index of the object obj if found, otherwise raise an exception indicating that
value does not exist.
Example Program
#Demo of list.index (obj)
list1 = ['abcd', 147, 2.43, 'Tom']
print (list1.index (2.43))
Output
Example Program
#Demo of list.extend(seg)
list1 = ['abcd', 147, 2.43,‟Tom']
37
CS1543: PYTHON PROGRAMMING Module 1
list2 = ['def', 100]
list1.extend(list2)
print(list1)
Output
Example Program
#Demo of list.reverse()
listl = ['abcd', 147, 2.43, 'Tom']
list1.reverse()
print(list1)
Output
7. list.insert(index,obj) - Returns a list with object obj inserted at the given index
Example Program
#Demo of list.insert lindex, obj)
8. list.sort([Key=None, Reverse=False]) - Sorts the items in a list and returns the list. If a function is
provided, it will compare using the function provided.
Example Program
#Demo of list.sort ( [Key=None, Reverse=Falsel)
list1=[890, 147, 2.43, 100]
print("List before sorting:", list1)
listl.sort()
print("List after sorting in ascending order:", list1)
Output
List before sorting: [840, 147, 2.43, 100]
List after sorting in ascending order: [2.43, 100, 147,840]
The following example illustrates how to sort the list in descending order.
38
CS1543: PYTHON PROGRAMMING Module 1
Example Program
9. list.pop([index]) - Removes or returns the last object obj from a list. We can even pop out any item in a
list with the index specified.
Example Program
#Demo of list.pop([index])
list1= ['abcd', 147, 2.43, 'Tom']
print("List before poping", list1)
list1.pop(-1)
print("List after poping :", list1)
item=list1.pop(-3)
print("Popped item: ", item)
print("List after poping:", list1)
Output
List before poping ['abcd', 147, 2.43, 'Tom']
List after poping: ['abcd', 147, 2.43]
Example Program
#Demo of list.clear()
list1 = ['abcd', 147, 2.43, 'Tom']
print("List before clearing:", list1)
list1.clear()
print("List after clearing:", list1)
Output
List before clearing: ['abcd', 147, 2.43, 'Tom']
Example Program
#Demo of list.copy ()
list1 = ['abcd', 147, 2.43, Tom']
39
CS1543: PYTHON PROGRAMMING Module 1
print("List before clearing:", list1)
list2=list1.copy ()
list1.clear()
print("List after clearing:", list1)
print("Copy of the list:", list2)
Output
List before clearing: ['abcd', 147, 2.43, 'Tom']
List after clearing: [ ]
Copy of the list: ['abcd', 147, 2.43, 'Tom']
Example Program
#Demo of List as Stack
stack=[10,20,30,40,50]
stack.append(60)
print ("Stack after appending:", stack)
stack.pop()
print("Stack after poping:" , stack)
Output
Stack after appending: [10, 20, 30, 40, 50, 60]
Stack after poping: [10, 20, 30, 40, 50 ]
It is also possible to use a list as a queue, where the first element added is the first element retrieved.
Queues are First In First Out (FIFO) data structure. But lists are not efficient for this purpose. While
appends and pops from the end of list are fast, doing inserts or pops from the beginning of a list is slow
since all of the other elements have to be shifted by one.
To implement a queue, Python provides a module called collections in which a method called deque is
designed to have fast appends and pops from both ends.
Example Program
#Demo of List as Queue
from collections import deque
queue = deque (["apple", "orange", "pear"])
queue. append("cherry") # cherry arrives
queue.append( "grapes") # grapes arrives
queue.popleft() # The first to arrive now leaves
queue.popleft() # The second to arrive now leaves
print (queue) # Remaining queue in order of arrival
40
CS1543: PYTHON PROGRAMMING Module 1
Output
deque (['pear', 'cherry', 'grapes'])
TUPLE
A tuple is another sequence data type that is similar to the list. A tuple consists of a number of values
separated by commas. The main differences between lists and tuples are lists are enclosed in square
brackets ( [ ] ) and their elements and size can be changed, while tuples are enclosed in parentheses ( ( ) )
and cannot be updated. Tuples can be considered as read-only lists.
Example Program
first_tuple = ('abcd', 147, 2.43, 'Tom', 74.9)
small_tuple = (111, 'Tom')
print(first_tuple) # Prints complete tuple
print(first_tuple[0]) # Prints first element of the tuple
print(first tuple[1:3]) # Prints elements starting from 2nd till 3rd
print(first_tuple[2:]) # Prints elements starting from 3rd element
print(small_tuple * 2) # Prints tuple two times
print(first_tuple + small tuple) # Prints concatenated tuples
Output
('abcd', 147, 2.43, Tom', 74.9)
abcd
(147, 2.43)
(2.43, 'Tom', 74.9)
(111, Tom', 111, 'Tom')
('abcd', 147, 2.43, Tom'. 74.9, 111, 'Tom')
The following code is invalid with tuple whereas this is possible with lists
first_list =['abcd', 147, 2.43,'Tom', 74.9]
first_tuple = ('abcd', 147, 2.43, 'Tom', 74.9)
first_tuple [2] = 100 # Invalid syntax with tuple
first_list [2] = 100 # Valid syntax with list
To delete an entire tuple we can use the del statement. Example del tuple. It is not possible to remove
individual items from a tuple. However it is possible to create tuples which contain mutable objects, such
as lists.
Example Program
#Demo of Tuple containing Lists
t=([1,2,3],['apple', 'pear', 'orange'])
print(t)
Output
([1, 2, 3], ['apple', 'pear', 'orange'])
41
CS1543: PYTHON PROGRAMMING Module 1
It is possible to pack values to a tuple and unpack values from a tuple. We can create tuples even without
parenthesis. The reverse operation is called sequence unpacking and works for any sequence on the right-
hand side. Sequence unpacking requires that there are as many variables on the left side of the equals sign
as there are elements in the sequence.
Example Program
#Demo of Tuple packing and unpacking
t="apple",1, 100
print (t)
x, y, z= t
print(x)
print(y)
print(2)
Output
('apple', 1, 100)
apple
1
100
Example Program
#Demo of len (tuple)
tuplel = ('abcd', 147, 2.43, 'Tom')
print(len(tuplel))
Output
4
Example Program
#Demo of min (tuple)
42
CS1543: PYTHON PROGRAMMING Module 1
tuplel = (1200, 147, 2.43, 1.12)
tuple2 = (213, 100, 289)
print("Minimum value in: ", tuplel, "is", min(tuple1))
print("Minimum value in: ", tuple2, "is", min(tuple2))
Output
Minimum value in: (1200, 147, 2.43, 1.12) is 1.12
Minimum value in: (213, 100, 289) is 100
Example Program
#Demo of tuple (seg)
list = ['abcd', 147, 2.43, Tom']
print("Tuple:", tuple(list))
Output
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 and they may be of different types (integer, float, tuple, string etc.).
Items in a set are not ordered. Since they are unordered we cannot access or change an element of set
using indexing or slicing. We can perform set operations like union, intersection, difference on two 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( ).
Example Program
# Demo of Set Creation
sl={1,2,3} #set of integer numbers
print (s1)
{ 1, 2, 3}
{1, 3, 2.4, "apple', 'Tom' }
{1, 2, 3, 4}
43
CS1543: PYTHON PROGRAMMING Module 1
Built-in Set Functions
1. len(set) - Returns the length or total number of items in a set.
Example Program
#Demo of len(set)
set1= {'abcd', 147, 2.43, 'Tom'}
print(len (set1))
Output
Example Program
#Demo of max (set)
set1 ={1200, 147, 2.43, 1.12} .
set2 = {213, 100, 289}
print ("Maximum value in: ", set1, "is", max (set1))
print("Maximum value in: ", set2, "is", max(set 2))
Output
Maximum value in: {1200, 1.12, 2.43, 147} is 1200
Maximum value in: {289, 100, 213} is 289
Example Program
#Demo of min(set)
set1 = {1200, 147, 2.43,1.12}
set2 = {213, 100, 289}
print("Minimum value in: ", set1, "is", min(set1))
print ("Minimum value in: ", set2, "is", min(set2))
Output
Minimum value in: {1200, 1.12, 2.43, 147} is 1.12
Minimum value in: {289, 100, 213} is 100
Example Program
#Demo of sum(set)
set1={147, 2.43}
set2 = {213, 100, 289}
print("Sum of elements in", set1, "is", sum(set1))
print("Sum of elements in", set2,"is", sum(set2))
44
CS1543: PYTHON PROGRAMMING Module 1
Output
Sum of elements in {147, 2.43} is 149.43
Sum of elements in {289, 100, 213) is 602
5.sorted(set)- Returns a new sorted list. The set does not sort itself.
Example Program
#Demo of sorted (set)
set1= {213, 100, 289, 40, 23,1, 1000}
set2 = sorted (set1)
print("Sum of elements before sorting:”,set1)
print("Sum of elements after sorting:", set 2)
Output
Sum of elements before sorting:{1, 100, 289, 1000, 40, 213, 23}
Sum of elements after sorting: [1, 23, 40, 100, 213, 289, 1000]
6.enumerate(set) - Returns an enumerate object. It contains the index and value of all the items of set as a
pair.
Example Program
#Demo of enumerate (set)
set1 = {213, 100, 289, 40, 23, 1, 1000}
print ("enumerate (set):” enumerate (set1))
Output
enumerate (set): <enumerate object at 0x7f0a73573690>
7. any(set) - Returns True, if the set contains at least one item, False otherwise.
Example Program
#Demo of any (set)
set1 = set( )
set2={1,2,3,4}
print("any (set):", any (set 1))
print("any (set):", any (set 2))
Output
any (set): False
any (set) : True
8. all(set) - Returns True, if all the elements are true or the set is empty.
Example Program
#Demo of all(set)
setl =set()
set 2={1,2,3,4}
print("all(set):", all(set1))
45
CS1543: PYTHON PROGRAMMING Module 1
print("all(set):", all (set1))
Output
all (set) : True
all (set) : True
Example Program
#Demo of set.add(obj)
set1={3, 8, 2, 6}
print("Set before addition:", set 1)
set1.add (9)
print("Set after addition:", set1)
Output
Set before addition:{8, 2, 3, 6}
Set after addition:{8, 9, 2, 3, 6}
2. set.remove(obj) - Removes an element obj from the set. Raises KeyError if the set is empty
Example Program
#Demo of set.remove(obj)
set1={3,8,2,6}
print("Set before deletion:", set1)
set1.remove(8)
print("Set after deletion:", set1)
Output
Set before deletion:{8, 2, 3, 6}
Set after deletion:{2, 3, 6}
3. set discard(obj) - Removes an element obj from the set. Nothing happens if the element to be deleted is
not in the set.
Example Program
#Demo of set. discard (obj)
setl={3, 8, 2, 6}
print("Set before discard:, set1)
setl.discard(8)
print("Set after discard:",setl) # Element is present
set1.discard(9)
print("Set after discard:", setl) #element is not present
Output
Set before discard: {8, 2, 3, 6}
Set after discard: {2, 3, 6}
46
CS1543: PYTHON PROGRAMMING Module 1
4 set.pop() - Removes and returns an arbitrary set element. Raises KeyError if the set is empty.
Example Program
#Demo of set.pop()
set1={3, 8, 2, 6}
print("Set before pop:", set1)
set1.pop()
print("Set after poping:", set1)
Output
Set before pop:{8, 2, 3, 6}
Set after poping: {2, 3, 6}
Example Program
#Demo of seti.union(set2)
setl={3, 8, 2,6}
print("Set 1:", set1)
set2={4,2,1,9}
print("Set 2:", set2)
set3=set1.union(set 2) #unique values will be taken
print("Union:", set3)
Output
Set1:{8, 2, 3, 6}
Set 2:{9, 2, 4, 1}
Union:{1, 2, 3, 4, 6, 8, 9}
6. set1.update(set2) - Update a set with the union of itself and others. The result will be stored in set1.
Example Program
#Demo of set1.update (set2)
setl={3,8,2,6}
print("Set 1:", set 1)
set2={4,2,1,9}
print("Set 2:", set2)
setl.update(set 2) #Unique values will be taken
print("Update Method.", set1)
Output
Set1:{8, 2, 3, 6}
Set 2:{9, 2, 4, 1}
Update Method:{1, 2, 3, 4, 6, 8, 9}
47
CS1543: PYTHON PROGRAMMING Module 1
7. set1.intersection(set2) - Returns the intersection of two sets as a new set
Example Program
#Demo of set1.intersection(set 2)
set1={3, 8, 2,6}
print("Set1:".set1}
set2= {4,2,1,9}
print("Set 2:", set 2)
set3 = set1.intersection (set 2)
print("Intersection:", set3)
Output
Set1: (8, 2, 3, 6}
Set 2:{9, 2, 4, 1}
Intersection:{2}
8. set1.intersection_update() - Update the set with the intersection of itself and another. The result will be
stored in setl.
Example Program
#Demo of set1.intersection_update (set 2)
set1={3, 8, 2,6}
print("Set 1:", set1)
set2={4,2,1,9}
print("Set 2:", set 2)
set1.intersection_update(set 2)
print("Intersection:", set1)
Output
Set1:{8, 2, 3, 6}
Set 2: {9, 2, 4, 1}
Intersection_update:{8, 2, 3, 6}
9. set1.difference(set2) - Returns the difference of two or more sets into a new set
Example Program
#Demo of set1.difference (set 2)
set1={3, 8, 2,6}
print("Set1: , set1)
set 2= {4,2,1,9}
print("Set 2:", set2)
set3 = set1.difference (set2)
print("Difference:", set 3)
Output
Set1:{8, 2, 3, 6}
Set 2:{9, 2, 4, 1}
Difference: {8, 3, 6}
48
CS1543: PYTHON PROGRAMMING Module 1
10.set1.difference_update(set2) - Remove all elements of another set set2 from set1 and the result is
stored in set1.
Example Program
#Demo of set1.difference_update (set 2)
set1={3, 8, 2,6}
print("Set 1:",set1}
set 2={4,2,1,9}
print("Set 2:", set 2)
set1.difference_update (set 2)
print("Difference Update:", set1)
Output
Set 1:{8, 2, 3, 6}
Set 2:{9, 2, 4, 1}
Difference Update: {8, 3, 6)
49
CP 1442: PYTHON PROGRAMMING Module 1
13.set1.isdisjoint(set2) :Returns True if two sets have a null intersection
Example Program
Example Program
#Demo of set1.issubset(set 2)
setl={3,8}
print("Set 1:",set1)
set2={3,8,4,7,1,9}
print("Set 2:", set2)
print("Result of seti.issubset(set2):", set1.issubset(set 2))
Output
Set 1:{8, 3}
Set 2:{1, 3, 4, 7, 8, 9}
Result of seti.issubset(set2): True
Example Program
#Demo of set1.issuperset (set 2)
set1={3,8, 4,6}
print("Set 1:",set1)
set2={3,8}
print("Set 2:",set2)
print("Result of set1.issuperset(set2):" seti.issuperset(set2)
Output
Set 1:{8, 3, 4, 6)
Set 2:{8, 3}
Result of set1.issuperset (set2): True
FROZENSET
Frozenset is a new class that has the characteristics of a set, but its elements cannot be changed once
assigned. While tuples are immutable lists, frozensets are immutable sets. Sets being mutable are
50
CP 1442: PYTHON PROGRAMMING Module 1
unhashable, so they can‟t be used as dictionary keys. On the other hand, frozensets are hashable and can
be used as keys to a dictionary
Frozensets can be created using the function frozenset(). This datatype supports methods like difference(),
intersection(), isdisjoint() issubset(), issuperset(), symmetric_difference() and union(). Being immutable it
does not have methods like add(), remove(), update(),difference_update(), intersection_update(),
symmetric_difference_update() etc.
Example Program
#Demo of frozenset()
set1= frozenset({3, 8, 4,6})
print ("Set 1:", set1)
set 2=frozenset({3,8})
print("Set 2:", set2)
print("Result of set1.intersection (set2):", set1.intersection (set 2))
Output
Set1: frozenset({8, 3, 4, 6})
Set 2: frozenset({8, 3})
Result of set1.intersection (set2): frozenset((8, 3})
DICTIONARY
Dictionary is an unordered collection of key-value pairs. It is generally used when we have a huge amount
of data. We must know the key to retrieve the value. In Python, dictionaries are defined within braces { }
with each item being a pair in the form key:value. Key and value can be of any type. Keys are usually
numbers or strings. Values, on the other hand, can be any arbitrary Python object. Dictionaries are
sometimes found in other languages as "associative memories" or "associative arrays".
Dictionaries are enclosed by curly braces ({}) and values can be assigned and accessed using square
braces ([ ]).
Example Program
dict={}
dict['one']= "This is one"
dict [2] ="This is two"
tinydict={'name': 'john', 'code': 6734, „dept':‟ sales‟}
studentdict={'name': 'john', 'marks': [35,80,90]}
print (dict['one')) # Prints value for 'one' key
print (dict [2]) # Prints value for 2 key
print (tinydict) # Prints complete dictionary
print (tinydict. keys ()) # Prints all the keys
print (tinydict.values()) # Prints all the values
print (studentdict) #Prints studentdict
51
CP 1442: PYTHON PROGRAMMING Module 1
Output
This is one
This is two
Example Program
#Demo of updating and adding new values to dictionary
dict1= { 'Name': 'Tom', 'Age':20, 'Height' :160}
print (dict1)
dict1['age'] =25 #updating existing value in Key-Value pair
print("Dictionary after update:", dict1)
dict1[ 'Weight']=60 #Adding new Key-value pair
print("Dictionary after adding new Key-value pair:", dict1)
Output
{'Age': 20, 'Name': Tom', 'Height': 160}
Dictionary after update: {'age': 25, 'Age': 20, 'Name': „Tom',
'Height': 160}
Dictionary after adding new Key-value pair: {'age': 25, 'Age': 20,
'Name': 'Tom', „Weight‟: 60, 'Height': 160}
We can delete the entire dictionary elements or individual elements in a dictionary. We can use del
statement to delete the dictionary completely. To remove entire elements of a dictionary, we can use the
clear() method.
Example Program
#Demo of Deleting Dictionary
dict1= {'Name':'Tom', 'Age' :20, 'Height': 160}
print(dict1)
del dict1['Age'] #deleting Key-value pair 'Age':20
print("Dictionary after deletion:", dict1)
dict1.clear() #Clearing entire dictionary
print(dict1)
Output
{'Age' : 20, 'Name': 'Tom', 'Height': 160}
Dictionary after deletion: { 'Name': 'Tom', 'Height: 160}
{}
3. type(variable) - The method type() returns the type of the passed variable. If passed variable is
dictionary then it would return a dictionary type. This function can be applied to any variable type like
number, string, list, tuple etc.
Example Program
#Demo of type (variable)
dict1= { 'Name': 'Tom', 'Age' :20, 'Height‟:160}
print(dict1)
print("Type (variable).", type (diet))
s="abcde"
print("Type (variable)-", type(s))
list1= [1, 'a', 23,' Tom']
print("Type (variable) -", type(list1))
Output
{'Age': 20, 'Name': Tom', 'Height: 160}
Type (variable) = <class 'dict'>
Type (variable) <class 'str'>
Type (variable)- <class 'list'>
Example Program
#Demo of dict.copy ()
dictl= { 'Name': 'Tom', 'Age' :20, 'Height' :160}
print(dict1)
dict2=dict1.copy()
print(dict2)
Output
{'Age': 20, 'Name': Tom', 'Height': 160}
{'Age': 20, 'Name': Tom', 'Height': 160}
Example Program
#Demo of dict.keys ()
dict1= { 'Name': Tom', 'Age :20, 'Height':160}
print(dict1)
print("Keys in Dictionary:", dict1.keys())
Output
{„Age': 20, 'Name': 'Tom', 'Height‟: 160}
Keys in Dictionary: ['Age'. 'Name', 'Height‟]
The values of the keys will be displayed in a random order. In order to retrieve the keys in sorted order, we
can use the sorted() function, all the keys should of the same type. But for using the sorted() function, all
keys should of same type.
Example Program
#Demo of dict.keys() in sorted order
dictl= { 'Name': Tom', 'Age' : 20, 'Height':160}
print(dict1)
print("Keys in sorted order:", sorted(dict1.keys()))
Output
{Age : 20, 'Name': "Tom', 'Height‟: 160}
4.dict. values0 - This method returns list of all values available in a dictionary
Example Program
#Demo of dict.values()
54
CP 1442: PYTHON PROGRAMMING Module 1
dict1={„Name': Tom', 'Age‟: 20, „Height‟:160}
print(dict1)
print("Values in Dictionary:",dict1.values())
Output
The values will be displayed in a random order. In order to retrieve the values in sorted order, we can use
the sorted function. But for using the sorted() function, all the values should of the same type.
Example Program
#Demo of dict.values()in sorted order
dict1= { 'Height' :160, 'Age':20, 'weight':60}
print(dict1)
print("Values in sorted order:",sorted (dict1.values()))
Output
{'Age': 20, 'Height': 160, 'Weight': 60}
Values in sorted order: [20, 60, 160]
Example Program
#Demo of dict.items()
dict1={'Name' :' Tom', 'Age':20, 'Height' :160}
print(dict1)
print("Items in Dictionary:", dict1.items()) . .
Output
{age': 20, 'Name': 'Tom', 'Height': 160}
Items in Dictionary: [('Age', 20), ('Name', 'Tom'), ('Height', 160)]
6.dict1.update(dict2) - The dictionary dict's key-value pair will be updated in dictionary dictl.
Example Program
#Demo of dict1.update (dict2)
dict1= { 'Name': 'Tom', 'Age' :20, 'Height' :160)
print(dict1)
dict2={'Weight': 60}
print (dict2)
dict1.update (dict2)
print("Dict1 updated Dict2 :",dict1)
Output
{'Age': 20, 'Name': "Tom', 'Height': 160}
{'Weight': 60}
Dict1 updated Dict2: {'Age': 20, 'Name': 'Tom', 'Weight‟:60,"Height':
160}
7.dict.get(key, default=None) - Returns the value corresponding to the key specified and if the key
specified is not in the dictionary, it returns the default value.
Example Program
#Demo of dict1.get (key, default='Name')
dict1= { 'Name': 'Tom', 'Age‟:20, 'Height' :160}
print (dict1)
print("Dict1.get('Age') :", dict1.get('Age'))
55
CP 1442: PYTHON PROGRAMMING Module 1
print ("Dict1.get('Phone') :", dict1.get('Phone', 0)) #' Phone not a
key, hence 0 #is given as default
Output
{'Age': 20, 'Name': 'Tom', 'Height': 160)
Dict1.get(key) : 20
Dict1.get(key) : 0
8. dict.setdefault(key, default=None) - Similar to dict.get(key,default=None) but will set the key with the
value passed and if key is not in the dictionary, it will set with the default value
Example Program
#Demo of dict1.set (key, default='Name')
dict1= { 'Name': 'Tom', 'Age':20, 'Height' :160}
print (dict1)
print("Dict1.setdefault ('Age') :",dict1.setdefault ('Age'))
print("Dictl.setdefault („Phone'):", dict1.setdefault ('Phone',0))
#'Phone not a #key, hence 0 is give as default value.
Output
{'Age' : 20, 'Name': "Tom', 'Height': 160}
Dictl.setdefault('Age') : 20
Dict1.setdefault('Phone') : 0
9. dict.fromkeys(seq,[val)) - Creates a new dictionary from sequence seq and values from val.
Example Program
#Demo of dict.fromkeys (seg, (val])
list=['Name', 'Age', 'Height']
dict=dict.fromkeys (list)
print("New Dictionary:", dict)
Output
New Dictionary: { „Age': None, 'Name': None, "Height': None }
Objects whose value can change are said to be mutable and objects whose value is unchangeable once they
are created are called immutable. An object's mutability is determined by its type. For instance, numbers,
strings and tuples are immutable, while lists, sets and dictionaries are mutable. The following example
illustrates the mutability of objects.
Example Program
#Mutability illustration
#Numbers
a=10
print(a) #Value of a before subtraction
print(a-2) #value of a - 2
print(a) #Value of a after subtraction
#Strings
56
CP 1442: PYTHON PROGRAMMING Module 1
str="abcde"
print(str) #Before applying upper() function
print(str.upper()) #result of upper()
print(str) #After applying upper() function
#Lists
list=[1,2,3,4,5]
print(list) #Before applying remove () method
list.remove(3)
print(list)#After applying remove() method
Output
10
8
10
abcde
ABCDE
abcde
[1, 2, 3, 4, 5]
[1, 2, 4, 5]
From the above example, it is clear that the values of numbers and strings are not even after applying a
function or operation. But in the case of list, the value is changed or the changes are reflected in the
original variable and hence called mutable.
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 representing the converted value. Table 2.6 shows various
functions and their descriptions used for data type conversion.
Function Description
int(x [,base]) Converts x to an integer, base specifies the base if x is a string.
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.
57
CP 1442: PYTHON PROGRAMMING Module 1
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.
Example Program 1
Integer x= 12
Long x= 12000
Floating Point x= 12.0
Complex number = (5+2j)
String conversion of 12 is 12
Expression String of 12 is 12
Example Program 2
Output 2
Conversion of abcde to tuple is ('a', 'b', 'c', d', 'e')
Conversion of abcde to list is ['a', 'b', 'c', 'd', 'e']
Conversion of abcde to set is set(['a', 'c', 'b', 'e', 'd'])
58
CP 1442: PYTHON PROGRAMMING Module 1
Conversion of abcde to frozenset is frozenset(['a', 'c', 'b', 'e',
d'])
Conversion of {1: 'a', 2: 'b', 3: 'c'} to dictionary is {1: 'a', 2:
'b',3: 'c'}
Example Program 3
Output 3
SOLVED EXERCISES
1. Write a Python program which accept the radius of a circle from the user and compute the area.
Program
import math
r = float (input("Input the radius of the circle:")
print("The area of the circle with radius",r,"is" , math.pi * r**2))
Output
Input the radius of the circle:3.5 .
The area of the circle with radius 3.5 is: 38.48451000647496
Program
# Biggest of three numbers
a = int(input("Enter first number:")) #Reads First Number
b = int(input("Enter second number:")) #Reads Second Number
c = int(input("Enter third number:")) #Reads Third Number
big = max(a,b,c) #Finds the biggest
print("Biggest of", a,b,c, "is", big)#prints the biggest number
59
CP 1442: PYTHON PROGRAMMING Module 1
Output
Enter first number:3
Enter second number: 4
Enter third number: 5
Biggest of 3 4 5 is 5
3. Write a Python program which accepts a sequence of comma-separated number from user and generate
a list and a tuple with those numbers.
Program
values = input ("Input some comma separated numbers:”)
list = values.split(",”)
tuple = tuple(list)
print('List : ',list)
print("Tuple : ", tuple)
Output
4.Write a Python program to accept a filename from the user print the extension of that.
Program
filename = input ("Input the Filename: ")
f_extns = filename.split(".")
print("The extension of the file is ",f_extns [-1])
Output
Input the Filename: ABC.doc
The extension of the file is : doc
5.Write a Python program to display the first and last colors from the following list.
Program
color=input("Enter colors (space between colors) :")
color_list = color.split(" ")
print(color_list)
print("The first color in the list is:", color_list[0],"and last
color is:",color_list[-1])
Output
Enter colors (space between colors) : red green blue white yellow
['red', 'green', 'blue', 'white', 'yellow']
The first color in the list is: red and last color is: yellow
6. Write a Python program that accept an integer (n) and computes the value of n+nn+nnn.
Program
a =int (input ("Input an integer:" ))
60
CP 1442: PYTHON PROGRAMMING Module 1
n1 = int("%s" %a)
n2 = int("%s%s" %(a, a))
n3 = int("%s%s%s" %(a, a, a))
print(n1," ", n2, " ",n3)
print("sum=",(n1+n2+n3))
Output
Input an integer: 2
2 22 222
sum= 246
DECISION MAKING
Decision making is required when we want to execute a code only if a certain condition is satisfied.
The if...elif...else statement is used in Python for decision making.
if statement
Syntax
if test expression:
statement (s)
The following Fig. 3.1 shows the flow chart of the if statement.
test false
expression
true
body of if
Here, the program evaluates the test expression and will execute statement(s) only if the test
expression is True. If the test 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 ends
with the first unintended line. Python interprets non-zero values as True. None and 0 are interpreted
as False.
Example Program
61
CP 1442: PYTHON PROGRAMMING Module 1
Output 1
Enter a number: 0 Zero
This is always printed
Output 2
Enter a number: 2 This is always printed
In the above example, num == 0 is the test expression. The body of if is executed only if this
evaluates to True. When user enters O, test expression is True and body inside if is executed. When
user enters 2, test expression is False and body inside if is skipped. The Statement This is always
printed because the print statement falls outside the if block. The statement outside the if block is
shown by unindentation. Hence, it is executed regardless of the test expression or it is always
executed.
The following Fig. 3.2 shows the flow chart of if else. The if. .else statement evaluates test
expression and will execute body of if only when test condition is true. if the condition is false, body
of else is executed. Indentation is used to separate the blocks.
test false
expression
body of else
true
body of if
Example Program
62
CP 1442: PYTHON PROGRAMMING Module 1
Output 2
In the above example, when user enters 5, the test expression is True. Hence the body of if is
executed and body of else is skipped. When user enters -2, the test expression is False and body of
else is executed and body of if is skipped.
Body of else
The elif is short for else if. It allows us to check for multiple expressions. If the condition for if is
false, it checks the condition of the next elif block and so on. If all the conditions are false, body of
else is executed. Only one block among the several if... elif... else blocks is executed according to
the condition. An if block can have only one else block. But it can have multiple elif blocks. The
following Fig. 3.3 shows the flow chart for if.elif. .else statement
test false
expression
of if
test false
expression
of elif
true
body of if
body of else
body of elif
Example Program
num=int (input ("Enter a number: "))
if num> 0:
63
CP 1442: PYTHON PROGRAMMING Module 1
Output 1
Enter a number: 5 Positive Number
Output 2
Enter a number: 0 Zero
Output 3
Enter a number:-2 Negative Number
Nested if statement
We have a if...elif...else statement inside another if...elif...else statement. this is called nesting in
computer programming. indentation is the only way to identify the level of nesting.
Example Program
else:
else:
Output 1
Enter a number: 5
Positive Number
Output 2
Enter a number: 0
Zero
Output 3
Enter a number: -2
Negative Number
LOOPS
Generally, statements are executed sequentially. The first statement in a function is executed first,
followed by the second, 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 allows for repeated
64
CP 1442: PYTHON PROGRAMMING Module 1
execution. A loop statement allows us to execute a statement or group statements multiple times.
for loop
The for loop in Python is used to iterate over a sequence (list, tuple, string) or other objects that can
be iterated. 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. The
sequence can be list, tuple, string, set etc. 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.
for each
item in
sequence
test No
expression
Yes
body of for
Example Program 1
#Program to find the sum of all numbers stored in a list
numbers = [2,4,6,8,10] #List of numbers
sum = 0 # variable to store the sum
for item in numbers: # iterate over the list
sum = sum + item
print(" The sum is", sum) #print the sum
Output 1
The sum is 30
Example Program 2
flowers =[rose', lotus', jasmine']
for flower in flowers:
print (Current flower :', flower)
65
CP 1442: PYTHON PROGRAMMING Module 1
Output 2
Current flower: rose
Current flower: lotus
Current flower: jasmine
Example Program 3
for letter in 'program':
print ( 'Current letter:', letter)
Output 3
Current letter:p
Current letter: r
Current letter: o
Current letter:g
Current letter: r
Current letter:a
Current letter: m
range() function
We can use the range () function in for loops to iterate through a sequence of numbers. It can be
combined with the len () function to iterate though a sequence using indexing.len () function is used
to find the length of a string or number of elements in a list, tuple,set etc.
Example Program
flowers =['rose', lotus', „jasmine']
for i in range (len (flowers)):
print (“Current flower:” flowers [i])
Output
Current flower rose
Current flower: lotus
Current flower :jasmine
We can generate a sequence of numbers using range () function. range (10) will generate numbers
from 0 to 9 (10 numbers). We can also define the start, stop and step_size as range (start, stop,
step_size). The default value of step_size is 1, if not provided. This function does not store all the
values in memory. It keeps track of the start, stop, step_size and generates the next number. To
make this function to output all the items, we can use the function list ().
Example Program
for num in range ( 2,10,2) : print ("Number =",num)
Output
Number = 2
Number = 4
Number = 6
Number = 8
enumerate(iterable, start=0)function
66
CP 1442: PYTHON PROGRAMMING Module 1
This is one of the built-in Python functions. Returns an enumerate object. The parameter iterable
must be a sequence, an iterator, or some other object like list which supports iteration.
Example Program
Output
Python supports to have an else statement associated with a loop statement. If the else statement is
used with a for loop, the else statement is executed when the loop has finished iterating the list. A
break statement can be used to stop a for loop. In this case, the else part is ignored. Hence, a for
loop's else part runs if no break occurs.
Example Program
#Program to find whether an item is present in the list
list= [10,12, 13 , 34,27,98]
num = int (input (“Enter the number to be searched in the list: "))
for item in range (len (list) ):
if list [item] == num:
print ("Item found at: ", (item+1))
break
else:
print("Item not found in the list")
Output 1
Enter the number to be searched in the list:34
Item found at:4
Output 2
Enter the number to be searched in the list:99
Item not found in the 1ist
while loop
The while loop in Python is used to iterate over a block of code as long as the test expression
(condition) is True. We generally use this loop when we don't know the number of times to iterate in
advance. Fig. 3.5 shows the flow chart of a while loop.
Syntax
67
CP 1442: PYTHON PROGRAMMING Module 1
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
is continued 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 unintended
line shows the end. When the condition is tested and the result is False, the loop body will be
skipped and the first statement after the while loop will be executed.
test No
expression
Yes
body of while
Example Program
Output
Enter the 1imit: 5
Illustration
In the above program, when the text Enter the 1imit appears, 5 is given as input. ie.n=5. Initially, a
counter i is set to 1 and sum is set to 0. When the condition is checked for the first time i<=n, it is
True. Hence the execution enters the body of while loop.sum is added with i and i is incremented.
Since the next statement is unindented, it assumes the end of while block. This process is repeated
68
CP 1442: PYTHON PROGRAMMING Module 1
when the condition given in the while loop is False and the control goes to the next
print statement to print the sum.
while loop with else statement
If the else statement is used with a while loop, the else statement is executed when the condition
becomes False. while loop can be terminated with a break statement. In such case, the else part is
ignored. Hence, a while loop's else part runs if no break occurs and the condition is False.
Example Program 1
Output 1
Python Programming
Python Programming
Python Programming
Exit
End of Program
Illustration
In this example, initially the count is 1. The condition in the while loop is checked and since it is
True, the body of the while loop is executed. The loop is terminated when the condition is False and
it goes to the else statement. After executing the else block it will move on to the rest of the program
statements. In this example the print statement after the else block is executed.
Example Program 2
#Demo of While with else
Count=l
while count <=3:
print ("Python Programming")
count=count +1
if count = =2 :
break
else:
print (" Exit")
print ("End of Program")
Output 2
Python Programming End of Program
Illustration
In this example, initially of the count is 1. The condition in the while loop is checked and since it is
true, the body of the while loop is executed. When the if condition inside the while loop is true, ie.
when count becomes 2, the control is exited from the while loop. it will not execute the else part of
the loop. the control will moves on to the next statement after the else. Hence, the print statement
End of Program is executed.
69
CP 1442: PYTHON PROGRAMMING Module 1
NESTED LOOPS
Sometimes we need to place a loop inside another loop. This is called nested loop. We can have
nested loops for both while and for.
Syntax for nested for loop
for iterating_variable in sequence :
for iterating_ variable in sequence:
statements (s)
statements (s)
while expression:
while expression:
Statement (s)
statement (s)
Q: Write a program to print the prime numbers starting from 1 upto a limit entered by the user.
Output
Enter a Limit:12
1
2
3
5
7
11
The limit entered by the user is stored in n. To find whether a number is prime, the logic used is to
divide that number from 2 to square root of that number (Since all numbers are completely divisible
by 1, we started from 2). If the remainder of this division is zero at any time, that number is Skipped
and moved to next number. A complete division shows that the number is not prime. If the
remainder is not zero at any time, it shows that it is a prime number.
The outer for loop starts from 1 to the input entered by the user. Initially i=1. A variable k is used to
store the square root of the number. The inner for loop is used to find whether the number is
completely divisible by any number between 2 and square root of that number(k). If it is completely
divisible by any number between 2 and k, the number 1s not prime, else the number is considered
prime. The same steps are repeated until the limit entered by the user is reached.
The above program is rewritten using nested while and is given below.
70
CP 1442: PYTHON PROGRAMMING Module 1
Output
Enter a Limit:12
1
2
3
5
7
11
CONTROL STATEMENTS
Control statements change the execution from 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. Python supports the following three control statements.
1. break
2. continue
3. pass
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. It is inside a nested loop( loop inside another loop), break
will terminate the innermost loop. It can be used with both for and while loops. Fig. 3.6 shows the
flow chart of break statement.
71
CP 1442: PYTHON PROGRAMMING Module 1
Enter loop
False
condition
True
Yes
break?
No
exit loop
body of loop
Example Program1
#Demo of break statement in Python
for i in range (2, 10,2) :
if i==6:
break
print (i)
print (" End of Program")
Output 1
2
4
End of Program
Illustration
In this the for loop is intended to print the even numbers from 2 to 10. The if condition checks
whether i=6. If it is 6, the control goes to the next statement after the for loop. Hence it goes to the
print statement End of Program.
Example Program 2
#Demo of break statement in Python
i=5
while i>0 :
if i==3:
break
print (i)
i=i-1
print ("End of Program")
Output 2
5
4
End of Program
72
CP 1442: PYTHON PROGRAMMING Module 1
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. Continue returns the control to the
beginning of the loop. The continue statement rejects all the remaining statements in the current
iteration of the loop and moves the control back to the top of the loop. The continue statement can
be used in both while and for loops. Fig. 3.7 shows the flow chart of continue statement.
Enter loop
False
condition
True
Yes
continue?
No
exit loop
body of loop
Example Program
# Demo of continue in Python
for letter in 'abcd':
if letter = ='c':
continue
print (letter)
Output
abd
Illustration
When the letter=c, the continue statement is executed and the control goes to the beginning of the
loop, bypasses the rest of the statements in the body of the loop. In the output the letters from "a" to
"d" except "c" gets printed.
pass statement
In Python programming, pass is a null statement. The difference between a comment and pass
statement in Python is that, while the interpreter ignores a comment entirely, pass is not ignored. But
nothing happens when it is executed. It results in no operation.
It is used 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. The function or loop cannot have an empty body. The interpreter
73
CP 1442: PYTHON PROGRAMMING Module 1
will not allow this. So, we use the pass statement to construct a body that does nothing.
Example
TYPES OF LOOPS
There are different types of loops depending on the position at which condition is checked.
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. 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.
Example Program
count=l
while count==l:
n=input ("Enter a Number : ") print "Number=", n)
This will continue running unless you give CTRL+C to exit from the loop.
This kind of loop can be implemented using an infinite loop along with a conditional break in
between the body of the loop. Fig. 3.8 shows the flow chart of a loop with condition in the middle.
Enter loop
body of loop
True
Yes
break?
No
body of loop
exit loop
74
CP 1442: PYTHON PROGRAMMING Module 1
Example Program
vowels ='aeiou' # Infinite Loop
while True:
v=input ("Enter a letter: ")
if v in vowels:
print (v, "is a vowel")
break
print ("This is not a vowel, Enter another letter")
print ("End of Program")
Output
Enter a letter: t
This is not a vowel, Enter another letter Enter a letter: o
o is a vowel End of Program
Enter loop
body of loop
No
break?
Yes
exit loop
Example Program
# Demo of loop with condition at the bottom Choice=0
a, b=6, 3
while choice !=5:
print ( "Menu" ) print (1. Addition")
print ("2. Subtraction")
print ("3. Multiplication")
75
CP 1442: PYTHON PROGRAMMING Module 1
Output
Menu
1. Addition
2. Subtraction
3. Multiplication
4. Division
5. Exit
Enter your choice: 2
Difference= 3
Menu
1. Addition
2. Subtraction
3. Multiplication
4. Division
5. Exit
Enter your choice:5
End of Program
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.
Example Program 1
#Generation of squares using list comprehension
squares= [x**2 for x in range (10)]
print (squares)
Output 1
Example Program 2
[(3, 4, 5), (5, 12, 13), (6, 8, 10), (8, 15, 17), (9, 12, 15)]
Nested List
In Python, we can implement a matrix as nested list (list inside a list). We can treat each element as
a row of the matrix. For example X = [[1, 2], [4, 5], [3, 6]] would represent a 3x2 matrix. First row
can be selected as X[0] and the element in first row, first column can be selected as X[0][0]
Example Program #Demo of Nested List
matrix= [ [1,2,3],
[4,5,6],
[7,8,9]]
Output
123
456
789
The initial expression in a list comprehension can be any arbitrary expression, including another list
comprehension. The following nested list comprehension transposes rows and Columns.
Example Program
147
258
369
SET COMPREHENSIONS
Sets support comprehensions in a similar way to lists. The following program illustrates this.
Example Program
#Generation of consonants using set comprehensio1 s={x for * in 'abhtdefkijlyqacdvedou' if x not in
'aeiou' } print (s)
77
CP 1442: PYTHON PROGRAMMING Module 1
Output
{'h', 'l', 'd', v', 'f',' b', 'y', t', 'q', 'k', 'c', 'j'}
DICTIONARY COMPREHENSIONS
Dictionaries also support comprehension like lists and sets. The following program generates a
dictionary with key as a number and value will be its square.
Example Program
Output
NESTED DICTIONARIES
Python support dictionaries nested one inside the other. Nesting involves putting a list or dictionary
inside another list or dictionary. We will look at two examples here, lists inside a dictionary and
dictionaries inside a dictionary.
Example Program 1
#This program stores people's favorite numbers as lists and display them.
favorite_numbers = {'Tom': [3, 11, 19, 23, 42], 'Jim':[2, 4, 5],'Jack' : 5, 35, 120]}
# Display each person' s favorite numbers.
for name in favorite _numbers:
print (" \n%s's favorite numbers are:" name) #Each value is itselt a list, so we need another for
loop #to work with the list.
for favorite_number in favorite_numbers (name):
print (favorite_number)
Output 1
Jack' s favorite numbers are: 5
35
120
78
CP 1442: PYTHON PROGRAMMING Module 1
Example Program 2
#This program stores information about books. For each book, #we store the name of author,
the publisher's name, and
#the year of publication.
books = {'Python':{'name': 'Jeeva', 'publisher': 'Khanna', 'year': 2015},
'C':{'name': 'Strousp', 'publisher': Mc GrawHill', 'year': 2000},
'Java': {'name':' Patrick ','publisher': 'Pearson','year': 2005}}
Output 2
*******************************************