PDF&Rendition 1
PDF&Rendition 1
25ULU251
Lecture: 4 hrs Tutorial :0 hrs per week Lab Practice: 0 hrs per week Lecture: 4 hrs per
per week week
Links to other -
Courses
Develop a comprehensive understanding of Python programming, covering basic syntax, control structures,
functions, data types, and file handling, to enable effective problem-solving and application development.
List and tuples in two lists- sorting the list elements- repetition of lists- nested lists-
python finding common elements in two list- Tuples: creating tuple
concatenation of two lists- sorting the list elements tuples-
12
accessing the tuple elements-basic operation on tuple nested
tuple-insert-modifying -deleting elements from a tuple.
Dictionaries and converting list into dictionary- Types of files in python- opening 12
file in python a file - closing a file- working with binary files.
Course Focuses Course addresses the Cross cutting issues Course relevance to
on
Professional Ethics Global need
Employability
Learning Resources:
Recommended Texts
1. [Link] Rao, “Core Python Programming”, DreamTech Press, 2021, ISBN 10-9390457157.
Reference Books: 1.
ReemaThareja, “Python Programming using problem solving approach”, First Edition, 2017, Oxford
University Press. 2.
[Link], “A primer to python programming”, Notion Press, 2022, ISBN 13-979-
8888497821. 3.
Wesley Chun, “Core Python Programming” , 3rd Edition 2015, Pearson, ISBN: 10-9332555362
Web Resources:
1) [Link]
2) [Link]
3) [Link]
4) [Link]
[Link]
Programming in Python
UNIT-I
Introduction to Python and installation:
1) Finding an Interpreter:
Before we start Python programming, we need to have an interpreter
to interpret and run our programs. There are certain online
interpreters like [Link] [Link] or
[Link] that can be used to start Python without installing
an interpreter.
Windows: There are many interpreters available freely to run Python
scripts like IDLE (Integrated Development Environment) which is
installed when you install the python software from
[Link]
The following are the primary factors to use python in day-to-day life:
1. Python is object-oriented
Structure supports such concepts as polymorphism,
operation overloading and multiple inheritance.
2. Indentation:Indentation is one of the greatest feature in python
3. It‟s free (open source)
Downloading python and installing python is free and easy
4. It‟s Powerful
Dynamic typing
Built-in types and tools
Library utilities
Third party utilities (e.g. Numeric, NumPy, sciPy)
Automatic memory management
5. It‟s Portable
Python runs virtually every major platform used today
As long as you have a compaitable python
interpreter installed, python programs will
run in exactly the same manner, irrespective
of platform.
6. It‟s easy to use and learn
No intermediate compile
Python Programs are compiled automatically to
an intermediate form called byte code, which the
interpreter then reads.
This gives python the development speed of
an interpreter without the performance loss
inherent in purely interpreted languages.
Structure and syntax are pretty intuitive and easy to grasp.
7. Interpreted Language
Python is processed at runtime by python Interpreter
8. Interactive Programming Language
Users can interact with the python interpreter directly for writing
the programs
9. Straight forward syntax
The formation of python syntax is simple and straight forward
which also makes it popular.
Applications of Python:
10. Although the original idea of developing Python is simple and
easy to use language, its efficacy and evolution made it a popular
programming language. Now it has been used in a variety of
domains and different packages have been developed for
different applications. The following are the domains using
Python language.
11. Python is exclusively used in web development. A lot of
frameworks are available for the design of the dynamic website.
For eg. Django, Flask, Web2py are the popular frameworks used
for the purpose of web development.
12. Scientific and numeric computing is one of the important
domains which is used in various scientific and engineering
applications. Python comes with handy scipy, numpy packages
for efficient processing.
13. Game Development is one of the popular domains and a lot of
people are using pygame for developing 2D and 3D games.
14. Data Analysis is another new-age technique used in the world to
analyze data for interpreting the same. Pandas are one of the
notable packages used in Python for data analysis
15. Machine Learning is a domain where the data are analysed to
predict new information. Packages like scikit-learn are
extensively used in Python.
16. Besides Python is extensively used in Scripting, Network
Programming, GUI Programming, Database Programming,
Image Processing, Internet Programming and Information and
Text Retrieval.
[Link] Version Release Date
1 Python 2.0.1 June’22,2007
2 Python 2.6 Oct’02,2008
3 Python 3.0 Dec 3,2008
4 Python 3.5.1 Dec‘7,2015
5 Python 3.7.1 Oct’20,2018
6 Python 3.8.1 Dec ’18,2019
7 Python 3.9.1 Dec’7,2020
8 Python 3.10.0 Oct’4,2021
Installation:
PVM
[Link] [Link]
>>> x=[0,1,2]
>>> x
The chevron at the beginning of the 1st line, i.e., the symbol >>> is
a prompt the python interpreter uses to indicate that it is ready. If the
programmer types 2+6, the interpreter replies 8.
python [Link]
Example:
Python Fundamentals
Python Fundamentals deal with the basic building blocks of creating scripts in
python. It includes the structure and semantic matters, identifiers, variables,
statements, operators and expressions. This is the basis for developing simple
python scripts.
The variables which are all used throughout the program either inside the
function or outside the function are called global variables. Those variables
should be initialized in this part.
Class Definitions
Python allows object-oriented programming also. The user-defined data type
which includes both data members and function members are called classes. Class
definitions occupy the fourth part of the structure.
Function Definition
The block of code that has a name assigned to it and performs the specified
task is called function. Function definition must be introduced before the main
program code.
print("Square of ",number2,"is:",square)
The above program shows the structure of the python Program. The Python
scripts can be developed with main program alone. But it is advisable to have
module documentation. The example program shows the position of each part of
the program. The execution starts with the main program. Normally, it follows a
bottom-up approach. The program reads two positive integer numbers. Then it
calculates the square of the second number. It then calls the function to generate
a random number and print it. Finally prints the square of the second number
given.
The output of the program is
Enter any Positive integer: 10
Enter one more Positive int: 20
Random Number is: 11
Square of 20 is: 400
Comments are a single line of text placed in different parts of the program
based on the requirement. Comments help the reader to understand the code and
its purpose without actually interpreting the statement. It is basically a short
description. The comments are introduced with the #(hash/pound) symbol. The
python interpreter ignores the statement that is followed by #. The comments are
used for future reference. Normally it includes the basic information (see
3.1)along with a small note about the program and formulas if any.
Program : Display Welcome message with comment statement
#Author: Name
#Date : [Link]
The statements are introduced one by one. If the statements are too small in
length, then one can use more than one statement in a single line. This can be
done with a semicolon(;).
Example
>>>a=5; b=7.0; c='Hello'
Block of code or Suites
#Usage of Indentation
#Program: Read a number
#check whether it is a positive number
num=int(input("Enter a Number:"))
if num>0: #indent statement
print("The given number", num,"is POSITIVE")
The program shows how indentation is used to represent blocks of code. With
indent, the next line will be started automatically by leaving 4 spaces by default.
The output of Program is shown below
Enter a Number: 120
The given number 120 is POSITIVE
>>>
Program :De- Indentation
#Usage of Indentation
num=int(input("Enter a Number:"))
if num>0:
The program shows indentation. If the developer of the code does not follow the
default 4 spaces of indent, it will be called as de-indentation. It is given in Fig. It
leads to an error that is specified in below fig.
Some statements may occupy more than one line. To indicate the continuation
of the current statement to the next line the continuation character \ (Backslash)
is used at the end of the current statement.
Example
A= b*c+(x-2*y) \
*(x%2)-36
Doc Strings
#Usage of docstring
def square(n):
'''Takes a number n & returns the square of n'''
return n**2
#Main Program
print("Square of 25 is:", square(25))
print("Doc String:",square.__doc__)
In program docsting is introduced below function definition to specify the
purpose of the function. It is possible to retrieve the docstrings in the program
using functionname._ _ doc _ _ attribute.
Output:
Square of 25 is: 625
Doc String: Takes a number n & returns the square of n
>>>
Identifiers
The name used to identify various objects like variable, function, class, module
and others is called an identifier.
Identifier naming conventions in Python:
Reserved words are those words that are reserved by the language itself for
specific purpose. A reserved word is "reserved for use as a keyword". The terms
"reserved word" and "keyword" are often used interchangeably. They cannot be
used as an identifier such as the name of a variable, function, or label. All the
Python keywords contain lowercase letters only.
Table Reserved Words in Python
input print format del main
if else elif for while
break continue pass def return
lamda global is in not
and or class with Open
try except finally assert type
Variables
An object whose value is changed during the execution of the program is called
a variable. A variable is a name that represents a value stored in the computer’s
memory. 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, the user can store integers, decimals or characters
in these variables.
Variable Naming conventions (rules):
Example
counter=0 #integer assignment
name=’Ram’ #string assignment
kilometres=1.069*miles #floating point assignment
a=a+1 #increment assignment
Example
>>>a=8
>>>b=11
>>>a=a+b
The above statement show a normal assignment that uses the variable ‘a’ twice
both in the left and rigt side of the equal sign(=).
In the augmented assignment, the variable ‘a’ can be used once
>>>a=8
>>>b=11
>>>a += b
Multiple Assignments
If more than one variables need to be initialized with the same value, they can
be initialized with a single Python statement. The process of assigning a single
object to multiple variables is called Multiple Assignment.
Syntax:
variableObject1=variableObject2=variableObject3=value
Example
>>>a=b=c=3.0
A floating-point object is created with values 3.0 and a, b and c are all assigned
the same reference to that object.
>>>x=y= 3*c
The objects x and y takes the value of the expression 3*c. The expression is
evaluated and the result is assigned to multiple objects x and y.
Multuple Assignment
Instead of assigning individual objects with values in a separate statement,
more than one variable objects can be assigned with more than one value in a
single statement. It is called a multuple assignment statement.
Example
>>> x,y,z=36,45.902,"PYTHON"
>>> x
36
>>> y
45.902
>>> z
'PYTHON'
>>>
In the above code, one integer object (with value 36), one floating-point object
(with value 45.902) and one string object (with value ‘PYTHON’) are assigned
to x, y and z respectively. Parentheses are normally used to denote tuples, and
although they are optional. They make the code easier to read.
Example for multiple assignments with paranthesis
>>> x,y,z=(36,45.902,"PYTHON")
>>> x
36
>>> y
45.902
>>> z
'PYTHON'
>>>
To interchange any two values in the C language, we need to use a temporary
variable.
Example in C Language:
#include<stdio.h>
void main()
{
int a=60, b=80, t;
t=a;
a=b;
b=t;
printf(“a=%d, b=%d”,a,b)
}
Output:
a=80, b=60
Initially a=80 & b=100. After swapping, a =100 and b=80. It is done in a single
multiple assignment statement.
a: 80 b: 100
After Sap
a: 100 b: 80
>>>
Tips:
Variables need not be declared before they are used
No need to declare variable types.
No memory management on the programmers' part
Variable names can be "recycled"
del statement allows for explicit "deallocation"
Python Objects
Python uses object model concepts for storing data. So everything is treated as
an object in Python. Any construct that contains any data type of value is called
an object.
For example the variable, the number and the list variable are all called objects.
Every Python objects have the following three characteristics:
An identity
Type
Value
Identity: The object’s identifier is a unique value. It is an address of the
memory location of that object. The unique identifier differentiates an object from
all others. It is obtained using the id () built-in function. id () function returns
the address of the memory location.
Type: An object's type indicates the data type of an object. The type() built-in
function is used to find the data type of a Python object. Since types are also
objects in Python.
Value: Value is a data item assigned to an object.
Program: Python objects characteristics
>>> x= 345
>>> id(x) # returns address of x
2920180680848
>>> type(x) #gives data type of x
<class 'int'>
>>> x #gives value in x
345
>>>
Data Types
In programming languages, the data type is a classification that represents the
type of value a variable takes and performs operations on it. A data type is simply
a set of values and the allowable operations on those values. Python supports a
set of basic (built-in) or standard data types and some auxiliary types. Most
applications generally use the standard types. The standard types are referred to
as "primitive data types". One of the features of Python related to data type is
dynamic typing. In dynamic typing, there is no need to declare the type of the
variable. The value is assigned to the variable object. The interpreter predicts the
type of the variable from the value assigned to it. It also accepts the re-assignment
of variables with different types.
Example
Program: dynamic typing
a=33.45
print("a is:",a)
print("Data type of a is:",type(a))
a='Excellent'
print("a is:",a)
print("Data type of a is:",type(a))
Object ‘a’ initially takes a float value. Later it is assigned with a string type of
data. Both are accepted by the object. The nature of changing the type and value
of the object is termed as dynamic typing.
Output
a is: 33.45
Data type of a is: <class 'float'>
a is: Excellent
Data type of a is: <class 'str'>
>>>
Standard Data types are grouped into five categories.
They are
a) Numeric Data Types
b) Sequences
c) Mappings
d) Sets
e) Others
Examples
16384L -0x4E8L 017L -2147483648l 052144364L
299792458l 0xDECADEDEADBEEFBADFEEDDEAL -5432101234L
Tip: Python long integers are different from other language long integers. In
other compiled languages long integers are restricted to 32- or 64-bit sizes,
whereas Python longs are limited only by the amount of (virtual) memory in the
machine.
Float (Floating Point numbers):
Floats are represented in fractional or scientific notations. It takes 8-byte
(64-bit) values. 52 bits are allocated to the mantissa, 11 bits to the exponent and
one bit to the sign. It gives the range ± 10308.25. Floating-point values are
denoted by a decimal point (.) in the appropriate place. In scientific notation, the
number has four parts. They are mantissa, the letter ‘e’ or ‘E’ that represents the
exponent followed by positive (+) or negative (-) signs and the exponent value.
The absence of a sign indicates a positive exponent.
In 4.3e25, 4.3 is a mantissa, the letter ‘e’, absence of sign indicates positive
power and the exponent value 25.
Examples
Floating point numbers : -5.555567119, 0.0978, 123.78654
Scientific notation: 9.384e-23, 4.2E-10, -1.609E-19
Complex Number:
A complex number is an ordered pair of floating-point real numbers (x, y)
denoted by x + yjformat where xis the real part and yis the imaginary part.
Imaginary numbers by themselves are not supported in Python. They are always
paired with a real part of 0.0 to make a complex number.
Syntax
Real+Imaginary j
where
Both real and imaginary components are floating-point values
The imaginary part is suffixed with the letter "J" . It may be a lower case
letter (j) or uppercase letter(J)
Examples
64.375+1j
4.23-8.5j
0+1j
Attributes of Complex Numbers:
Data Attributes:
[Link]: It gives the real component of complex numbers.
[Link]: Displays the imaginary component of complex numbers.
Method Attribute:
[Link]() : Returns complex conjugate of num
Sequences
The data structure that is organized in an ordered format is called
sequences. It includes String, List and Tuple. Data structures indicate the
organizing collection of data items in a specific format.
Strings
The collection of characters enclosed between quotes is known as Strings.
Python allows three forms of quotes
Single Quotes
Double Quotes
Triple Quotes
Pair of single and double quotes represents string whereas pair of triple single
quotes or double quotes represents documentations.
Program: Example code for string implementation
There is no difference between the usage of single quotes and double quotes to
represent strings. Single quotes are not useful to represent apostrophe commas
whereas double quotes can be used.
Program: apostrophes inside single quotes
>>> print('Welcome to Python's World')
List
A data structure that contains different types of data items separated by
commas and enclosed between square brackets ([]) is called Lists. Lists are
similar to arrays in C except that all the items belonging to a list can be of different
data types. Lists are mutable objects. It means that the data items within the list
can be modified.
The values stored in a list can be accessed using the slice operator ([ ] and [:]).
The list index starts from 0 and ends with the total number of elements in the list
-1. It has its own operators, functions and methods.
The above program shows the list data structure creation, accessing elements
and operators.
Output:
Contents of List_items1 are: [36, 45.0, 'JAVA', (3+5j)]
The First item/0th item in the list is: 36
[45.0, 'JAVA']
[33.789, 456, 33.789, 456]
['JAVA', (3+5j)]
[36, 45.0, 'JAVA', (3+5j), 33.789, 456]
>>>
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. Tuples are enclosed within
parentheses. Tuples are immutable objects. The data items within the tuple cannot
be modified.
The main differences between lists and tuples are:
Lists are enclosed in brackets ( [ ] ) but Tuples are enclosed in
parentheses(( ))
Lists are mutable means that their elements and size can be changed. But
tuples are immutable means that their elements cannot be modified.
They act as read only lists.
Program: Tuple implementation
tuple_items1 = (36,45.0,"JAVA",3+5j)
tuple_items2 = (33.789,456)
The above program shows the creation of tuple, accessing elements from tuple
and operators applied to tuple object.
Output:
Contents of Tuple_items1 are : (36, 45.0, 'JAVA', (3+5j))
The First item/0th item in the Tuple is: 36
(45.0, 'JAVA')
(33.789, 456, 33.789, 456)
('JAVA', (3+5j))
(36, 45.0, 'JAVA', (3+5j), 33.789, 456)
>>>
Mapping (Dictionary)
dict1['two'] = 2
dict1['three']=[6,7]
Set
A Set is an unordered collection of data with no duplicate elements. A
set supports operations like union, intersection, or difference. The function set()
creates a new set. It performs operations equivalent to mathematical set
operations.
Example
>>>set1=set() #creates new set without elements
>>>set2=set(['a','b','c','d','e','d']) # creates set with elements
>>>print(set2)
{'d','e','a','b','c' } #set2 without duplication
Boolean:
In the Python programming language, the Boolean data type is a primitive data
type having one of two values: True or False. This is a fundamental data type. It
is useful in conditional expressions.
Example
flag = True
None:
There is another special data type –None. Basically, the data type means non-
existent, not known or empty.
Example y=None
Data Type Conversion
During the program development, there may be the possibility to convert one
form of data into other forms. To convert between types, the type name can be
used as a function. There are several built-in functions to perform conversion
from one data type to another.
The input and output statements are used to receive data from the users and
display the outputs to the user
Input Statement
Input statement is used to read data fom [Link] for the program can be
read in three ways. They are
Static input
The value which is given as an input for the program can be assigned to the
variable using assignment operator (=) during the development of the program.
Example
a=34
b=128
Dynamic input
When the input is given during the execution of the program, it is called
dynamic input. The user can input their data during the execution time with the
help of the built-in functions input().
Syntax:
variable_object= input([“prompt string”])
where
prompt string is the message string and is optional.
This function reads integer, float and string data only as a string. Data type
coercion is used to convert them into required types.
Pogram reads the name and basic_pay from the user and displays those data items.
The input() function reads all types of data only in the form of a string. So
basic_pay is also read as a string. Data type conversion is required with input()
function to read data in the expected type like integer, float etc.
To display the data on the screen, Python uses print statements. The print
function normally displays a line of output.
Syntax:
print(variable_obj,variable_obj,…,sep=’separator’,end=’end’,file=[Link],
flush=false)
where
variable_obj represents a variable that holds the value.
sep represents the separator of values. It may be a blank space or any
delimiter.
end indicates the end of the character. Generally, it is a newline (\n). Any
delimiter may also be used.
the file represents the way of displaying output. Sys. stdout specifies the
console.
flush is a boolean value that indicates whether a buffer is cleared or not.
All the arguments except variable_object are optional
Program: Displaying output with print()
#output Statement: print()
num1=int(input("Enter a number:"))
num2=int(input("Enter one more number:"))
print (num1,num2,sep="\t")
print ("Number1:",num1, "Number2:",num2, sep="\n")
for i in range(1,6):
for j in range(i):
print(j, end='\t')
print("\n")
Multiple values can also be printed using a single print statement. When
multiple arguments are passed, they are automatically separated by a space when
they are displayed on the screen. If the developer of the program wants to
introduce the character as a separator between arguments, it will be introduced
using ‘sep’ argument as in program.
Output
Enter a number:7
Enter one more number:8
7 8
Number1:
7
Number2:
8
0
0 1
0 1 2
0 1 2 3
0 1 2 3 4
>>>
Expressions can also be directly incorporated into print() along with message
strings.
Below example shows printing values with message string.
>>> a=44
>>> b=12
>>> print("Multiplication of two numbers results:",a*b)
Multiplication of two numbers results: 528
>>>
Escape Characters
An escape characteris a special character that is used to introduce required spaces
or characters in the output. It is preceded by a backslash (\). It is always treated
as a string (enclosed between quotes) and also called as escape sequences.
Table Escape sequences
Escape Description
Character
New Line. Cursor is moved to the
\n
next line.
Tab. It moves the cursor to the next
\t
horizontal tab position
\v Vertical tab
\r Carriage return
\f Form feed
\” Double quote will be printed
\\ Back Slash character will be printed
\’ Prints single quote
\ooo Octal value
\xhh Hex value
Example
print('Sunday\t Monday\tTuesday\tWednesday\tThursday')
Output
Sunday Monday Tuesday Wednesday Thursday
Generally, the + operator is used to add two numbers. When the + operator is
used with two strings, it performs string concatenation. This means that it appends
one string to another.
Example
print('This is ' + 'one string.')
It will print
This is one string.
Formatted Outputs
The output of the program can be presented in several different forms. They
are
Formatting with string modulo operator(%)
Format() method
Syntax
print(‘String %format symbols’ % arg1,arg2,..)
The format symbol may take any one of the following symbols. It usually
represents the type of data.
Table Format Symbols
Format Conversion
Symbol
%c Character value will be
printed
%s String value using str()
%r String value via repr()
%d (or)%i Signed decimal integer
%u Unsigned decimal integer
%o Octal integer
%x (or)%X Hexadecimal integer
%e (or) %E Exponential notation
%f (or) %F Floating point number
%% Print % character
Output:
Format() function
The format () function is used to represent the way in which the value should
be displayed. It requires two arguments. The first one is the value to be displayed
and the second is the format specifier. The format specifier is a string that contains
special characters to represent the formatting of the given numeric value.
Syntax
format (variable_objetct, ’separator format specifier’)
where
The separator is used to introduce required separators between objects.
The format specifier requires precision and formatting character.
Formatting floats
The floating-point numbers are normally displayed with 12 significant digits
or more. Example,
>>> a=5; b=3.0
>>> a/b
1.6666666666666667
A simple division gives 17 digits as its output. So it is necessary to convert the
output into the required format.
Format to specific digits: it uses precision with format symbol ‘f’
>>>print(format(a/b,'.2f'))
1.67
.2f is the precision. It tells the number of digits after a fractional point. ‘f’ is a
format symbol for floating-point numbers.
Formatting floats with separators: it is used to include necessary separators with
numbers. The example shows a comma separator.
>>> print(format(20789.43789,',.2f'))
20,789.44
Formatting with Percentage:
To convert the given value into a percentage, the percentage symbol % will be
used instead of using format symbols like ‘f’. The % symbol multiplies the given
value by 100 and attaches % with it.
>>> print(format(mark_english,'.0%'))
71%
Formatting scientific notations: To represent the numbers in scientific notation
the format symbol ‘e’ or ‘E’ is used. The second argument is simply an ‘e’ or it
may be a precision followed by ‘e’. In both cases, it takes only 2 digits after the
sign.
>>> print(format(334821.3400089,'e'))
3.348213e+05
>>> print(format(334821.3400089,'.2e'))
3.35e+05
Formatting Integers
To format integers, the character ‘d’ is used as the format symbol and precision
is not required. Separators can be incorporated with numbers and additionally
width may be specified.
Example
0.777777777777
778
// Floor Divides one >>>a=47; b=6
Division value by other >>> a // b
7
and removes
fraction
% Modulo Gives >>> a=47; b=6
Division remainder of >>> a%b
division 5
** Exponenti Gives power >>> a= 13; b=2
ation for the given >>> a**b
base 169
The “/” operator and “//” operator performs division operations. But the
difference between them is the way in which they provide outputs. If the operands
are integer then division and floor division produce the same results. If the
operands are float, then division operation gives float output by performing
complete division but floor division makes the fraction to zero.
>>> a//b
>>> a=17.0;b=3.0
>>> a//b
5.0
>>>
The difference between integer and float data by applying floor division (//) is
given in the above program. The floor division operator applied to integer data
results in integer output whereas the same operator applied to float data results in
truncation of fraction, that is the fraction is made zero.
Modulo Division
Modulo division operator gives the remainder of the division. The sign of
modulo division depends on the divisor, not the dividend.
The relational operators determine whether any relationship exists among the
operands.
For example, to check whether the first operand is greater than the second
operand, greater than operator is used. Relational operators result only Boolean
outputs (True or False).
4. Assignment Operator
Bitwise operators work on bits. It converts the given number into bits and
performs the specified operation.
Tips: Left shift a number by one time is equivalent to multiplying the number
by 2. Similarly right shift a number by one time is equivalent to dividing the
number by 2.
6. Membership Operators
The example contains a list of names and reads a name from the user. Then it
checks whether the name provided by the user is a member or available in the list
of names. It displays “available” if the name is a member of the list otherwise
results in “Sorry Not Available”
Output
Enter a Name: Manoj
Available
>>>
The membership operator “in” can be used with conditional statements or can be
used directly as below.
>>> name_list=["Harish", "Manoj", "Raman", "Irfan"]
>>> name=input("Enter a Name:")
Enter a Name:Kishore
>>> name in name_list #in operator can be used directly
False
>>> name=input("Enter a Name:")
Enter a Name:Raman
>>> name in name_list
True
>>>
7. Identity Operators
Identity operators are also the special operators in Python. It compares the
memory locations of two objects. Memory locations of the objects can be
obtained from the id() method.
The precedence gives the rules for the order of evaluation of operators in an
expression when they are not grouped with parenthesis. It is applicable for
complex expressions. If the expression has more than one operator, the conflict
arises for choosing which operator is first for evaluation. Python provides priority
for selecting the operators. It is given as follows
Associativity
Example
In the example, two operators division (/) and multiplication (*) are given. Both
are equal precedence operators. Now it is necessary to select the order of
evaluating the expression. The operators are left-associative (in the sense they
select the left side of its operand first and apply the operation on the right side of
the operand), so the expression is evaluated from left to right. 25/5 results 5.0.
Then it is multiplied by 3 to produce 15.0.
Image
The above example is for the right-associative operator. The exponentiation
operator takes the right side of the operand first and applies the operation on the
left side of the operator. 2**2 results 4. Then 3**4 produces 81.
Expressions
Operators combined with operands form the expressions. Python has a rich set
of operators. By using these operators with operands different sorts of expressions
can be formed.
Arithmetic Expressions
When the arithmetic operators are used with operands, arithmetic expressions
are formed. They are useful to perform mathematical computations.
Table 3-11 Examples for expressions
Mathematical Programming
Expressions Statement
7x 7*x
3ab(5x+6y) 3*a*b*(5*x+6*y)
𝐴 = 𝜋𝑟 2 A=3.14*r*r
#calculate Interest
simple_interest=p*n*r/100
Relational Expressions
no1=int(input("Enter a number:"))
if no1>no2:
else:
The above program reads two numbers from the user and checks the biggest
number among the two.
Output
Enter a number: 345
Enter a second number: 239
The biggest is: 345
>>>
Enter a number: 54
Enter a second number: 1098
The biggest is: 1098
>>>
Logical Expressions
The logical operators with operands form logical expressions. The operands
should be relational expressions. It results in a Boolean outcome. It is used to
perform complex relational expressions.
Example
>>> a=23;b=49;c=12
>>> (a == b) or (a > c)
True
Bitwise Expressions
Control Structures
In Programming languages, the statements are categorized into two types
namely sequential statements and control flow statements.
Sequential statements: The set of statements that are executed in the order
one after another in which they are written is called sequential statements.
Control flow statements: The statements that alter the order of execution of
statements are called control flow statements or control structures.
The programs are generally written by using sequential statements. But in some
situations, it is necessary to decide which statement to be executed next based on
logical design. It leads to the introduction of control structures. It is represented
in two forms.
Selection or Decision making statements: The sequence of execution of the
statement is decided based on the condition mentioned in the current statement.
Loop or Repetition Statements: A set of statements are executed repeatedly
according to the logic of the program.
Selection or Decision Making Statements
a. Simple if statement
b. if-else statement
c. Nested if statement
d. elif ladder
Simple if Statement
It is the simplest form of decision structure. The simple “if” statement contains
a relational or logical expression. It is used to compare data and then a decision
is made based on the result of the comparison.
Syntax:
if conditional_expression:
True-suite
Statement-in-sequence
if conditional-expression : statement
Example
if option==1: print “Good”
Example
Program : Usage of Simple if
The Program reads a number from the user and checks whether it is an odd
number or even number using the modulo division operator (%). If the remainder
of any number by 2 results in 0, then it will be an even number otherwise it is an
odd number. The “if” clause header has a conditional expression no%2 == 0. On
executing this relational expression, the boolean output will be generated. If True
is produced then the statement which is followed by header (True-Suit) will be
executed. In this example, it prints the result as Even. After the completion of
True-Suit, the control jumps to the statement which is in sequence with “if”. Here
it moves to Line number 9 and prints “FOUND THE NUMBER TYPE"
Output of Program 4.2 is given below
Enter a number: 34
The given number 34 is EVEN
FOUND THE NUMBER TYPE
>>>
If the conditional expression no%2 == 0 gives False output, then control jumps
to the else part of the statement and False-suit will be executed.
Example
Enter a number: 315
The given number 315 is ODD
FOUND THE NUMBER TYPE
>>>
Nested if statement
The example program shows checking of the balance after withdrawing the
amount from the account. Every bank has been expecting the customer to
maintain a minimum balance in their account. Based on that, the minimum
balance in this example is Rs1000. The balance available in the account is say for
example Rs.8000. The customer has to input the amount to be withdrawn. If the
available balance is greater than the minimum balance then he/she is allowed to
withdraw. The above condition is introduced using a nested if statement. Line
number 5 checks for minimum balance against available balance. If it is true, the
available balance after withdrawal will be checked with a minimum balance. If
this is also true then the customer can withdraw the amount. Otherwise relevant
messages will be printed. It is given in line numbers 11 and 14. The two scenarios
are given as outputs below
Enter the amount to be withdrawn: 5000
Your withdraw Amount is: 5000.0
Balance is : 3000.0
>>>
Enter the amount to be withdrawn: 7500
After withdrawing 7500.0 your balance goes below mnimum balance
So you are unable to withdraw
>>>
if-elif-else Statement
A special case of the decision structure is the if-elif-else statement. The “if”
clause can be introduced inside the false block of the if statement also. It makes
the logic simpler to write. It is known as the elif ladder.
Syntax:
if conditional_expression_1:
True-suite_1
elif conditional_expression _2:
True-suite_2
….
else:
False-suite
statement_in_sequence
The example shows mark list processing using if-elif-else. Marks for four
subjects are read from the user from lines 5 to 8. The total and average of the
marks are calculated. If marks in all the subjects are greater than or equal to 40,
then the result will be Pass. If Pass, then grade will be calculated. If Fail, there is
no grade and the result will be printed as “Re Appear”.
Output
Enter Mark1: 67
Enter Mark2: 81
Enter Mark3: 64
Enter Mark4: 70
-----------------------
Marks and Grade
-----------------------
Mark1 : 67
Mark2 : 81
Mark3 : 64
Mark4 : 70
Result : Pass
Percentage Obtained: 70.5
Grade: First Class
Tip: switch..case is not supported in Python. But it can be implemented using the
elif statement. Similarly, there is no ternary or conditional operator(?:) in Python.
In entry controlled statements, the set of statements are allowed to execute only
after testing the conditional expression. If the conditional expression results true,
the looping statements are executed.
In exit controlled statements, the decision to repeat the set of statements is
decided only at the end of the looping statements. The conditional expression to
continue the loop is tested, and if it results true, then the set of statements are
repeated. In exit controlled loop, the body of the loop will be executed at least
once if the conditional expression results false initially.
‘while’ loop comes under entry controlled loop. It first tests the condition and
then continues with iteration. The test is done at the beginning of the loop. The
loop has two parts
a. a condition that is tested for a true or false value and
b. a statement or set of statements that is repeated as long as the condition is
true.
Syntax:
while conditional_expression:
Statement
Statement
Statement
statement-in-sequence
The first line refers to the while clause header. It begins with the keyword ‘while’,
followed by a boolean conditional expression that will be evaluated as either true
or false. When the while loop executes, the conditional expression is tested. If itis
true, the statements that appear in the block following the while clause are
executed, and then the loop starts over. If the conditional expression is false, the
program exits the loop and continues with statement-in-sequence, the next
statement of the program.
The above program shows condition controlled while loop. It has three parts.
First is the loop control variable ‘i’. It should be initialized before the starting of
the loop with the starting value 11. The second is the while clause header. It
checks whether the loop controlled variable reaches 21. If ‘i’ is less than or equal
to 20, the loop body will be executed. The third one is incrementing the loop
control variable ‘i'. By changing the value of ‘i’ loop is made to continue or exit.
Inside the loop body, the executable statements are introduced.
Output
11
12
13
14
15
16
17
18
19
20
Next Statement in Sequence
>>>
When ‘i' reaches 21, the control jumps to the while clause header and checks
the condition. Now the condition is false, so the control moves to the next
statement in sequence. The only way to exit from the loop is to make the
conditional expression false.
In a condition controlled loop, the loop control variable is not incremented or
decremented inside the loop body. Instead of that, it should be modified to apply
the conditional expression. Program 4.6 shows a condition controlled loop. The
object ‘option’ is used as a condition controlled variable. Every time the
conditional expression checks whether it is equal to ‘y’. If it is so, the looping
statements are executed and the loop is continued. Otherwise, control exits from
the loop and the next statement will be executed. If the option flag is not equal to
‘y’, the contents of the list will be displayed.
Example
Program : while statement with conditional flag
Output
Enter any number: 45
Output
23
56
10
90
for loop
In programming languages like C, Java etc, the for loop follows the traditional
format. It includes the initialization, checking for conditional expression to
continue the loop and modifying the value of loop control variable in for clause
header. But in Python the for loop acts like a ‘for each’ loop as in other scripting
languages.
Syntax
for iteration_object in sequence:
suite/block of statements/loop body
next-statement
The for clause header retrieves each item in the sequence into an iteration
object (variable) and executes the loop body until there is no element in the
sequence. The for loop is applied only to sequence types of objects. The iteration
is done with individual items in the sequence or with the index of the sequence.
Example
The program displays the elements of the sequence type data (List and String)
using a for loop. The items from the numberList are retrieved one by one,
assigned it one by one, and assigned to iterator object nlist. Then it is displayed.
Output
23
56
10
90
Elements of List is printed
C
o
m
p
u
e
t
r
Items in String is printed
>>>
Instead of iterating over individual items, indices can also be used for iteration
and it is done with range() built-in function. The range() function takes only the
continuous values from starting and end value-1 with step. It is done with the help
of range() built-in function.
Syntax
range(start,end,step)
where:
start: indicates initial value
end : indicates last value
step : indicates increment value and it is optional.
All the values in between the start and end-1 value will be generated. The
default step value is 1. If the step value is anything other than 1, it will be added
to the start value to obtain the next value.
Example: The below code prints the number from 10 to 14 using range()
function.
>>> for a in range(10,15): print(a)
10
11
12
13
14
>>>
Example 2: The introduction of step value modifies the value assigned to the
iteration object.
10
12
14
16
18
>>>
Example 3: The step value may be a negative value. Negative step value
decrements the start up to end value every time.
>>> for c in range(20,10,-2):print(c)
20
18
16
14
12
>>>
The loop with indices is usually combined with the range() function with the
len() function to make the code easier.
Example
Program : for statement with range() function
In the above program the range() function generates the index of the list from
0 to the length of the sequence minus 1. Then to retrieve the elements from
numberList, the subscription operator[ ] with index i is used.([i])
Output
0 th element is: 23
1 th element is: 56
2 th element is: 10
3 th element is: 90
Elements of List is printed
>>>
Loop Statements with else clause
In Python, while and for loops can also be used with the else clause. The else
clause is executed if the conditional expression is false in the while loop. The else
clause will be executed only when a break statement does not terminate the
loop. The normal exit from the loop executes the else clause, whereas the pre
matured exit does not execute the else clause.
Program: while with else
In program the loop is terminated after printing all the specified values of ‘i’. That
is the loop follows normal exit. So the statements in else block is continued after
it.
Output
0
1
2
3
else part of while
Next statement
>>>
Program:else clause implementation with while
Program is same as that of program 4.9 with only one difference. It is the
introduction of break statement after printing ‘i' value. The break statement in
line number 5 causes premature exit from the while loop. So the else block
statement is not executed.
Output
0
Next statement
>>>
The break statement in Python terminates the current loop and continues the
execution from the next statement in sequence with the program. It is used to
come out from the loop completely. The break statement can be used in
both while and for loops.
Syntax:
Break
Program : use of break statement
1 #Read a string and print the characters till the first vowel is found
2 string1=input("Enter any String:\t")
3 for s in range(0,len(string1)):
4 if string1[s] == 'a' or string1[s]=='e' or string1[s]=='i' or \
5 string1[s]=='o' or string1[s]=='u':
6 break
7 print(string1[s])
8 print("First vowel found in position", s)
Line number 2 reads a sentence from the user. Using the for loop with range()
and len() function, the index is extracted and assigned to the object ‘s’. Then the
character which is specified by the position’s’ in string1 is checked for vowel. If
it is not a vowel (a,e,i,o,u), it will be printed. If it is a vowel, the break statement
is executed which moves the control out of the loop and the loop is terminated.
The program uses a break statement to completely exit out of the loop when the
vowel is found.
Output
Enter any String: Python is a interpreted language
P
y
t
h
First vowel found in position 4
>>>
continue statement
The continue statement returns the control to the beginning of the loop clause
header. The continue skips 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.
Syntax:
Continue
Program : use of continue statement
pass statement
The pass statement is called as a do-nothing statement. It does not perform any
activity. The pass statement is used when a statement is required syntactically but
does not execute any code. This is useful to test the flow of the statement block
for example, the function definition.
Program: use of pass statement
The pass statement inside the loop does not perform anything forms a do-nothing
loop. Instead, the loop control variable ‘i’ is incremented and tested for every
time until it reaches 11. If it reaches 11, the conditional expression is made false,
and the next statement's sequence will be executed.
Output
The program prints ‘*’ for the number of rows times. For that, a nested for loop
is used. The outer loop with loop control variable ‘i’ indicates row,s and the inner
loop with loop control variable ‘j’ specifies columns.
Output
Enetr number of rows: 4
*
* *
* * *
* * * *
>>>
Infinite Loops
If a loop does not stop a way, it is called an infinite loop. An infinite loop
continues to repeat until the program is interrupted. Infinite loops usually occur
when the programmer forgets to write code inside the loop that makes the test
condition false. In most circumstances, you must avoid writing infinite loops.
Example
Program: infinite loop
1 #infinite Loop
2 #Print the numbers from 10 to 20
3 i=10
4 while i!=-1:
5 print i
6 i +=1
7 print "Nicely print the numbers"
Output
math module
The math module is a collection of mathematical functions. These include
trigonometric functions, representation functions, logarithmic functions, angle
conversion functions, etc. In addition, two mathematical constants pi and e are
also defined in this module.
[Link] gives the value 3.141592653589793
math.e gives Euler’s number. It is the base of natural logarithm. Its value is
2.718281828459045.