Python Mod 1
Python Mod 1
Chapter 1
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. 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 be 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.
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.
a) 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.
Invoking the interpreter without passing a script file as a parameter brings up the following prompt.
$ python
Python 3.7 (default, Mar 27, 2019, 18:11:38) [GCC 5.1.1 20150422 (Red Hat 5.1.1-1)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
Type the following text at the Python prompt and press the Enter:
>>> print ("Programming in Python!")
The result will be as given below
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 $python script.py or python; script.py.
For Windows/ Dos it is C:>python script.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 in Python!")
Now, try to run this program as follows.
$ python first.py
This produces the following result:
Programming in Python!
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 Python Win 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.
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 (). For example Total and total is different.
Reserved keywords (explained in Section 1.4) cannot be used as an identifier.
Identifiers cannot begin with a digit. For example 2more, 3times etc. are invalid identifiers.
Special symbols like @, !, #, $, % etc. cannot be used in an identifier. For example sum@,
#total are invalid identifiers.
Identifier can be of any length.
Some examples of valid identifiers are total, max_mark, count2, Student etc. Here are some naming
conventions for Python identifiers.
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 the programming language and prevent the user or the programmer
from using it as an identifier in a program. There are 33 keywords in Python 3.3. This number may
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.
>>> import keyword
>>> 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']
Python Keywords
False class finally is return
None continue for lambda try
True def from nonlocal while
and del global not with
as elif if or yield
assert else import pass
break except in raise
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 a = 100 # An integer assignment
b = 1000.0 # A floating point
name = "John" # A string
print (a)
print (b)
print (name)
Here, 100, 1000.0 and "John" are the values assigned to a, b, and name variables, 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
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
>>>#This is demo of comment
>>>#Display Hello
>>>print("Hello")
This produces the following result: 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
>>>#This is a very long sentence
>>>#and it ends after
>>>#Three lines
Example 2
>>>""" This is a very long sentence
>>>and it ends after
>>>Three lines"""
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
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
which will be discussed in coming Chapters. In Python, end of a statement is marked by a newline
character. But we can make a statement extend over multiple lines with the line continuation
character(\). For example:
grand_total = first_item + \
second_item + \
third_item
Statements contained within the [ ], {}, or ( ) brackets do not need to use the line continuation
character. For example
months = ['January', 'February', 'March', 'April',
"May', 'June', 'July', 'August', 'September',
October', 'November', 'December']
We could also put multiple statements in a single line using semicolons, as follows
a = 1; b = 2; C = 3
MULTIPLE STATEMENT GROUP (SUITE)
A group of individual statements, which make a single code block is called a suite in Python.
Compound or complex statements, such as if, while, def, and class require a header line and a
suite. Header lines begin the statement (with the keyword) and terminate with a 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.
word = 'single word'
sentence = "This is a short sentence."
paragraph = """ This is a long paragraph. It consists of
several lines and sentences. """
Example Program
a, b, c = 10, 5, 2
print("Sum=", (a+b))
print("Differences", (a-b))
print("Product=", (a*b))
print("Quotient=", (a/b))
print ("Remainder=", (b&c))
print("Exponent=", (b**2))
print("Floor Division=", (b//c))
Output
Sum= 15
Difference= 5
Product= 50
Quotient= 2
Remainders =1
Exponent= 25
Floor Division= 2
2. Comparison Operators
These operators compare the values on either sides of them and decide the relation among them.
They are also called relational operators. Python supports the following relational operators. Table
1.3 shows the comparison or relational operators in Python.
Operator Description
== If the values of two operands are equal, then the condition becomes true.
!= If values of two operands are not equal, then condition becomes true.
> If the value of left operand is greater than the value of right operand, then condition
becomes true.
< If the value of left operand is less than the value of right operand, then condition
becomes true.
>= If the value of left operand is greater than or equal to the value of right operand,
then condition becomes true.
<= If the value of left operand is less than or equal to the value of right operand, then
condition becomes true.
Example Program
a, b=10,5
print ("a==b is", (a==b))
print ("a!=b is", (a!=b))
print ("a>b is", (a>b))
print ("asb is", (a<b))
print ("a>=b is", (a>=b))
print ("a<=b is", (a<=b))
Output
a==b is False
a !=b is True
a>b is True
a<b is False
a>=b is True
a<=b is False
3. 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
provides the various assignment operators.
Table: Assignment Operators
Operator Description
= Assigns values from right side operands to left side operand.
+= It adds right operand to the left operand and assign the result to left operand.
-= It subtracts right operand from the left operand and assign the result to left operand.
*= It multiplies right operand with the left operand and assign the result to left operand.
/= It divides left operand with the 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 division on operators 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*ra 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.
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
5
50
2
1
25
2
4 Bitwise Operators
Bitwise operator works on bits and performs bit by bit operation. The following are the bitwise
operators supported by Python. Table gives a description of bitwise operators in Python.
Operator Operation Description
Operator copies a bit to the result if it exists in both
& Binary AND
operands.
| Binary OR It copies a bit if it exists in either operand.
^ Binary XOR It copies the bit if it is set in one operand but not both.
~ Binary Ones complement It is unary and has the effect of 'flipping bits.
<< Binary Left Shift The left operand's value is moved left by the number of bits
specified by the right operand.
The left operand's value is moved right by the number of
>> Binary Right Shift
bits specified by the right operand.
Example Program
a, b, c, d=10,5,2,1
print((a>b) and (c>d))
print((a>b) or (d>c))
print (not (a>b))
Output
True
True
False
6. Membership Operators
Python's membership operators test for membership in a sequence, such as strings, lists, or tuples.
There are two membership operators as explained below in Table.
Table Membership Operators
Operator Description
in Evaluates to true if the variables on either side of the operator point to the same object
and false otherwise.
not in Evaluates to true if it does not finds a variable in the specified sequence and false
otherwise.
Example Program
s='abcde'
print('a' in s)
print('f' in s)
print('f'not in s)
Output
True
False
True
7. Identity Operators
Identity operators compare the memory locations of two objects. There are two identity operators
as shown in below Table.
Table Identity Operators
Operator Description
is Evaluates to true if the variables on either side of the operator point to the same object
and false otherwise.
is not Evaluates to 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 ia c)
print (a is not b)
Output
True
False
False
Operator Precedence
The following Table lists all operators from highest precedence to lowest. 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.
Table Operator Precedence
Operator Description
** Exponentiation (raise to the power)
~,+,- Complement, unary plus and minus
*, /, %, // Multiply, divide, modulo and floor division
+, - Addition and subtraction
>>, << Right and left bitwise shift
& Bitwise AND
^, | Bitwise exclusive 'OR' and regular 'OR'
<=, < >, >= Comparison operators
<>,= =, != Equality operators
=, %=, /=, //=, -=, +=, *=, **= Assignment operators
is, is not Identity operators
in, not in Membership operators
not, or, and Logical operators
Chapter 2
Data Types and Operations
The data stored in memory can be of many types. For example, a person's name is stored as
alphabets, age is stored as a numeric value and his or her address is stored as alphanumeric
characters. Python has the following standard data types.
Numbers Tuple
String Set
List Dictionary
1. 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.
del variable1[, variable2 [, variable3[ ...., variableN ] ] ] ]
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.
int (signed integers)
long (long integers, they can also be represented in octal and hexadecimal)
float (floating point real values)
complex (complex numbers)
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
a, b, c, d=1,1.5,231456987,2+9j
print("a",a)
print("b ", b)
print("c=",c)
print("d",d)
Output
a=1
b= 1.5
c=231456987
d=(2+9j)
1.1 Mathematical Functions
Python provides various built-in mathematical functions to perform mathematical calculations. The
following Table provides various mathematical functions and its purpose. For using the below
functions, all functions except abs(x), max(x1,x2,... xn), min(x1,x2,... xn), round(xl.nl) 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.
Table 2.1 Mathematical Functions
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 >0.
log10(x) Finds the logarithm to the base 10 for x>0.
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,modf (12.090876))
Output
Absolute value of -120: 120
Square root of 25: 5.0
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.6931471805599453
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: 10.09087599999999973, 12.0)
1.2 Trigonometric Functions
There are several built-in trigonometric functions in Python. The function names and its purpose are
listed in Table.
Table Trigonometric Functions
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(x,y) Returns the Euclidean form, sqrt(x*x + y*y).
degrees(x) Converts angle x from radians to degrees.
radians(x) Converts angle x from degrees to radians.
Example
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 (1):", 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)
print("Radians of 90:", math.radians (90))
Output
Sin(90): 0.893996663601
Cos (90): -0.448073616129
Tan (90): -1.99520041221
asin(1): 1.57079632679
acos (1): 0.0
atan (1): 0.785398163397
atan2 (3,2): 0.982793723247
Hypotenuse of 3 and 4: 5.0
Degrees of 90: 5156.62015618
Radians of 90: 1.57079632679
1.3 Random Number Functions
There are several random number functions supported by Python. Random numbers have
applications in research, games, cryptography, simulation and other applications. Table 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.
Table Random Number Functions
Function Description
choice(sequence) Returns a random value from a sequence like list, tuple, string etc.
shuffle(list) Shuffles the items randomly in a list. Returns none.
random() Returns a random floating-point number which lies between 0 and 1.
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(x, y) Generates a random floating-point number n such that n>x and n<y,
Example
import random
s= 'abcde'
print("choice (abcde):", random.choice(s) )
list = [10,2,3,1,8,19]
random. shuffle (list)
print("shuffle (list):", list)
print("random.seed (20):", random.seed (20))
print ("random(): ", random.random() )
print("uniform (2,3):", random.uniform(2,3) )
print("randrange (2,10,1):", random.randrange (2,10,1))
Output
choice (abcde): d
shuffle (list): [3, 1, 2, 10, 19, 8]
random.seed (20): None
random(): 0.9056396761745207
uniform (2,3): 2.6862541570267027
randrange (2,10,1): 4
2. 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
str = 'Welcome to Python Programming'
print (str) # Prints complete string
print (str[0]) # Prints first character of the string
print (str[11 : 17]) # Prints characters starting from 11th to 17th
print (str [11:]) # Prints string starting from 11th character
print (str * 2 ) # Prints string two times
print (str + " Session") # Prints concatenated string
Output
Welcome to Python Programming
W
Python
Python Programming
Welcome to Python Programming Welcome to Python Programming
Welcome to Python Programming Session
The following example shows the usage of various string formatting functions.
Example Program
#Demo of String Formatting Operators
print("The first letter of %s is %c" %('apple', 'a'))
print("The sum=%d" %(-12))
print("The sum=%i" %(-12))
print("The sum=%u" %(12))
print("%o is the octal octal equivalent of %d" %(8,8))
print("%x is the hexadecimal equivalent of %d" %(10,10))
print("%X is the hexadecimal equivalent of %d" %(10,10))
print("%e is the exponential equivalent of %f" %(10.98765432, 10.98765432))
print("%E is the exponential equivalent of %f" %(10.98765432,10.98765432))
print("%.3f" %(32.1274))
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
A is the hexadecimal equivalent of 10
1.098765e+01 is the exponential equivalent of 10.987654
1.098765E+01 is the exponential equivalent of 10.987654
32.127
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 [ ]. 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']
print (first_list) # Prints complete list
print (first_list [0] ) # Prints first element of the list
print (first_list[1:3]) # Prints elements starting from 2nd till 3rd
print (first_list [2:]) # Prints elements starting from 3rd element
print (small_list * 2) # Prints list two times
print (first_list + small_list) # Prints concatenated lists
Output
['abcd', 147, 2.43, 'Tom', 74.9]
abcd
[147, 2.43]
[2.43, 'Tom', 74.91]
[111, 'Tom', 111, 'Tom']
['abcd', 147, 2.43, 'Tom', 74.9, 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
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'
print("Item at Position 0 and 1 is", list[0], list [1])
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', 74.91
List after deletion: ["abcd', 147, Tom', 74.9]
numbers = (1, 2, 3, 4)
result = map(addition, numbers)
print(list(result))
Output
[2, 4, 6, 8]
Example Program 2
def calc_sum(x1, x2):
return x1+x2
4 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)
tuple [2] = 100 # Invalid syntax with tuple
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'])
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(z)
Output
('apple', 1, 100)
apple
100
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 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
s1={1,2,3} #set of integer numbers
print (s1)
s2={1,2,3,2,1,2 } #output contains only unique values
print (s2)
s3={1, 2.4, 'apple', 'Tom', 3 } #set of mixed data types
print (s3)
#s4={1,2, [3, 4] } #sets cannot have mutable items
#print s4 # Hence not permitted
s5=set([1,2,3,4] ) #using set function to create set from a list
print (s5)
Output
{1, 2, 3)
{1, 2, 3}
(1, 3, 2.4, 'apple, Tom' }
{1, 2, 3, 4}
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)
set1={3, 8, 2,6}
print("Set before discard:", set1)
set1.discard (8)
print("Set after discard:", set1) # Element is present
set1.discard (9)
print ("Set after discard:", set1) #Element is not present
Output
Set before discard:{8, 2, 3, 6}
Set after discard: {2, 3, 6}
Set after discard: {2, 3, 6}
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 ("Set1 before pop:", set1)
set1.pop()
print("Set1 after poping:", set1)
set1.pop()
print("Set1 after poping:", set1)
set1.pop()
print("Set1 after poping:", set1)
set1.pop()
print("Set1 after poping:", set1)
set1.pop()
print("Set1 after poping:", set1)
Output
Set1 before pop: {8, 2, 3, 6}
Set1 after poping: {2, 3, 6}
Set1 after poping: {3, 6}
Set1 after poping: {6}
Set1 after poping: set()
Traceback (most recent call last):
File "main.py", line 12, in <module>
set1.pop()
KeyError: 'pop from an empty set'
6 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
Output
This is one
This is two
{'dept': 'sales', 'name': 'john', 'code': 6734}
dict_keys ( ['dept', 'name', 'code'])
dict_values(['sales', 'john', 6734])
{"marks': [35, 80, 90], 'name': 'john'}
We can update a dictionary by adding a new key-value pair or modifying an existing entry.
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("After adding new Key-value pair:", dict1)
Output
{'Name': 'Tom', 'Age': 20, 'Height': 160}
Dictionary after update: {'Name': 'Tom', 'Age': 25, 'Height': 160}
After adding new Key-value pair: {'Name': 'Tom', 'Age': 25, 'Height': 160, 'weight': 60}
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}
Function Description
int(x) Converts x to an integer
long(x) Converts x to a long integer.
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.
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
Chapter 3- Flow Control
3.1 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.
3.1.1 if statement
Syntax
if test expression:
statement(s)
The following Fig. 3.1 shows the flow chart of the if statement.
False
Test
Expression
True
Body of if
False
Test
Expression
True
Test False
Expression of
if
Test False
True Expression of
elif
Body of if
True
3.2 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 allow for repeated execution.
A loop statement allows us to execute a statement or group of statements multiple times.
3.2.1 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. Fig. 3.4 shows flow chart of for loop.
Syntax
for item in sequence:
Body of for
Here, item is the variable that takes the value of the item inside 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.
Yes
Last item
reached?
No
Body of for
Exit loop
False
Test
expression
True
Body of while
Exit loop
Illustration
In the above program, when the text Enter the limit appears, 10 is given as the input. ie, n=10.
Initially, a counter i is set to 1 and sum is set to 0. When the condition is checked 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 unindented, it assumes the end of while block. This process
repeated when the condition given in the while loop is False and the control goes to the next print
statement to print the sum.
3.2.6 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, else part is
ignored. Hence, a while loop's else part runs if no break occurs and the condition is False.
Example Program 1
#Demo of while with else
count=1
while count<=3:
print("Python Programming")
count=count+1
else:
print("Exit")
print("End of Program")
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=1
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 the count is 1. The condition in the while loop is checked since it is True,
the body of the while loop is executed. When the if condition inside 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.
Enter loop
False
Condition
True
Yes
Break?
No
Enter loop
False
Condition
True
Yes
Continue?
No
Enter loop
Body of loop
Yes
Break?
No
Body of loop
No
Break?
Yes
Exit loop
Fig 3.9 Loop with condition at the bottom
Example Program
#Demo of loop with condition at the bottom
choice=0
a,b=6,3
while choice !=3:
print("Menu")
print("1. Addition")
print("2. Subtraction")
print("3. exit")
choice =int (input("enter your choice:"))
if choice==1:
print ("sum=", (a+b))
if choice==2:
print("Differences=", (a-b))
if choice==3:
break
print("End of Program")
Output
Menu
1. Addition
2. Subtraction
3. exit
enter your choice:
1
sum= 9
Menu
1. Addition
2. Subtraction
3. exit
enter your choice:
3
End of Program