KEMBAR78
PYTHON-Unit-I-Notes for python learnerss | DOCX
<DEPARTMENT OF PG MATHEMATICS> PLAN-ACT-SUCCEED
1
UNIT-I NOTES
< Introduction to Python Programming – 22BMA5EA0>
UNIT 1 (Copy-Paste from the Syllabus)
Introduction to Python: Introduction - Python Overview - Getting Started with Python –
Comments - Python Identifiers - Reserved Keywords – Variables - Standard Data Types –
Operators - Statement and Expression - String Operations - Boolean Expressions - Control
Statements - Iteration – while Statement - Input from Keyboard
TOPICS(Should match with the Teaching Plan in CAMU)
NO. TOPICS
1 Introduction to Python: Introduction - Python Overview - Getting Started with
Python – Comments - Python Identifiers - Reserved Keywords
2 Variables - Standard Data Types – Operators - Statement and Expression - String
Operations
3 Boolean Expressions - Control Statements - Iteration – while Statement - Input from
Keyboard
4 Summary of Unit – I
LEARNING OUTCOMES
NO. LEARNING OUTCOMES
1 To start with the key features of the Python programming language, comments, identifiers
and keywords
2 To describe the variables, data types, various operators, statements , expressions, and
handling string operations
3 Identify the structure and syntax of Boolean expressions, control statements like if
statements, while statement, and getting input through keyboard
4
Summary of Unit – I
<DEPARTMENT OF PG MATHEMATICS> PLAN-ACT-SUCCEED
2
INTRODUCTION
Python is a high-level, interpreted, general-purpose, dynamic programming language. Python
was conceived in the late 1980s and its usage began from December 1989. It is a widely used
programming language. Python possesses a property of code termed reusability. The syntax
of Python programs can express concepts in fewer lines as compared to programs in C, C++
and JAVA.
Python can be used in multiple programming styles, including Object-Oriented, Functional
programming Procedural Programming and Imperative styles. It also supports automatic
memory management and has a large standard library and innumerous set of third party
libraries. Python can be used on almost every operating system because its interpreter is
available for many operating systems.
Python is free and open-source software. Open-source software is a kind of computer
software in which the source code of the software is made public, i.e., the copyright holder
gives rights to everyone to read, change and distribute the code for any purpose. It generally
has a community-based development.
DETAILED NOTES
INTRODUCTION
PYTHON OVERVIEW
Python is a high-level general-purpose programming language. Some of its key features are as
follows:
● The code written in Python is automatically compiled to byte code and executed.
● Python can be used as a scripting language, as a language for implementing web
applications, etc.
● Extending Python with C or C++ can help in the performance of intensive tasks
where speed ofexecution is a key criterion.
● Python supports many features such as nested code blocks, functions, classes, modules
and packages.
● Python makes use of an object-oriented programming approach.
Python has several additional features which are as follows:
● It has many built-in data types: strings, lists, tuples, dictionaries, etc.
● It supports many control statements such as if, if-else, if-elif-else, while, iterativefor, etc.
<DEPARTMENT OF PG MATHEMATICS> PLAN-ACT-SUCCEED
3
Note Python 2.7.x version of python interpreter is being discussed throughout this book.
Install Python 2.7.x for better results. Many Examples listed in this book may or may not
work under Python 3.x.
● It allows for easier programming with the use of functions, classes, modules and
packages.
GETTING STARTED WITH PYTHON
There are three different ways of starting Python:
1. Running a script written in Python
2. Using a Graphical user interface (GUI) from an Integrated Development Environment
(IDE)
3. Employing an interactive approach
The first approach will require a text editor. We will have to create our scripts and then
execute them using the text editor. The second approach will require a GUI application, one
that comes with the Python installer itself. The third interactive approach is the one we will
be using in this book. Python provides us a command line interpreter that we will utilise for
this approach.
Now, try to interact with the interpreter by entering a simple expression, 8 + 9, on the
console. After entering the expression, press the Enter key to get the result.
>>> 8+9
17 # Output
>>>
The given example shows how Python can also work as a simple
calculator.Now, type the following text at the Python prompts and
press Enter.
>>> print “Hello, Python!”
This produces the following result:
Hello, Python! # Output
Now, let us try some more examples.
>>> Hello
<DEPARTMENT OF PG MATHEMATICS> PLAN-ACT-SUCCEED
4
Note The print statement is used to display output to the screen. Those of you who are
familiar with C know that the printf() function produces screen output. Many shell script
languages use the echo command for program output.
Check Your Understanding
1. What is Python?
Ans. Python is a high-level, interpreted, interactive and object-oriented scripting
language. It is a highly readable language. Unlike other programming
languages, Python provides an interactive mode similar to that of a calculator.
After writing Hello, when you hit the Enter key, an error message will be displayed. This is
because Python does not have any Hellocommand and its interpreter is unable to identify the
command.
>>> Hello
Traceback (most recent call last): # Output
File “<pyshell#0>”, line 1, in <module>Hello
NameError: name ‘hello’ is not defined
However, if you want to display a message on the console, you will need to keep your
message within quotes. This tells the interpreter that the text entered is not a command.
Therefore, the interpreter simply echoes the text.
>>> ‘Hello’
‘Hello’ # Output
TIP
The print statement, paired with the string format operator (%), behaves even more like
C’s printf() function.
<DEPARTMENT OF PG MATHEMATICS> PLAN-ACT-SUCCEED
5
Check Your Understanding
1. What are comments?
Ans. Comments are annotations made by the programmer. These help other
programmers inunderstanding the code.
2. Which character is used for commenting in Python?
Ans. Hash mark (#) is used for commenting in Python.
COMMENTS
Just like other programming languages, Python allows you to add comments in the code.
Comments are used by the programmer to explain the piece of code to others as well as to
himself in a simple language. Every programming language makes use of some special
character for commenting, so does Python.
Python uses the hash character (#) for comments. Putting # before a text ensures that the text
will not be parsed by the interpreter. Comments do not affect the programming part and the
Python interpreter does not display any error message for comments. Comments show up as it
is in the programming. It is a good practice to use comments for program documentation in
your program so that it becomes easier for other programmers to maintain or enhance the
program when required.
Now, take a look at some examples of comments used in Python. Commenting without the use of
Hash mark (#)
>>> 8+9 addition
SyntaxError: invalid syntax # Output
>>>
In the above example, ‘addition’ is written without the Hash mark. As a result, the interpreter
accepts the word ‘addition’ as part of programming. Since ‘addition’ is not a command in
Python, an error message is displayed.
Commenting using Hash mark (#)
>>> 8+9 #addition
17 # Output
>>>
Now, in this example, ‘addition’ is written with a Hash mark. Hence, the interpreter
understands it as a comment and does not display any error message.
<DEPARTMENT OF PG MATHEMATICS> PLAN-ACT-SUCCEED
6
PYTHON IDENTIFIERS
A Python identifier is the name given to a variable, function, class, module or other object. An
identifier canbegin with an alphabet (A – Z or a – z), or an underscore (_) and can include any
number of letters, digits,or underscores. Spaces are not allowed.
Python will not accept @, $ and % as identifiers. Furthermore, Python is a case-sensitive
language. Thus, Hello and hello both are different identifiers. In Python, a class name will
always start with a capital letter.
Table 3.1 provides examples of valid and invalid names for creating identifiers.
TABLE 3.1 Examples of Valid and Invalid Names for Creating Identifiers
Examples of Identifiers
Valid Invalid
MyName My Name (Space is not allowed)
My_Name 3dfig (cannot start with a digit)
Your_Name Your#Name (Only alphabetic character, Underscore ( _ ) and
numeric are allowed
RESERVED KEYWORDS
Just like other programming languages, Python has a list of reserved words known as
keywords. Every keyword has a specific purpose and use. In the upcoming chapters, we will
look into the use of these keywords in programming.
A list of reserved keywords in Python:
and del from None True
as elif global nonlocal try
assert else if not while
break except import or with
class False in pass yield
continue finally is raise
def for lambda return
VARIABLES
Declaring a Variable
A variable holds a value that may change. The process of writing the variable name is called
Declaring the variable. In Python, variables do not need to be declared explicitly in order to
reserve memory spaces as in other programming languages like C, Java, etc. When we initialize
the variable in Python, Python Interpreterautomatically does the declaration process.
<DEPARTMENT OF PG MATHEMATICS> PLAN-ACT-SUCCEED
7
Year name
Albert
2016
Initializing a Variable
The general format of assignment statement is as follows:
Variable = expression
The equal sign (=) is known as Assignment operator. An expression is any value, text or
arithmetic expression, whereas variable is the name of the variable. The value of the expression
will be stored in the variable.
Let us now look at an example of initialising a variable:
>>>year=2016
>>> name=’Albert’
The two given statements reserve two memory spaces with variable names yearand name.2016
and Albert, are stored respectively, in these memory spaces as shown in Fig. 3.7.
Memory
Figure 3.7
TIP
Whenever you want to display the value of the variables, simply type these variable
nameson console.
Let us now look at an example of a variable displaying its value:
>>> year
2016 # Output
>>> name
‘Albert’ # Output
>>>
<DEPARTMENT OF PG MATHEMATICS> PLAN-ACT-SUCCEED
8
Note You can also assign one variable value into another variable. Assign the value of
name1 variable into name2 variable.
Let us now look at an example of assigning one variable value into another:
>>> name1=’Albert’
>>> name2=name1
>>> name2
‘Albert’ # Output
>>>
Whenever two values are successively assigned to a variable, the interpreter will forget the
previous valueassigned to it and store the latest value in the variable memory space.
>>> year=2016
>>> year=2017
>>> year
2017 # Output
>>>
In the given example, we first assigned 2016 to the variable year and then assigned 2017 to the
same variable. The interpreter will forget the value 2016 and will display 2017as the value of
year.
We can also assign different types of values to the same variable. For example, we can assign a
text valuewhere there previously was a numeric value. Even in such a case however, only the last
assigned value remains.
Let us now look at an example of assigning different types of values to the same variable:
>>> amount=50
>>> amount
50 # Output
>>> amount=’Fifty’
<DEPARTMENT OF PG MATHEMATICS> PLAN-ACT-SUCCEED
9
>>> amount
‘Fifty’ # Output
>>>
STANDARD DATA TYPES
The data stored in the memory can be of many types. For example, a person’s name is stored as an
alphabeticvalue and his address is stored as an alphanumeric value. Sometimes, we also need to
store answer in terms of only ‘yes’ or ‘no’, i.e., true or false. This type of data is known as
Boolean data.
Python has six basic data types which are as follows:
1. Numeric
2. String
3. List
4. Tuple
5. Dictionary
6. Boolean
Numeric
Numeric data can be broadly divided into integers and real numbers (i.e., fractional numbers).
Integers can themselves be positive or negative. Unlike many other programming languages,
Python does not have any upper bound on the size of integers. The real numbers or fractional
numbers are called floating point numbers in programming languages. Such floating point
numbers contain a decimal and a fractional part.
Let us now look at an example that has an integer as well as a real number:
>>> num1=2 # integer number
>>>num2=2.5 # real number (float)
>>>num1
2 # Output
>>>num2
2.5 # Output
>>>
<DEPARTMENT OF PG MATHEMATICS> PLAN-ACT-SUCCEED
10
Check Your Understanding
1. What are data types?
Ans. The data you have to manipulate can be in different forms. For example, the
name of a personis in string form while his age is in numeric form.
Note In all the earlier versions of Python 3, slash (/) operator worked differently. When
both numerator and denominator are integers, then the result will be an integer. The slash
operator removes the fraction part.
Let us look at an example of the division operator in all the earlier versions of Python 3:
>>> 5/2
2 # Output
>>>
The result becomes a floating number when either the numerator or the denominator is a floating
number. When both the numerator and the denominator are floating numbers, the result is again
a floating number.
Let us look at an example of the division operator in all the earlier versions of Python 3:
>>> 5.0/2
2.5 # Output
>>>
This operator has been modified in Python 3 and in all the versions after Python 3. The division
operatorprovides accurate results even when both the numerator and the denominator are
integers.
Here is an example of the division operator that is used in all the versions after Python 3:
>>> 5/2
2.5 # Output
>>>
<DEPARTMENT OF PG MATHEMATICS> PLAN-ACT-SUCCEED
11
Syntax
>>> sample_string[start : end <:step>] #step is optional
String
Besides numbers, strings are another important data type. Single quotes or double quotes are used
to represent strings. A string in Python can be a series or a sequence of alphabets, numerals and
special characters. Similar to C, the first character of a string has an index 0.
There are many operations that can be performed on a string. There are several operators such
as slice operator ([]) and [:]), concatenation operator (+), repetition operator (*), etc. Slicing is
used to take out a subset of the string, concatenation is used to combine two or more than two
strings and repetition is used torepeat the same string several times.
Here is an example of string data:
>>> sample_string =”Hello” # store string value
>>> sample_string # display string value
‘Hello’ # Output
>>> sample_string + “World” # use of + operator
‘HelloWorld’ # Output
>>> sample_string * 3 # use of * operator
‘HelloHelloHello’ # Output
Python also provides slice operators ([] and [:]) to extract substring from the string. In Python,
the indexing of the characters starts from 0; therefore, the index value of the first character is 0.
Example
>>>sample_string=”Hello”
>>>sample_string[1]
‘e’
>>>sample_string[0:2]
‘He’
# display 1st index element.
# Output
# display 0 to 1st index elements
# Output
<DEPARTMENT OF PG MATHEMATICS> PLAN-ACT-SUCCEED
12
Example
>>> sample_string = "HelloWorld"
>>> sample_string[1:8:2] # display all the alternate charactors between index 1
to 8. ie, 1,3,5,7
'elWr' # Output
List
List is the most used data type in Python. A list can contain the same type of items.
Alternatively, a list can also contain different types of items. A list is an ordered and
indexable sequence. To declare a list in Python, we need to separate the items using commas
and enclose them within square brackets([]). The list is somewhat similar to the array in C
language. However, an array can contain only the same type of items while a list can contain
different types of items.
Similar to the string data type, the list also has plus (+), asterisk (*) and slicing [:]
operators for concatenation, repetition and sub-list, respectively.
Let us look at an example of the List data type:
>>>first=[1,”two”,3.0,”four”] # 1st
list
>>>second=[“five”, 6] # 2nd
list
>>>first # display 1st
list
[1, ‘two’, 3.0, ‘four’] # Output
>>>first+second # concatenate 1st
and 2nd
list
[1, ‘two’, 3.0, ‘four’, ‘five’, 6]# Output
>>>second * 3 # repeat 2nd
list
[‘five’, 6, ‘five’, 6, ‘five’, 6] # Output
>>>first[0:2] # display sublist
[1, ‘two’] # Output
>>>
<DEPARTMENT OF PG MATHEMATICS> PLAN-ACT-SUCCEED
13
Tuple
Similar to a list, a tuple is also used to store sequence of items. Like a list, a tuple consists of
items separatedby commas. However, tuples are enclosed within parentheses rather than within
square brackets.
Let us look at an example of the tuple data type:
>>>third=(7, “eight”,9, 10.0)
>>>third
(7, ‘eight’, 9, 10.0) # Output
Lists and tuples have the following differences:
 In lists, items are enclosed within square brackets [], whereas in tuples, items are
enclosed withinparentheses ().
 Lists are mutable whereas Tuples are immutable. Tuples are read only lists. Once the
items are stored,the tuple cannot be modified.
Let us look at an example of list and tuple data type:
>>>first[0]=”one”
>>>third[0]=”seven”
Traceback (most recent call last): # Output
File “<pyshell#15>”, line 1, in <module>
third[0]=”seven”
TypeError: ‘tuple’ object does not support item assignment
TIP
The items cannot be modified in a tuple but the same is not the case with a list.
Dictionary
It is the same as the hash table type. The order of elements in a dictionary is undefined. But,
we can iterateover the following:
1. The keys
2. The values
3. The items (key-value pairs) in a dictionary
<DEPARTMENT OF PG MATHEMATICS> PLAN-ACT-SUCCEED
14
A Python dictionary is an unordered collection of key-value pairs. When we have the large
amount of data, the dictionary data type is used. Keys and values can be of any type in a
dictionary. Items in dictionaryare enclosed in the curly-braces{} and separated by the comma
(,). A colon (:) is used to separate key from value. A key inside the square bracket [ ] is used
for accessing the dictionary items.
Example of dictionary:
>>> dict1 = {1:"first line", "second":2} # declare dictionary
>>> dict1[3] = "third line" # add new item
>>> dict1 # display dictionary
{1: 'first line', 'second': 2, 3: 'third line'} #Output
>>> dict1.keys() # display dictionary keys
[1, 'second', 3] # Output
>>> dict1.values() # display dictionary values
['first line', 2, 'third line'] # Output
Boolean
In a programming language, mostly data is stored in the form of alphanumeric but sometimes
we need to store the data in the form of ‘Yes’ or ‘No’. In terms of programming language,
Yes is similar to True and No is similar to False.
This True and False data is known as Boolean Data and the data types which stores this
Boolean data areknown as Boolean Data Types.
Example
>>> a = True
>>> type(a)
<type ‘bool’>
>>> x = False
>>> type(x)
<type ‘bool’>
<DEPARTMENT OF PG MATHEMATICS> PLAN-ACT-SUCCEED
15
Sets
The lists and dictionaries in Python are known as sequence or order collection of data.
However, in Python we also have one data type which is an unordered collection of data
known as Set. A Set does not contain any duplicate values or elements.
Union, Intersection, Difference and Symmetric Difference are some operations which are
performed on sets.
Union: Union operation performed on two sets returns all the elements from both the sets. It
is performedby using & operator.
Intersection: Intersection operation performed on two sets returns all the element which are
common or in both the sets. It is performed by using | operator.
Difference: Difference operation performed on two sets set1 and set2 returns the elements
which are presenton set1 but not in set2. It is performed by using – operator.
Symmetric Difference: Symmetric Difference operation performed on two sets returns the
element which are present in either set1 or set2 but not in both. It is performed by using ^
operator.
# Defining sets
>>> set1 = set([1, 2, 4, 1, 2, 8, 5, 4])
>>> set2 = set([1, 9, 3, 2, 5])
type()Function
type() function in Python programming language is a built-in function which returns the
datatype of any arbitrary object. The object is passed as an argument to the type() function.
Type() function can take anything as an argument and returns its datatype, such as integers,
strings, dictionaries, lists, classes, modules, tuples,functions, etc.
>>> print union
set([1, 2, 3, 4, 5, 8, 9])
#Output
>>> difference = set1 - set2
>>> print difference
set([8, 4])
# Difference of set1 and set2
#Output
>>> symm_diff = set1 ^ set2 # Symmetric difference of set1 and
set2
>>> print symm_diff
set([3, 4, 8, 9]) #Output
<DEPARTMENT OF PG MATHEMATICS> PLAN-ACT-SUCCEED
16
Example
>>> x = 10
>>> type(x)
<type ‘int’> #Output
>>> type(‘hello’)
<type ‘str’> #Output
>>> import os
>>> type (os)
<type ‘module’> #Output
>>> tup = (1,2,3)
>>> type(tup)
<type ‘tuple’> #Output
>>> li = [1,2,3]
>>> type(li)
<type ‘list’> #Output
Check Your Understanding
1. What is a list?
Ans. A list is a dynamic array or sequence that is ordered, indexable and mutable. It is
one of the most versatile compound data types of Python. A list is used to store
multiple items separated by commas within square brackets [].
2. What is the output of print list[2]when list = [‘abcd’, 2.23, ‘john’]?
Ans. john
3. What is the main difference between a list and a tuple?
Ans. In a list, items are enclosed within square brackets; tuple is a sequence of items
separated by comma and enclosed in parentheses.
<DEPARTMENT OF PG MATHEMATICS> PLAN-ACT-SUCCEED
17
Note Items separated by ‘comma’ is the signature of tuple not parenthesis
OPERATORS
Operators are constructs used to modify the values of operands. Consider the following
expression:
3 + 4 = 7
In the above expression, 3 and 4 are the operands whereas + is operator. Based on functionality,
operators are categories into following seven types:
1. Arithmetic operator
2. Comparison operator
3. Assignment operator
4. Logical operator
5. Bitwise operator
6. Membership operator
7. Identity operator
Arithmetic Operators
These operators are used to perform arithmetic operations such as addition, subtraction,
multiplication anddivision (Table 3.2).
TABLE 3.2 List of Arithmetic Operators
Operator Description Example
+ Addition operator to add two operands. 10+20=30
– Subtraction operator to subtract two operands. 10–20=–10
* Multiplication operator to multiply two operands. 10*20=200
/ Division operator to divide left hand operator by right hand
Operator.
5/2=2.5
** Exponential operator to calculate power. 5**2=25
% Modulus operator to find remainder. 5%2=1
// Floor division operator to find the quotient and remove the
fractional part.
5//2=2
<DEPARTMENT OF PG MATHEMATICS> PLAN-ACT-SUCCEED
18
Comparison Operators
These operators are used to compare values. Comparison operators are also called relational
operators. The result of these operators is always a Boolean value, that is, either true or false.
Table 3.3 provides a list of comparison operators.
Example
>>> x = 10
>>> y = 12
>>> z = 0
>>> z = x + y
>>> print z
22
#Ouput
>>> z = x - y
>>> print z
-2
#Ouput
>>> z = x * y
>>> print z
120
#Ouput
>>> z = x / y
>>> print z
0
#Ouput
>>> z = x % y
>>> print z
10
#Ouput
>>> z = x ** y
>>> print z
1000000000000
#Ouput
>>> z = x // y
>>> print z
0
#Ouput
<DEPARTMENT OF PG MATHEMATICS> PLAN-ACT-SUCCEED
19
TABLE 3.3 List of Comparison Operators
Operator Description Example
== Operator to check whether two operands are equal. 10 == 20, false
!= or <> Operator to check whether two operands are not equal. 10 !=20, true
> Operator to check whether first operand is greater than
second operand.
10 > 20, false
< Operator to check whether first operand is smaller than
second operand.
10 < 20, true
>= Operator to check whether first operand is greater than or
equal to second operand.
10 >= 20, false
<= Operator to check whether first operand is smaller than or
equal to second operand.
10 <= 20, true
Example
>>> x = 10
>>> y = 12
>>> z = 0
>>> if (x == y):
print “x is equal to y”
else:
print “x is not equal to y”
x is not equal to y #Output
>>> if (x != y):
print “x is not equal to y”
else:
print “x is equal to y”
x is not equal to y #Output
>>> if (x <> y):
<DEPARTMENT OF PG MATHEMATICS> PLAN-ACT-SUCCEED
20
print “x is not equal to y”
else:
print “x is equal to y”
x is not equal to y #Output
>>> if (x < y):
print “x is less than y”
else:
print “x is not less than y”
x is less than y #Output
>>> if (x > y):
print “x is greater than y”
else:
print “x is not greater than y”
x is not greater than y #Output
>>> if (x <= y):
print “x is either equal to or less than y”
else:
print “x is neither equal to nor less than y”
x is either equal to or less than y #Output
>>> if (x >= y):
<DEPARTMENT OF PG MATHEMATICS> PLAN-ACT-SUCCEED
21
Assignment Operators
This operator is used to store right side operand in the left side operand. Table 3.4 provides
a list of assignment operators.
TABLE 3.4 List of Assignment Operators
Operat
or
Description Example
= Store right side operand in left side operand. a=b+c
+= Add right side operand to left side operand and store the result
in left side operand.
a+=b or
a=a+b
– = Subtract right side operand from left side operand and store
the result in left side operand.
a–=b or
a=a–b
* = Multiply right side operand with left side operand and store
the result in left side operand.
a*=b or
a=a*b
/ = Divide left side operand by right side operand and store the
result in left side operand.
a/b or a=a/b
% = Find the modulus and store the remainder in left side operand. a%=b
or
a=a%b
** = Find the exponential and store the result in left side operand. a**=b or
a=a**b
// = Find the floor division and store the result in left side operand. a//=b or
a=a// b
Example
>>> x = 10
>>> y = 12
>>> y += x
>>> print y
22
print “x is either equal to or greater than y”
else:
print “x is neither equal to nor greater than y”
x is neither equal to nor greater than y #Output
<DEPARTMENT OF PG MATHEMATICS> PLAN-ACT-SUCCEED
22
Example
>>> x = 10
>>> y = 12
>>> y += x
>>> print y
22
#Output
>>> y *= x
>>> print y
220
#Output
>>> y /= x
>>> print y
22
#Output
Bitwise Operators
These operators perform bit level operation on operands. Let us take two operands x = 10 and
y = 12. Inbinary format this can be written as x = 1010 and y = 1100. Table 3.5 presents a list of
bitwise operators.
>>> y %= x
>>> print y
2
#Output
>>> y **= x
>>> print y
1024
#Output
>>> y //= x
>>> print y
102
#Output
<DEPARTMENT OF PG MATHEMATICS> PLAN-ACT-SUCCEED
23
TABLE 3.5 List of Bitwise Operators
Operator Description Example
& Bitwise
AND
This operator performs AND operation between
operands. Operatorcopies bit if it exists in both
operands.
x & y results
1000
| Bitwise OR This operator performs OR operation between
operands. Operator copiesbit if it exists in either
operand.
x | y results 1110
^ Bitwise
XOR
This operator performs XOR operation between
operands. Operatorcopies bit if it exists only in one
operand.
x ^ y results 0110
~ bitwise
inverse
This operator is a unary operator used to opposite the
bits of operand.
~ x results 0101
<< left shift This operator is used to shift the bits towards left x << 2 results
101000
<< right
shift
This operator is used to shift the bits towards right x >> 2 results
0010
>>> z = x | y
>>> print z
14 # 14 = 0000 1110
# Bitwise XOR
>>> z = x ^ y
>>> print z
6 # 6 = 0000 0110
# Bitwise inverse
>>> z = ~x
>>> print z
-11 # -11 = 1111 0101
# Left shift
>>> z = x << 2
>>> print z
40 # 40 = 0010 1000
# Right shift
>>> z = x >> 2
>>> print z
2 # 2 = 0000 0010
<DEPARTMENT OF PG MATHEMATICS> PLAN-ACT-SUCCEED
24
Example
>>> x = True
>>> y = False
>>> print (x and y)
Example
>>> x = 10
>>> y = 12
>>> z = 0
# 10 = 0000 1010
# 12 = 0000 1100
# Bitwise AND
>>> z = x & y
>>> print z
8
# 8 = 0000 1000
# Bitwise OR
Logical Operators
These operators are used to check two or more conditions. The resultant of this operator is
always a Booleanvalue. Here, x and y are two operands that store either true or false Boolean
values. Table 3.6 presents a list of logical operators. Assume x is true and y is false.
TABLE 3.6 List of Logical Operators
Operator Description Example
and logical
AND
This operator performs AND operation between
operands. When both operands are true, the resultant
become true.
x and y results
false
or logical OR This operator performs OR operation between
operands. When anyoperand is true, the resultant
becomes true.
x or y results
true
not logical
NOT
This operator is used to reverse the operand state. not x results
false
False #Output
<DEPARTMENT OF PG MATHEMATICS> PLAN-ACT-SUCCEED
25
>>> print
True
(x or y)
#Output
>>> print
False
(not x)
#Output
>>> print
True
(not y)
#Output
Membership Operators
These operators are used to check an item or an element that is part of a string, a list or a tuple. A
membership operator reduces the effort of searching an element in the list. Suppose, x stores a
value 20 and y is the list containing items 10, 20, 30, and 40. Then, x is a part of the list y because
the value 20 is in the list y. Table 3.7gives a list of membership operators.
TABLE 3.7 List of Membership Operators
Operator Description Example
in Return true, if item is in list or in sequence. Return
false, if item is not in list or in sequence.
x in y, results true
not in Return false, if item is in list or in sequence. Return
true, if item is not in list or in sequence.
x not in y, results
false
Identity Operators
These operators are used to check whether both operands are same or not. Suppose, x stores a
value 20 and y stores a value 40. Then x is yreturns falseand x not is yreturns true. Table 3.8
provides a listof identity operators
TABLE 3.8 List of Identity Operators
Operator Description Example
is Return true, if the operands are same. Return false, if
the operands are not same.
x is y, results false
not is Return false, if theoperands are same. Return true, if the
operands are not same.
x not is y, results
true
<DEPARTMENT OF PG MATHEMATICS> PLAN-ACT-SUCCEED
26
Example
>>> x = 12
>>> y = 12
>>> if ( x is y):
print “x is same as y”
else:
print “x is not same as y”
x is same as y #Output
>>> y = 10
>>> if ( x is not y):
print “x is not same as y”
else:
print “x is same as y”
x is not same as y #Output
Precedence of Operators
When an expression has two or more operators, we need to identify the correct sequence to
evaluate theseoperators. This is because the final answer changes depending on the sequence
thus chosen.
Let us look at an example of a mathematical expression:
10 + 5 / 5
When the given expression is evaluated left to right, the final answer becomes 3. However, if
the above expression is evaluated right to left, the final answer becomes 11. This shows that
changing the sequence in which the operators are evaluated in the given expression also
changes the solution. Therefore, in order to remove this problem, a level of precedence is
associated with the operators. Precedence is the condition that specifies the importance of each
operator relative to the others.
Table 3.9 to display operator precedence from lower precedence to higher:
TABLE 3.9 Operator Precedence
Operator Description
NOT, OR AND Logical operators
in , not in Membership operator
<DEPARTMENT OF PG MATHEMATICS> PLAN-ACT-SUCCEED
27
is, not is Identity operator
=, %=, /=, //=, -=, +=,
*=, **==
Assignment operators.
<>, ==, != Equality comparison operator
<=, <, >, >= Comparison operators
^, | Bitwise XOR and OR operator
& Bitwise AND operator
<<, >> Bitwise left shift and right shift
+, - Addition and subtraction
*, /, %, // Multiplication, Division, Modulus and floor division
** Exponential operator
It may happen that an expression has two operators having same precedence. In that case, we
use Associativity to evaluate the expression. Associativity is nothing but the direction in which
we evaluate the operators if they have same precedence.
Associativity
In Table 3.9 (precedence of operators) we can see that many operators are having the same
precedence. Hence, associativity decides the order in which the operators with same precedence
are executed.
There are two types of associativity. One is left-to-right and other is right-to-left. In left-to-right
associativity, the operator of same precedence are executed from the left side first and in right-to-
left associativity, the operator of same precedence are executed from the right side first. Most of
the operators in Python have left-to-right associativity. Examples for left-to-right associative
operators are multiplication,floor division, etc and ** operator is right-to-left associative.
>>
>
2
3 * 4 // 6
#Output
>>
>
0
3 * (4 // 6)
#Output
>>
>
3 ** 4 ** 2 # 3^16
Note When two operators have the same precedence, then operators are evaluated from left to right
direction
Let us now look at an example of a mathematical expression with operators having the same
precedence:
10 * 5 / 5
<DEPARTMENT OF PG MATHEMATICS> PLAN-ACT-SUCCEED
28
Example
>>> x = 12
>>> +x
12
>>> -x
-12
>>> ~x
-13
#Output
#Output
#Output
Note The invert(~) operator returns the bit-wise inversion of long integer
arguments. The bit-wise inversion of y can be computed as –(y+1). Hence, in the
above example, we get the ~(12)as -13.
In the above expression, the multiplication operator is evaluated before the division operator is
evaluated.Based on the number of operands, operators are classified into following two types:
1.Unary Operator
2.Binary Operator
Unary Operator
Unary operators are operators with only one operand. These operators are basically used to
provide sign tothe operand.
The format of the unary operator is:
Operator operand
Some unary operators are as follows:
● +
● -
● ~
●
Binary Operator
Binary operators are operators with two operands that are manipulated to get the result. They are
also usedto compare numeric values and string values.
The format of binary operator is: Operand1 Operator Operand2
Some binary operators are as follows:
**, *, /, %, +, -, <<,>>, &, | ,^,<,>,<= ,>=, == ,!= ,<>
We saw many examples of binary operators in the section above.
<DEPARTMENT OF PG MATHEMATICS> PLAN-ACT-SUCCEED
29
STATEMENT AND EXPRESSION
Statement
A statement can be thought as an instruction that can be interpreted by the Python interpreter.
In Section3.9, we came across print and assignment statements. A statement is interpreted by the
interpreter and after execution displays some result (if there is a need for displaying it). For e.g.,
print statement produces some result to display but it does not happen in case of assignment
statement.
A program can contain many statements in sequence. If there are multiple statements, the
result isdisplayed after every statement.
As we move ahead in the chapter, we will study more statements such as whilestatement, for
statement,
if statement, print statement, etc.
Let us look at an example of the assignmentstatement:
>>> message=”Hello world”
Due to the assignment operator (=), the message variable stores the Hello worldstring.Let us
look at an example of the printstatement:
>>> print 1
1 #simply prints 1
>>> x=2
>>>print x
2 #prints the value of x
Check Your Understanding
1. What are the different types of operators in Python?
Ans.
● Arithmetic Operator
● Comparison Operator
● Assignment Operator
● Logical Operator
● Bitwise Operator
● Membership Operator
● Identity operator
<DEPARTMENT OF PG MATHEMATICS> PLAN-ACT-SUCCEED
30
Example
>>> 1+1
2 # Output
Note In the given example, we assigned a value “Hello Python” to the variable
program.Now, when we type only program, we get the output ‘Hello Python.’ This
is the term wetyped when we assigned a value to the variable. When we use a print
statement with program it gives the value of the variable, i.e., the value after
removing quotes.
Expression
An expression is a combination of variables, operators, values and a reserve keyword.
Whenever you type an expression in the command line, the interpreter evaluates it and
produces the result.
Evaluation of Expression
The evaluation of an expression produces a value. In an assignment statement, an expression is
always thereon the right side.
Let us look at an example of an expression:
>>> 2+3
5 # Output
>>>program=”Hello Python”
>>>program
‘Hello Python’ # Output
>>>print program
Hello Python # Output
An expression is not always a mathematical expression in Python. A value by itself is an
expression. In above example, the “Hello Python” is an expression. The interpreter reads the
expression and displays the string written in quotes as it is.
<DEPARTMENT OF PG MATHEMATICS> PLAN-ACT-SUCCEED
31
STRING OPERATIONS
The contiguous set of characters kept within quotation marks in Python is termed string.
Either single quotes ordouble quotes can be used to represent strings. A string in Python can be a
combination of alphabets, numerals and symbols. Mathematical operations cannot be performed on
the string even if we have numeral values in it. There are many operations which can be
performed on a string such as slice operator ([]) and [:]), concatenation operator (+) and
repetition operator (*). Slicing is used to take out a subset of the string,concatenation is used
to combine two or more than two strings and repetition is used when we want to repeat
same string several times.
Let us look at an example of how a string is declared in Python.
>>>test=”Test string”
As mentioned earler, a string supports various types of operations:
Concatenation
The concatenation operation is done with the + operator in Python. Concatenation means joining
the stringsby linking the last end of the first string with the first end of the second string and so on.
Two separate stringstransform into one single string after concatenation.
Let us look at an example of concatenation:
>>>test=”Test string”
>>> “Hello” + test
‘HelloTest string’ # Output
>>>
Repetition
The repetition operation is performed on the strings in order to repeat the string several times.
It is donewith * operator.
Let us look at an example of repetition:
>>> ‘Spam’*3
SpamSpamSpam # Output
>>>
<DEPARTMENT OF PG MATHEMATICS> PLAN-ACT-SUCCEED
32
Get Particular Character
To access a single item of the string square brackets[] are used. To access the third element of the
string, thestring name is typed followed by the [2]. Remember, the index of the string starts with
0 and not 1.
>>>test=”Test string”
>>>test[3]
‘t’ # Output
>>>
Slicing
In Python, you can extract a substring by using a colon inside the square bracket [:]. The
resultant substringis a part of the long string.
>>>test=”Test string”
>>>test[1:7]# substring between index 1 to 7 (excludes 7)
‘est st’ # Output
>>>test[:3] # substring from index 0 to 3(excludes 3)
‘Tes’ # Output
>>>test[2:] # substring from index 2 to last
‘st string’ # Output
>>>
Python also provides various in-built commands or methods for string operation (Table 3.10).
These methods are used to convert the lower case letter to upper case, to determine the length of
string, etc.
TABLE 3.10 List of in-built commands
Method Description
.lower() Convert all upper case letters into lower case.
.upper() Convert all lower case letters into upper case.
.isalpha() Return true if string contain only alphabetical characters.
.isdigit() Return true if string contain only digits characters.
<DEPARTMENT OF PG MATHEMATICS> PLAN-ACT-SUCCEED
33
Check Your Understanding
1. What is slicing?
Ans. In Python, you can extract a substring by using a colon inside the square bracket
[:]. Theresultant substring is a part of the long string.
2. What are statement and expression in Python?
Ans. A statement is the instruction that can be interpreted by the Python interpreter. An
expressionis a combination of variables, operators, values and reserve keyword.
.isspace() Return true if string contain space.
.find(“string”) Return the first index of search string.
.replace(“ old”,”new”) Replace the string with other string.
.count(“character”) Return the occurrence of particular character in string.
len(“string”) Return the length of string.
Example
>>> s = “Hello Python”
>>> print s.lower()
hello python
>>> print s.upper()
HELLO PYTHON
>>> print s.find(“l”)
2
>>> print s.replace(“l”,”p”)
Heppo Python
>>> print s.count(“o”)
2
>>> print len(s)
12
#Defining a string
#Converts the string in lower case
#Converts the string in upper case
#returns the index of first ‘l’ #Replace
each “l” to “p”
#count the number of “o”
#Length of the string
>>> s = “Hello”
>>> print s.isalpha()
True
>>> print s.isdigit()
False
#String contains only alphabets
#String doesn’t contain digits
<DEPARTMENT OF PG MATHEMATICS> PLAN-ACT-SUCCEED
34
BOOLEAN EXPRESSIONS
A Boolean expression may have only one of two values: TRUEor FALSE.
The simplest Boolean expressions in Python are True and False. The following example uses the
operator
==, which compares two operands and prints true if they are equal otherwise print false:
>>> 5 == 5
True # Output
>>> 5 == 6
False # Output
>>> True
True # Output
>>> False
False # Output
CONTROL STATEMENTS
The for Loop
The Python for loop is an iterator-based for loop. It goes through the elements in any ordered
sequence list, i.e., string, lists, tuples, the keys of dictionary and other iterables. In each iteration
step, a loop variable is set to a value. The for loop in Python is a bit different from the for loop in
any other programming language you have gone through.
Note We can see in the following example that bool is the name of the class
representingPython’s Boolean expressions.
>>>type(True)
<type ‘bool’>
>>>type(False)
<type ‘bool’>
<DEPARTMENT OF PG MATHEMATICS> PLAN-ACT-SUCCEED
35
Syntax
>>>for x in y :
Block 1
else:
Block 2
# Optional
# excuted only when the loop exits normally
Example
>>>for letter in ‘Python’ :
print ‘Current Letter :’, letter
Output:
Current Letter : P
Current Letter : y
Current Letter : t
Current Letter : h
Current Letter : o
Current Letter : n
Example
>>> subjects = [“Maths”, “English”, “Physics”, “Chemistry”, “Computer”]
>>> for x in subjects:print(x)
Example
# Print first five even numbers.
>>> count = 2
>>> while True:
print count
count = count + 2
if count >= 12:
break # breaks the loop
2
4
6
8
10
# Output
In the above section, we have seen the syntax of for loop. The for loop is used to iterate over a
sequence. Here, xis used to iterate over yand when the loop exits normally then the elsepart of
the forloop executes otherwise not.
<DEPARTMENT OF PG MATHEMATICS> PLAN-ACT-SUCCEED
36
Example
>>> for x in range(7):
print(x)
else:
print(‘Else Part’)
0
1
2
3
4
5
6
Else Part
In the above example, we have printed the value from 0 to 6 by using the for loop and an else
parthaving a print statement is also been used. In this case, the for loop is ended normally then
the else part also executed but when the loop stops because of break statement then the else
part doesn’t execute.
Example
>>> range(8)
[0, 1, 2, 3, 4, 5, 6, 7]
Example
>>> range(3,9)
[3, 4, 5, 6, 7, 8]
range()Function
The range()function is a built-in function in Python that helps us to iterate over a sequence of
numbers. It produces an iterator that follows arithmetic progression.
range(8)provides a sequence of numbers 0-7. That is to say, range(n)generates a sequence of
numbersthat starts with 0and ends with (n-1).
range()function can also be passed with two arguments: beginand end.
Maths
English
Physics
Chemistry
Computer
#Output
<DEPARTMENT OF PG MATHEMATICS> PLAN-ACT-SUCCEED
37
Example
>>> range(3,40, 5)
[3, 8, 13, 18, 23, 28, 33, 38]
We provided the begin index with 3 and the end index with 9. Hence, the range function
generates a sequence iterator of numbers that starts from 3and ends at 8.
Till now, we have seen that all the numbers in the sequence have a difference of 1. We can also
change this difference if we want to. For this purpose, we have to use another parameter, step,
along with begin and end.
This range() function gives us a sequence that starts from 3and ends at 38; every number in the
list hasa difference of 5.
Example
>>> subjects = [“Maths”, “English”, “Physics”, “Chemistry”, “Computer”]
>>> for x in subjects:print(x)
>>> for index in range(len(subjects)):
print ‘Current Subject : ‘, subjects[index]
Current Subject :maths #Output
Current Subject :physics
Current Subject : chemistry
Current Subject : computer
In the above example, a list subjects is defined which has 4 elements or items in it. Now, it is
required to print all the elements in list subjects one by one with the for loop and taking help of
range() function. Now, we initialized a for loop in next statement which will iterate over the
sequence of number given by the range() function. In our example, we have used
range(len(subjects))which meansrange(4)that is because the length of the list subjectsis 4 which
is computed by the function len.
<DEPARTMENT OF PG MATHEMATICS> PLAN-ACT-SUCCEED
38
Syntax
>>> while condition :block
else: #Optional
statement
While Statement
The while statement is used when you have a piece of code and you want to repeat it ‘n’
number of times or forever. With whileloop, we have to give a conditional statement that tells
the interpreter when the loop will halt.
Here, conditionis a statement by which interpreter decides when to halt the loop and blockis
thepiece of code that we want to repeat.
Break and continue Statements
The breakand continuestatements are often useful in a whileloop as well as in a forloop. The
breakstatement exits from the loop and transfers the execution from the loop to the statement that
is immediately following the loop. The continue statement causes execution to immediately
continue at the start of the loop, it skips the execution of the remaining body part of the loop.
<DEPARTMENT OF PG MATHEMATICS> PLAN-ACT-SUCCEED
39
Example
Write a while statement that prints integers from zero to 5.
>>> count = 0
>>> while count < 6:print
count count += 1
0
1
2
3
4
5
# Output
Example
# Print first four even numbers.
>>> for i in range(1,10):
Note If the break statement in a for loop is executed then the else part of that for loop
is skipped.
Note The break and continue statements are often useful in a while statement. The
break statement exits from the loop. The continue statement causes execution to
immediately continue at the start of the loop.
if elif else Statement
The ifstatement is known as the decision-making statement in programming languages. With an if
clause,a condition is provided; if the condition is True then the block of statement written in the
if clause will be executed, otherwise not.
if i % 2 != 0:
continue
# if condition becomes true, it skips the print
part
print i
2
4
6
8
# Output
<DEPARTMENT OF PG MATHEMATICS> PLAN-ACT-SUCCEED
40
Example
>>>var = 100
if (var ==100) : print “Value of expression is 100”
Output:
Value of expression is 100
Syntax
>>>if expression :
statement1
else :
statement2
Syntax
>>>if expression1 :
statement1
elif expression2 :
statement2
elif expression3 :
statement3
else expression4 :
statement4
Check Your Understanding
1. What is a for statement?
Ans. The for statement in Python differs a bit from what you may be used to in C. In
C, for loop gives the user the ability to define both the iteration step and the
halting condition, but in Python, the for statement iterates over the items any
ordered sequence (a list or a string), in the order that they appear in the
sequence.
An else statement can be combined with an if statement. It contains the block of code that
executes if the conditional expression in the if statement resolves to 0 or FALSE value. It is an
optional statement.Please note there can be at the most one elsestatement following if.
We can check multiple expressions for TRUEwith the help of elifstatement and execute a block of
codewritten just below the elifstatement whose condition is TRUE.
Similar to else, the elifstatement is optional. However, there can be more than one elif
statementfollowing an if.
<DEPARTMENT OF PG MATHEMATICS> PLAN-ACT-SUCCEED
41
Alternative Executions
The alternative execution provides two possibilities. The condition determines which possibility
is executed. If the condition is TRUE, the first block is executed but if condition is FALSE,
another block of code is executed.
This is the second form of the if statement. The syntax looks like:
>>>if x % 2 == 0 : print ‘x is even’else
print ‘x is odd’
The condition can be either true or false. So, only one alternative will be executed. The
alternatives arecalled branches, because they are branches in the flow of execution.
Conditional Execution
In programming languages, conditional statements or conditional constructs are the statements
that are generally used with some conditions. The actions performed by these conditional
statements are entirely dependent on the value of the condition, on whether the value is TRUE or
FALSE. The condition usually uses comparisons and arithmetic expressions with variables. These
expressions are evaluated to the Boolean values True or False. The statements for the decision-
making are called conditional statements or conditional expressions.
The simplest form is the ifstatement:
>>>if x > 0 :
print “x is positive”
TIP
The Boolean expression after the if statement is called the condition. If the condition
is true, then the intended statement is executed. If the condition is not true, the
statement isnot executed.
Here’s an example of the syntax for an ifstatement:
>>>if BOOLEAN EXPRESSION:
<DEPARTMENT OF PG MATHEMATICS> PLAN-ACT-SUCCEED
42
Note The set of intended statements that follow a conditional statement or a loop
statement is called block. Indentation can be done by 'tabs' or 'spaces'. Using 4 spaces for
indentation of a block is standard. A statement block inside a compound statement is called
the body of the statement.
The intended statements that follow the conditional statements are called block. The first
unintended statement marks the end of the block. A statement block inside the compound
statement is called the body of the statement.
Syntax
The syntax of a while loop in Python programming language is as follows:
>>> while expression :
statement(s)
else: # Optional
statement # executes only when while condition becomes false
STATEMENTS
There are no bounds on the number of statements that can appear in the body of an ifstatement, but
therehas to be at least one statement. Occasionally, it is useful to have a body with no statements.
In that case, you can use the pass statement, which does nothing.
>>>if True : # This is always true
pass # so this is always executed, but it does nothing
ITERATION – while STATEMENT
A while loop statement in Python programming language is the command that repeats a piece of
code up to several times. The number of times the piece of code is executed depends on the
condition expression written with the whilestatement.
Here, statement(s) may be a single statement or a block of statements. The condition may be any
expression, and whenever the expression resembles a non-zero value, it will be treated as TRUE,
otherwise it will be treated as FALSE. The loop iterates while the condition is TRUE.
<DEPARTMENT OF PG MATHEMATICS> PLAN-ACT-SUCCEED
43
Example
>>>count = 0
while (count < 9) :
print ‘The count is :’, countcount
= count + 1
Output:
The count is : 0
The count is : 1
The count is : 2
The count is : 3
The count is : 4
The count is : 5
The count is : 6
The count is : 7
The count is : 8
Unlike other programming languages, whileloop in Python makes use of an optional elseclause
whichis executed when the condition of whilestatement fails.
When the condition becomes false, program control passes to the line immediately following the
loop.
<DEPARTMENT OF PG MATHEMATICS> PLAN-ACT-SUCCEED
44
Flow Diagram
Figure 3.8 represents a flow diagram.
While has an optional‘else’
block
Figure 3.8 Working of a While Loop
The block here, consisting of the print and increment statements, is executed repeatedly until
count is no longer less than 9. With each iteration, the current value of the index count is
displayed and then increased by 1.
INPUT FROM KEYBOARD
In a programming language, the input from keyboard by user plays the most important role in
executing a program. There is hardly any program which executes without some input. The input
in many programs is prompted by the user and the user uses the keyboard in order to provide
input for the program to execute.
Python programming language also provides the facility to user to provide input from
keyboard. That is done by two ways in Python.
Note If there is a continue statement inside a while loop or a for loop then also the else
part of that loop is executed.
while expression:
statements(s)
condition
If condition
is ture If condition
is false
conditional code
<DEPARTMENT OF PG MATHEMATICS> PLAN-ACT-SUCCEED
45
Example
>>> name = input(“What is your Name?”)
>>> print (“Hello “ + name + “!”)
What is your Name? ‘John’
Hello John!
#Output
>>> age = input(“Enter your age? “)
>>> print age
Enter your age? 32
32
#Output
>>> hobbies = input(“What are your hobbies? “)
>>> print hobby
What are your hobbies? [‘playing’, ‘travelling’] #Output
[‘playing’, ‘travelling’]
>>> type(name)
<type ‘str’>
>>> type(age)
input()Function
The first function for prompting the input from user in Python is through input() function. input()
function has an optional parameter, which is the prompt string. When the input() function is
called, in order to take input from the user then the execution of program halts and waits for the
user to provide an input. The input is given by the user through keyboard and it is ended by the
return key.
input()function interprets the input provided by the user, i.e. if user provides an integer value as
input then the input function will return this integer value. On the other hand, if the user has input
a String, then the function will return a string.
<type ‘int’>
>>> type(hobbies)
<type ‘list’>
<DEPARTMENT OF PG MATHEMATICS> PLAN-ACT-SUCCEED
46
Example
# No casting
>>> age = raw_input(“What is Your Age? “)
What is Your Age? 46
>>> type(age)
<type ‘str’> #Input is stored as string
#Using casting function to convert input to integer
>>> age = int(raw_input(“What is your age? “))
What is your age? 46
>>> type(age)
<type ‘int’> #Input is stored as integer
Check Your Understanding
1. What is Alternative Execution?
Ans. The alternative execution provides two possibilities and the condition determines which one is
to be executed. This is the second form of the if statement.
2. What is the syntax for ifelse and elif statements?
Ans. >>> if expression1 :
statement(s)
elif expression2 :
statement(s)
elif expression3 :
statement(s)
else expression4 :
statement(s)
raw_input() Function
raw_input() is somewhat different from the input() function provided by Python programming
language. raw_input() also takes the input from the user but it does not interpret the input and
also it returns the input of the user without doing any changes, i.e. raw. Afterwards, we can
change this raw input into any data type which is needed for our program. In order to take input
from the user in desired data type, we can use the casting function with raw_input().
This is the reason, why raw_input()is most preferred over the input()function.
● In Python, forstatement iterates over the items in a sequence (a list or a string) in the
order in which they appear in the sequence.
● Syntax for whilestatement in Python is:
<DEPARTMENT OF PG MATHEMATICS> PLAN-ACT-SUCCEED
47
>>> while condition :Block
SELF-ASSESSMENT
1. Fill in the Blanks Questions – minimum ten questions
MultipleChoiceQuestions
1. Which of the following is not a data type?
a. String b. Numeric
c. Array d. Tuples
2. Which character is used for commenting in Python?
a. # b. !
c. @ d. *
3. What is the output of [‘name!’] * 2?
a. [‘name!’] * 2 b. [‘name’!, ‘name’!]
c. [‘name!’, ‘name!’] d. [‘name’!] * 2
4. Which is not a reserved keyword in Python?
a. Insert b. Pass
c. Class d. Lambda
5. What is the output of >>> 4+?
a. 4+ b. 4
c. 5 d. Invalid syntax
6. What will be the output of str[0:4] if str=”Hello”?
a. ‘Hello’ b. ‘H’
c. ‘Hel’ d. ‘Hell’
7. Which of the following is the floor division operator?
a. / b. %
c. // d. 
8. Which of the following is used to find the first index of search string?
a. .find(“string”) b. .search(“string”)
c. (“string”).find d. (“string”).search
9. Which of the following is used to access single character of string?
a. [:] b. ()
c. [.] d. []
10. What is the order of precedence in Python?
i. Addition ii. Multiplication
iii. Division iv. Subtraction
v. Exponential vi. Parenthesis
a. ii, i, iii, iv, vi, v b. vi, v, iii, ii, i, iv
<DEPARTMENT OF PG MATHEMATICS> PLAN-ACT-SUCCEED
48
c. vi, v, ii, i, iii, iv d. ii, vi, iii, i, iv, v
11. Which of the following will be printed?
x =4.5
y =2
print x//y
a. 2.0 b. 2.25
c. .25 d. 0.5
12. What gets printed?
Nums=set([1,1,2,3,3,3,4])
Print len(nums)
a. 2 b. 4
c. 5 d. 7
2. Match the Following – minimum five options
3. Short Answer Questions – minimum five
Write a Program to find the square root of a number.
Solution.
>>> x = int(input(‘Enter an integer number: ‘))
>>> sqrt_x = x ** 0.5
>>> print (sqrt_x)
Enter an integer number: 64
8.0 #Output
1. Write a program to find the area of a Rectangle.
Solution.
>>> l = float(input(‘Enter the length of the Rectangle: ‘))
>>> b = float(input(‘Enter the breadth of the Rectangle: ‘))
>>> area = l * b
>>> print (area)
Enter the length of the Rectangle: 14Enter
the breadth of the Rectangle: 7
98.0 #Output
2. Write a program to swap the values of two variables.
Solution.
<DEPARTMENT OF PG MATHEMATICS> PLAN-ACT-SUCCEED
49
>>> num1 = input(‘Enter the value of num1: ‘)
>>> num2 = input(‘Enter the value of num2: ‘)
>>> temp = num1
>>> num1 = num2
>>> num2 = temp
>>> print “num1 = “, num1
>>> print “num2 = “, num2
Enter the value of num1: 4Enter
the value of num2: 7
num1 = 7 #Output
num2 = 4
3. Write a program to convert kilogram into pound.
Solution.
>>> kg = float(input(‘Enter the value in kilogram: ‘))
>>> kg_to_pound = 2.20462
>>> pound = kg * kg_to_pound
>>> print “%0.3f kg = %0.3f pounds” %(kg,pound)
Enter the value in kilogram: 60
60.000 kg = 132.277 pounds #Output
4. Write a program to find whether a number is even or odd.
Solution.
>>> number = int(input(“Enter an integer number: “))
>>> if (number % 2) == 0: print
“Number is even”
else:
print “Number is odd”
Enter an integer number: 6
Number is even #Output
5. Write a program to check the largest among the given three numbers.
Solution.
>>> x = int(input(“Enter the first number: “))
<DEPARTMENT OF PG MATHEMATICS> PLAN-ACT-SUCCEED
50
Enter the first number: 14
>>> y = int(input(“Enter the second number: “))
Enter the second number: 21
>>> z = int(input(“Enter the third number: “))
Enter the third number: 10
>>> if (x > y) and (x > z):l =
x
elif (y > x) and (y > z):l =
y
else:
l = z
>>> print “The largest among the three is “,l
The largest among the three is 21 #Output
6. Write a Python program to check if the input year is a leap year or not.
Solution.
# Python program to check if the input year is a leap year or not
>>> year = int(input(“Enter year: “))
>>> if(year % 4)==0:if(year%100)==0:
if(year%400)==0:
print (year, ‘ is leap year’)
else:
else:
print (year, ‘ is not leap year’)
print (year, ‘ is leap year’)
else:
print (year, ‘ is leap year’)
Output:
Enter a year: 20162016
is leap year
Output:
<DEPARTMENT OF PG MATHEMATICS> PLAN-ACT-SUCCEED
51
Enter a year: 19851985
not leap year
4. Long Answer Questions – minimum two
5. Case Study Questions – minimum one, where Possible
6. Problem Solving Questions – minimum one, where Possible
7. Assignment – minimum one
<DEPARTMENT OF PG MATHEMATICS> PLAN-ACT-SUCCEED
52
SUMMARY (in bullet points)
● Python is a high-level general-purpose programming language. The code written in Python is
automaticallycompiled to byte code and executed.
● The printstatement is used to display the output screen.
● In Python, the Hash character (#) is used for commenting. Codes or texts that come after the
hash character are not considered as a part of the program.
● In Python, an identifier (name) must begin with a letter or underscore and can include
any number ofletters, digits, or underscore.
● Writing the name of a variable is called declaring a variable whereas assigning a value to
a variable iscalled initialising a variable.
● Python supports six data types which are as follows:
1. Numeric
2. String
3. List
4. Tuple
5. Dictionary
6. Boolean
● The main differences between lists and tuples are that lists are enclosed in brackets ([]) and
their elements and size can be changed, while tuples are enclosed in parentheses(()) and
cannot be updated. Tuples can be thought of as read-only lists.
● The items cannot be modified in tuple, but can be modified in the list.
● APython dictionary works on the basis of key-value pairs. Key used in dictionary can be an
integer valueor a string value.
● On the basis of functionality, operators in Python are categorised into following seven types:
1. Arithmetic operator
2. Comparison operator
3. Assignment operator
4. Logical operator
5. Bitwise operator
6. Membership operator
7. Identity operator
● A statement is a unit of code that the Python interpreter can execute.
● An expression is a combination of variables, operators, values and reserve keyword.
● A string is a combination of characters (alphabets, digits and symbols). A string value is
always enclosedwithin double or single quotes.
<DEPARTMENT OF PG MATHEMATICS> PLAN-ACT-SUCCEED
53
● The concatenation operation is done with the + operator. Concatenation means joining the
strings togetherby linking them end to end.
● The repetition operation is performed on the strings in order to repeat the string several
times.
● In Python, you can extract substring by using the colon inside the square bracket [:].
The resultant substring is a part of the long string.
KEYWORDS
✓ COMMENT: The part of the program not executed by the interpreter. It is used by other
persons tounderstand the program thoroughly.
✓ CONCATENATION: The process of joining strings end-to-end.
✓ DICTIONARY: A mapping of keys to their corresponding values.
✓ FLOATING POINT: A type of numeral that has a fractional part.
✓ HIGH-LEVEL LANGUAGE: A programming language such as Python that is designed to
be easy forhumans to read and write.
✓ INDEX: An integer value that represents an element in a sequence.
✓ INTEGER: A type of numeral that represents whole numbers including negative numbers.
✓ INTERACTIVE MODE: A way of using Python language where we type command and
expressions.
✓ INTERPRET: To execute a program in a high-level language by executing it one line at a
time.
✓ ITEM: An element or a value in a series.
✓ ITERATION: The repetition of a set of statements or a piece of code.
✓ KEYWORD: A word that is reserved in a programming language for a specific purpose. We
cannot usekeywords such as if and else as variable names.
✓ OPERAND: The value on which an operator operates.
✓ SLICE: A subset or a part of a string.
TEXT BOOKS(with indicative page numbers)
E Balagurusamy, Introduction To Computing And Problem Solving Using Python, McGraw Hill
Education (India) Private Limited, P-24, Green Park Extension, New Delhi 110 016, 2016.
UNIT I : Chapter 3 : Sections 3.1 – 3.15
UNIT II : Chapter 4 : Section 4.1 – 4.10
UNIT III : Chapter 5 : Section 5.1, 5.2
<DEPARTMENT OF PG MATHEMATICS> PLAN-ACT-SUCCEED
54
UNIT IV : Chapter 6 : Sections 6.1, 6.2
UNIT V: Chapter 7 : Section 7.1 – 7.5
REFERENCE BOOKS (with indicative page numbers)
1. Kenneth A. Lambert, Martin Osborne, Fundamentals of Python, Cengage, Learning India
Pvt Ltd, 2020
2. Mark Summerfield, Programming in Python 3 – Developer’s Library, Pearson Education,
Delhi 110 092, 2009
3. Robert Sedgewick, Kevin Wayne Robert Dondero, Introduction to Programming in
Python – An Inderdisciplinary Approach, , Pearson Education, Chennai 600 115, 2018
E-RESOURCES(Websites, YouTube, etc)
http://www.pitt.edu/~peterb/0012-161/syllabus.html

PYTHON-Unit-I-Notes for python learnerss

  • 1.
    <DEPARTMENT OF PGMATHEMATICS> PLAN-ACT-SUCCEED 1 UNIT-I NOTES < Introduction to Python Programming – 22BMA5EA0> UNIT 1 (Copy-Paste from the Syllabus) Introduction to Python: Introduction - Python Overview - Getting Started with Python – Comments - Python Identifiers - Reserved Keywords – Variables - Standard Data Types – Operators - Statement and Expression - String Operations - Boolean Expressions - Control Statements - Iteration – while Statement - Input from Keyboard TOPICS(Should match with the Teaching Plan in CAMU) NO. TOPICS 1 Introduction to Python: Introduction - Python Overview - Getting Started with Python – Comments - Python Identifiers - Reserved Keywords 2 Variables - Standard Data Types – Operators - Statement and Expression - String Operations 3 Boolean Expressions - Control Statements - Iteration – while Statement - Input from Keyboard 4 Summary of Unit – I LEARNING OUTCOMES NO. LEARNING OUTCOMES 1 To start with the key features of the Python programming language, comments, identifiers and keywords 2 To describe the variables, data types, various operators, statements , expressions, and handling string operations 3 Identify the structure and syntax of Boolean expressions, control statements like if statements, while statement, and getting input through keyboard 4 Summary of Unit – I
  • 2.
    <DEPARTMENT OF PGMATHEMATICS> PLAN-ACT-SUCCEED 2 INTRODUCTION Python is a high-level, interpreted, general-purpose, dynamic programming language. Python was conceived in the late 1980s and its usage began from December 1989. It is a widely used programming language. Python possesses a property of code termed reusability. The syntax of Python programs can express concepts in fewer lines as compared to programs in C, C++ and JAVA. Python can be used in multiple programming styles, including Object-Oriented, Functional programming Procedural Programming and Imperative styles. It also supports automatic memory management and has a large standard library and innumerous set of third party libraries. Python can be used on almost every operating system because its interpreter is available for many operating systems. Python is free and open-source software. Open-source software is a kind of computer software in which the source code of the software is made public, i.e., the copyright holder gives rights to everyone to read, change and distribute the code for any purpose. It generally has a community-based development. DETAILED NOTES INTRODUCTION PYTHON OVERVIEW Python is a high-level general-purpose programming language. Some of its key features are as follows: ● The code written in Python is automatically compiled to byte code and executed. ● Python can be used as a scripting language, as a language for implementing web applications, etc. ● Extending Python with C or C++ can help in the performance of intensive tasks where speed ofexecution is a key criterion. ● Python supports many features such as nested code blocks, functions, classes, modules and packages. ● Python makes use of an object-oriented programming approach. Python has several additional features which are as follows: ● It has many built-in data types: strings, lists, tuples, dictionaries, etc. ● It supports many control statements such as if, if-else, if-elif-else, while, iterativefor, etc.
  • 3.
    <DEPARTMENT OF PGMATHEMATICS> PLAN-ACT-SUCCEED 3 Note Python 2.7.x version of python interpreter is being discussed throughout this book. Install Python 2.7.x for better results. Many Examples listed in this book may or may not work under Python 3.x. ● It allows for easier programming with the use of functions, classes, modules and packages. GETTING STARTED WITH PYTHON There are three different ways of starting Python: 1. Running a script written in Python 2. Using a Graphical user interface (GUI) from an Integrated Development Environment (IDE) 3. Employing an interactive approach The first approach will require a text editor. We will have to create our scripts and then execute them using the text editor. The second approach will require a GUI application, one that comes with the Python installer itself. The third interactive approach is the one we will be using in this book. Python provides us a command line interpreter that we will utilise for this approach. Now, try to interact with the interpreter by entering a simple expression, 8 + 9, on the console. After entering the expression, press the Enter key to get the result. >>> 8+9 17 # Output >>> The given example shows how Python can also work as a simple calculator.Now, type the following text at the Python prompts and press Enter. >>> print “Hello, Python!” This produces the following result: Hello, Python! # Output Now, let us try some more examples. >>> Hello
  • 4.
    <DEPARTMENT OF PGMATHEMATICS> PLAN-ACT-SUCCEED 4 Note The print statement is used to display output to the screen. Those of you who are familiar with C know that the printf() function produces screen output. Many shell script languages use the echo command for program output. Check Your Understanding 1. What is Python? Ans. Python is a high-level, interpreted, interactive and object-oriented scripting language. It is a highly readable language. Unlike other programming languages, Python provides an interactive mode similar to that of a calculator. After writing Hello, when you hit the Enter key, an error message will be displayed. This is because Python does not have any Hellocommand and its interpreter is unable to identify the command. >>> Hello Traceback (most recent call last): # Output File “<pyshell#0>”, line 1, in <module>Hello NameError: name ‘hello’ is not defined However, if you want to display a message on the console, you will need to keep your message within quotes. This tells the interpreter that the text entered is not a command. Therefore, the interpreter simply echoes the text. >>> ‘Hello’ ‘Hello’ # Output TIP The print statement, paired with the string format operator (%), behaves even more like C’s printf() function.
  • 5.
    <DEPARTMENT OF PGMATHEMATICS> PLAN-ACT-SUCCEED 5 Check Your Understanding 1. What are comments? Ans. Comments are annotations made by the programmer. These help other programmers inunderstanding the code. 2. Which character is used for commenting in Python? Ans. Hash mark (#) is used for commenting in Python. COMMENTS Just like other programming languages, Python allows you to add comments in the code. Comments are used by the programmer to explain the piece of code to others as well as to himself in a simple language. Every programming language makes use of some special character for commenting, so does Python. Python uses the hash character (#) for comments. Putting # before a text ensures that the text will not be parsed by the interpreter. Comments do not affect the programming part and the Python interpreter does not display any error message for comments. Comments show up as it is in the programming. It is a good practice to use comments for program documentation in your program so that it becomes easier for other programmers to maintain or enhance the program when required. Now, take a look at some examples of comments used in Python. Commenting without the use of Hash mark (#) >>> 8+9 addition SyntaxError: invalid syntax # Output >>> In the above example, ‘addition’ is written without the Hash mark. As a result, the interpreter accepts the word ‘addition’ as part of programming. Since ‘addition’ is not a command in Python, an error message is displayed. Commenting using Hash mark (#) >>> 8+9 #addition 17 # Output >>> Now, in this example, ‘addition’ is written with a Hash mark. Hence, the interpreter understands it as a comment and does not display any error message.
  • 6.
    <DEPARTMENT OF PGMATHEMATICS> PLAN-ACT-SUCCEED 6 PYTHON IDENTIFIERS A Python identifier is the name given to a variable, function, class, module or other object. An identifier canbegin with an alphabet (A – Z or a – z), or an underscore (_) and can include any number of letters, digits,or underscores. Spaces are not allowed. Python will not accept @, $ and % as identifiers. Furthermore, Python is a case-sensitive language. Thus, Hello and hello both are different identifiers. In Python, a class name will always start with a capital letter. Table 3.1 provides examples of valid and invalid names for creating identifiers. TABLE 3.1 Examples of Valid and Invalid Names for Creating Identifiers Examples of Identifiers Valid Invalid MyName My Name (Space is not allowed) My_Name 3dfig (cannot start with a digit) Your_Name Your#Name (Only alphabetic character, Underscore ( _ ) and numeric are allowed RESERVED KEYWORDS Just like other programming languages, Python has a list of reserved words known as keywords. Every keyword has a specific purpose and use. In the upcoming chapters, we will look into the use of these keywords in programming. A list of reserved keywords in Python: and del from None True as elif global nonlocal try assert else if not while break except import or with class False in pass yield continue finally is raise def for lambda return VARIABLES Declaring a Variable A variable holds a value that may change. The process of writing the variable name is called Declaring the variable. In Python, variables do not need to be declared explicitly in order to reserve memory spaces as in other programming languages like C, Java, etc. When we initialize the variable in Python, Python Interpreterautomatically does the declaration process.
  • 7.
    <DEPARTMENT OF PGMATHEMATICS> PLAN-ACT-SUCCEED 7 Year name Albert 2016 Initializing a Variable The general format of assignment statement is as follows: Variable = expression The equal sign (=) is known as Assignment operator. An expression is any value, text or arithmetic expression, whereas variable is the name of the variable. The value of the expression will be stored in the variable. Let us now look at an example of initialising a variable: >>>year=2016 >>> name=’Albert’ The two given statements reserve two memory spaces with variable names yearand name.2016 and Albert, are stored respectively, in these memory spaces as shown in Fig. 3.7. Memory Figure 3.7 TIP Whenever you want to display the value of the variables, simply type these variable nameson console. Let us now look at an example of a variable displaying its value: >>> year 2016 # Output >>> name ‘Albert’ # Output >>>
  • 8.
    <DEPARTMENT OF PGMATHEMATICS> PLAN-ACT-SUCCEED 8 Note You can also assign one variable value into another variable. Assign the value of name1 variable into name2 variable. Let us now look at an example of assigning one variable value into another: >>> name1=’Albert’ >>> name2=name1 >>> name2 ‘Albert’ # Output >>> Whenever two values are successively assigned to a variable, the interpreter will forget the previous valueassigned to it and store the latest value in the variable memory space. >>> year=2016 >>> year=2017 >>> year 2017 # Output >>> In the given example, we first assigned 2016 to the variable year and then assigned 2017 to the same variable. The interpreter will forget the value 2016 and will display 2017as the value of year. We can also assign different types of values to the same variable. For example, we can assign a text valuewhere there previously was a numeric value. Even in such a case however, only the last assigned value remains. Let us now look at an example of assigning different types of values to the same variable: >>> amount=50 >>> amount 50 # Output >>> amount=’Fifty’
  • 9.
    <DEPARTMENT OF PGMATHEMATICS> PLAN-ACT-SUCCEED 9 >>> amount ‘Fifty’ # Output >>> STANDARD DATA TYPES The data stored in the memory can be of many types. For example, a person’s name is stored as an alphabeticvalue and his address is stored as an alphanumeric value. Sometimes, we also need to store answer in terms of only ‘yes’ or ‘no’, i.e., true or false. This type of data is known as Boolean data. Python has six basic data types which are as follows: 1. Numeric 2. String 3. List 4. Tuple 5. Dictionary 6. Boolean Numeric Numeric data can be broadly divided into integers and real numbers (i.e., fractional numbers). Integers can themselves be positive or negative. Unlike many other programming languages, Python does not have any upper bound on the size of integers. The real numbers or fractional numbers are called floating point numbers in programming languages. Such floating point numbers contain a decimal and a fractional part. Let us now look at an example that has an integer as well as a real number: >>> num1=2 # integer number >>>num2=2.5 # real number (float) >>>num1 2 # Output >>>num2 2.5 # Output >>>
  • 10.
    <DEPARTMENT OF PGMATHEMATICS> PLAN-ACT-SUCCEED 10 Check Your Understanding 1. What are data types? Ans. The data you have to manipulate can be in different forms. For example, the name of a personis in string form while his age is in numeric form. Note In all the earlier versions of Python 3, slash (/) operator worked differently. When both numerator and denominator are integers, then the result will be an integer. The slash operator removes the fraction part. Let us look at an example of the division operator in all the earlier versions of Python 3: >>> 5/2 2 # Output >>> The result becomes a floating number when either the numerator or the denominator is a floating number. When both the numerator and the denominator are floating numbers, the result is again a floating number. Let us look at an example of the division operator in all the earlier versions of Python 3: >>> 5.0/2 2.5 # Output >>> This operator has been modified in Python 3 and in all the versions after Python 3. The division operatorprovides accurate results even when both the numerator and the denominator are integers. Here is an example of the division operator that is used in all the versions after Python 3: >>> 5/2 2.5 # Output >>>
  • 11.
    <DEPARTMENT OF PGMATHEMATICS> PLAN-ACT-SUCCEED 11 Syntax >>> sample_string[start : end <:step>] #step is optional String Besides numbers, strings are another important data type. Single quotes or double quotes are used to represent strings. A string in Python can be a series or a sequence of alphabets, numerals and special characters. Similar to C, the first character of a string has an index 0. There are many operations that can be performed on a string. There are several operators such as slice operator ([]) and [:]), concatenation operator (+), repetition operator (*), etc. Slicing is used to take out a subset of the string, concatenation is used to combine two or more than two strings and repetition is used torepeat the same string several times. Here is an example of string data: >>> sample_string =”Hello” # store string value >>> sample_string # display string value ‘Hello’ # Output >>> sample_string + “World” # use of + operator ‘HelloWorld’ # Output >>> sample_string * 3 # use of * operator ‘HelloHelloHello’ # Output Python also provides slice operators ([] and [:]) to extract substring from the string. In Python, the indexing of the characters starts from 0; therefore, the index value of the first character is 0. Example >>>sample_string=”Hello” >>>sample_string[1] ‘e’ >>>sample_string[0:2] ‘He’ # display 1st index element. # Output # display 0 to 1st index elements # Output
  • 12.
    <DEPARTMENT OF PGMATHEMATICS> PLAN-ACT-SUCCEED 12 Example >>> sample_string = "HelloWorld" >>> sample_string[1:8:2] # display all the alternate charactors between index 1 to 8. ie, 1,3,5,7 'elWr' # Output List List is the most used data type in Python. A list can contain the same type of items. Alternatively, a list can also contain different types of items. A list is an ordered and indexable sequence. To declare a list in Python, we need to separate the items using commas and enclose them within square brackets([]). The list is somewhat similar to the array in C language. However, an array can contain only the same type of items while a list can contain different types of items. Similar to the string data type, the list also has plus (+), asterisk (*) and slicing [:] operators for concatenation, repetition and sub-list, respectively. Let us look at an example of the List data type: >>>first=[1,”two”,3.0,”four”] # 1st list >>>second=[“five”, 6] # 2nd list >>>first # display 1st list [1, ‘two’, 3.0, ‘four’] # Output >>>first+second # concatenate 1st and 2nd list [1, ‘two’, 3.0, ‘four’, ‘five’, 6]# Output >>>second * 3 # repeat 2nd list [‘five’, 6, ‘five’, 6, ‘five’, 6] # Output >>>first[0:2] # display sublist [1, ‘two’] # Output >>>
  • 13.
    <DEPARTMENT OF PGMATHEMATICS> PLAN-ACT-SUCCEED 13 Tuple Similar to a list, a tuple is also used to store sequence of items. Like a list, a tuple consists of items separatedby commas. However, tuples are enclosed within parentheses rather than within square brackets. Let us look at an example of the tuple data type: >>>third=(7, “eight”,9, 10.0) >>>third (7, ‘eight’, 9, 10.0) # Output Lists and tuples have the following differences:  In lists, items are enclosed within square brackets [], whereas in tuples, items are enclosed withinparentheses ().  Lists are mutable whereas Tuples are immutable. Tuples are read only lists. Once the items are stored,the tuple cannot be modified. Let us look at an example of list and tuple data type: >>>first[0]=”one” >>>third[0]=”seven” Traceback (most recent call last): # Output File “<pyshell#15>”, line 1, in <module> third[0]=”seven” TypeError: ‘tuple’ object does not support item assignment TIP The items cannot be modified in a tuple but the same is not the case with a list. Dictionary It is the same as the hash table type. The order of elements in a dictionary is undefined. But, we can iterateover the following: 1. The keys 2. The values 3. The items (key-value pairs) in a dictionary
  • 14.
    <DEPARTMENT OF PGMATHEMATICS> PLAN-ACT-SUCCEED 14 A Python dictionary is an unordered collection of key-value pairs. When we have the large amount of data, the dictionary data type is used. Keys and values can be of any type in a dictionary. Items in dictionaryare enclosed in the curly-braces{} and separated by the comma (,). A colon (:) is used to separate key from value. A key inside the square bracket [ ] is used for accessing the dictionary items. Example of dictionary: >>> dict1 = {1:"first line", "second":2} # declare dictionary >>> dict1[3] = "third line" # add new item >>> dict1 # display dictionary {1: 'first line', 'second': 2, 3: 'third line'} #Output >>> dict1.keys() # display dictionary keys [1, 'second', 3] # Output >>> dict1.values() # display dictionary values ['first line', 2, 'third line'] # Output Boolean In a programming language, mostly data is stored in the form of alphanumeric but sometimes we need to store the data in the form of ‘Yes’ or ‘No’. In terms of programming language, Yes is similar to True and No is similar to False. This True and False data is known as Boolean Data and the data types which stores this Boolean data areknown as Boolean Data Types. Example >>> a = True >>> type(a) <type ‘bool’> >>> x = False >>> type(x) <type ‘bool’>
  • 15.
    <DEPARTMENT OF PGMATHEMATICS> PLAN-ACT-SUCCEED 15 Sets The lists and dictionaries in Python are known as sequence or order collection of data. However, in Python we also have one data type which is an unordered collection of data known as Set. A Set does not contain any duplicate values or elements. Union, Intersection, Difference and Symmetric Difference are some operations which are performed on sets. Union: Union operation performed on two sets returns all the elements from both the sets. It is performedby using & operator. Intersection: Intersection operation performed on two sets returns all the element which are common or in both the sets. It is performed by using | operator. Difference: Difference operation performed on two sets set1 and set2 returns the elements which are presenton set1 but not in set2. It is performed by using – operator. Symmetric Difference: Symmetric Difference operation performed on two sets returns the element which are present in either set1 or set2 but not in both. It is performed by using ^ operator. # Defining sets >>> set1 = set([1, 2, 4, 1, 2, 8, 5, 4]) >>> set2 = set([1, 9, 3, 2, 5]) type()Function type() function in Python programming language is a built-in function which returns the datatype of any arbitrary object. The object is passed as an argument to the type() function. Type() function can take anything as an argument and returns its datatype, such as integers, strings, dictionaries, lists, classes, modules, tuples,functions, etc. >>> print union set([1, 2, 3, 4, 5, 8, 9]) #Output >>> difference = set1 - set2 >>> print difference set([8, 4]) # Difference of set1 and set2 #Output >>> symm_diff = set1 ^ set2 # Symmetric difference of set1 and set2 >>> print symm_diff set([3, 4, 8, 9]) #Output
  • 16.
    <DEPARTMENT OF PGMATHEMATICS> PLAN-ACT-SUCCEED 16 Example >>> x = 10 >>> type(x) <type ‘int’> #Output >>> type(‘hello’) <type ‘str’> #Output >>> import os >>> type (os) <type ‘module’> #Output >>> tup = (1,2,3) >>> type(tup) <type ‘tuple’> #Output >>> li = [1,2,3] >>> type(li) <type ‘list’> #Output Check Your Understanding 1. What is a list? Ans. A list is a dynamic array or sequence that is ordered, indexable and mutable. It is one of the most versatile compound data types of Python. A list is used to store multiple items separated by commas within square brackets []. 2. What is the output of print list[2]when list = [‘abcd’, 2.23, ‘john’]? Ans. john 3. What is the main difference between a list and a tuple? Ans. In a list, items are enclosed within square brackets; tuple is a sequence of items separated by comma and enclosed in parentheses.
  • 17.
    <DEPARTMENT OF PGMATHEMATICS> PLAN-ACT-SUCCEED 17 Note Items separated by ‘comma’ is the signature of tuple not parenthesis OPERATORS Operators are constructs used to modify the values of operands. Consider the following expression: 3 + 4 = 7 In the above expression, 3 and 4 are the operands whereas + is operator. Based on functionality, operators are categories into following seven types: 1. Arithmetic operator 2. Comparison operator 3. Assignment operator 4. Logical operator 5. Bitwise operator 6. Membership operator 7. Identity operator Arithmetic Operators These operators are used to perform arithmetic operations such as addition, subtraction, multiplication anddivision (Table 3.2). TABLE 3.2 List of Arithmetic Operators Operator Description Example + Addition operator to add two operands. 10+20=30 – Subtraction operator to subtract two operands. 10–20=–10 * Multiplication operator to multiply two operands. 10*20=200 / Division operator to divide left hand operator by right hand Operator. 5/2=2.5 ** Exponential operator to calculate power. 5**2=25 % Modulus operator to find remainder. 5%2=1 // Floor division operator to find the quotient and remove the fractional part. 5//2=2
  • 18.
    <DEPARTMENT OF PGMATHEMATICS> PLAN-ACT-SUCCEED 18 Comparison Operators These operators are used to compare values. Comparison operators are also called relational operators. The result of these operators is always a Boolean value, that is, either true or false. Table 3.3 provides a list of comparison operators. Example >>> x = 10 >>> y = 12 >>> z = 0 >>> z = x + y >>> print z 22 #Ouput >>> z = x - y >>> print z -2 #Ouput >>> z = x * y >>> print z 120 #Ouput >>> z = x / y >>> print z 0 #Ouput >>> z = x % y >>> print z 10 #Ouput >>> z = x ** y >>> print z 1000000000000 #Ouput >>> z = x // y >>> print z 0 #Ouput
  • 19.
    <DEPARTMENT OF PGMATHEMATICS> PLAN-ACT-SUCCEED 19 TABLE 3.3 List of Comparison Operators Operator Description Example == Operator to check whether two operands are equal. 10 == 20, false != or <> Operator to check whether two operands are not equal. 10 !=20, true > Operator to check whether first operand is greater than second operand. 10 > 20, false < Operator to check whether first operand is smaller than second operand. 10 < 20, true >= Operator to check whether first operand is greater than or equal to second operand. 10 >= 20, false <= Operator to check whether first operand is smaller than or equal to second operand. 10 <= 20, true Example >>> x = 10 >>> y = 12 >>> z = 0 >>> if (x == y): print “x is equal to y” else: print “x is not equal to y” x is not equal to y #Output >>> if (x != y): print “x is not equal to y” else: print “x is equal to y” x is not equal to y #Output >>> if (x <> y):
  • 20.
    <DEPARTMENT OF PGMATHEMATICS> PLAN-ACT-SUCCEED 20 print “x is not equal to y” else: print “x is equal to y” x is not equal to y #Output >>> if (x < y): print “x is less than y” else: print “x is not less than y” x is less than y #Output >>> if (x > y): print “x is greater than y” else: print “x is not greater than y” x is not greater than y #Output >>> if (x <= y): print “x is either equal to or less than y” else: print “x is neither equal to nor less than y” x is either equal to or less than y #Output >>> if (x >= y):
  • 21.
    <DEPARTMENT OF PGMATHEMATICS> PLAN-ACT-SUCCEED 21 Assignment Operators This operator is used to store right side operand in the left side operand. Table 3.4 provides a list of assignment operators. TABLE 3.4 List of Assignment Operators Operat or Description Example = Store right side operand in left side operand. a=b+c += Add right side operand to left side operand and store the result in left side operand. a+=b or a=a+b – = Subtract right side operand from left side operand and store the result in left side operand. a–=b or a=a–b * = Multiply right side operand with left side operand and store the result in left side operand. a*=b or a=a*b / = Divide left side operand by right side operand and store the result in left side operand. a/b or a=a/b % = Find the modulus and store the remainder in left side operand. a%=b or a=a%b ** = Find the exponential and store the result in left side operand. a**=b or a=a**b // = Find the floor division and store the result in left side operand. a//=b or a=a// b Example >>> x = 10 >>> y = 12 >>> y += x >>> print y 22 print “x is either equal to or greater than y” else: print “x is neither equal to nor greater than y” x is neither equal to nor greater than y #Output
  • 22.
    <DEPARTMENT OF PGMATHEMATICS> PLAN-ACT-SUCCEED 22 Example >>> x = 10 >>> y = 12 >>> y += x >>> print y 22 #Output >>> y *= x >>> print y 220 #Output >>> y /= x >>> print y 22 #Output Bitwise Operators These operators perform bit level operation on operands. Let us take two operands x = 10 and y = 12. Inbinary format this can be written as x = 1010 and y = 1100. Table 3.5 presents a list of bitwise operators. >>> y %= x >>> print y 2 #Output >>> y **= x >>> print y 1024 #Output >>> y //= x >>> print y 102 #Output
  • 23.
    <DEPARTMENT OF PGMATHEMATICS> PLAN-ACT-SUCCEED 23 TABLE 3.5 List of Bitwise Operators Operator Description Example & Bitwise AND This operator performs AND operation between operands. Operatorcopies bit if it exists in both operands. x & y results 1000 | Bitwise OR This operator performs OR operation between operands. Operator copiesbit if it exists in either operand. x | y results 1110 ^ Bitwise XOR This operator performs XOR operation between operands. Operatorcopies bit if it exists only in one operand. x ^ y results 0110 ~ bitwise inverse This operator is a unary operator used to opposite the bits of operand. ~ x results 0101 << left shift This operator is used to shift the bits towards left x << 2 results 101000 << right shift This operator is used to shift the bits towards right x >> 2 results 0010 >>> z = x | y >>> print z 14 # 14 = 0000 1110 # Bitwise XOR >>> z = x ^ y >>> print z 6 # 6 = 0000 0110 # Bitwise inverse >>> z = ~x >>> print z -11 # -11 = 1111 0101 # Left shift >>> z = x << 2 >>> print z 40 # 40 = 0010 1000 # Right shift >>> z = x >> 2 >>> print z 2 # 2 = 0000 0010
  • 24.
    <DEPARTMENT OF PGMATHEMATICS> PLAN-ACT-SUCCEED 24 Example >>> x = True >>> y = False >>> print (x and y) Example >>> x = 10 >>> y = 12 >>> z = 0 # 10 = 0000 1010 # 12 = 0000 1100 # Bitwise AND >>> z = x & y >>> print z 8 # 8 = 0000 1000 # Bitwise OR Logical Operators These operators are used to check two or more conditions. The resultant of this operator is always a Booleanvalue. Here, x and y are two operands that store either true or false Boolean values. Table 3.6 presents a list of logical operators. Assume x is true and y is false. TABLE 3.6 List of Logical Operators Operator Description Example and logical AND This operator performs AND operation between operands. When both operands are true, the resultant become true. x and y results false or logical OR This operator performs OR operation between operands. When anyoperand is true, the resultant becomes true. x or y results true not logical NOT This operator is used to reverse the operand state. not x results false False #Output
  • 25.
    <DEPARTMENT OF PGMATHEMATICS> PLAN-ACT-SUCCEED 25 >>> print True (x or y) #Output >>> print False (not x) #Output >>> print True (not y) #Output Membership Operators These operators are used to check an item or an element that is part of a string, a list or a tuple. A membership operator reduces the effort of searching an element in the list. Suppose, x stores a value 20 and y is the list containing items 10, 20, 30, and 40. Then, x is a part of the list y because the value 20 is in the list y. Table 3.7gives a list of membership operators. TABLE 3.7 List of Membership Operators Operator Description Example in Return true, if item is in list or in sequence. Return false, if item is not in list or in sequence. x in y, results true not in Return false, if item is in list or in sequence. Return true, if item is not in list or in sequence. x not in y, results false Identity Operators These operators are used to check whether both operands are same or not. Suppose, x stores a value 20 and y stores a value 40. Then x is yreturns falseand x not is yreturns true. Table 3.8 provides a listof identity operators TABLE 3.8 List of Identity Operators Operator Description Example is Return true, if the operands are same. Return false, if the operands are not same. x is y, results false not is Return false, if theoperands are same. Return true, if the operands are not same. x not is y, results true
  • 26.
    <DEPARTMENT OF PGMATHEMATICS> PLAN-ACT-SUCCEED 26 Example >>> x = 12 >>> y = 12 >>> if ( x is y): print “x is same as y” else: print “x is not same as y” x is same as y #Output >>> y = 10 >>> if ( x is not y): print “x is not same as y” else: print “x is same as y” x is not same as y #Output Precedence of Operators When an expression has two or more operators, we need to identify the correct sequence to evaluate theseoperators. This is because the final answer changes depending on the sequence thus chosen. Let us look at an example of a mathematical expression: 10 + 5 / 5 When the given expression is evaluated left to right, the final answer becomes 3. However, if the above expression is evaluated right to left, the final answer becomes 11. This shows that changing the sequence in which the operators are evaluated in the given expression also changes the solution. Therefore, in order to remove this problem, a level of precedence is associated with the operators. Precedence is the condition that specifies the importance of each operator relative to the others. Table 3.9 to display operator precedence from lower precedence to higher: TABLE 3.9 Operator Precedence Operator Description NOT, OR AND Logical operators in , not in Membership operator
  • 27.
    <DEPARTMENT OF PGMATHEMATICS> PLAN-ACT-SUCCEED 27 is, not is Identity operator =, %=, /=, //=, -=, +=, *=, **== Assignment operators. <>, ==, != Equality comparison operator <=, <, >, >= Comparison operators ^, | Bitwise XOR and OR operator & Bitwise AND operator <<, >> Bitwise left shift and right shift +, - Addition and subtraction *, /, %, // Multiplication, Division, Modulus and floor division ** Exponential operator It may happen that an expression has two operators having same precedence. In that case, we use Associativity to evaluate the expression. Associativity is nothing but the direction in which we evaluate the operators if they have same precedence. Associativity In Table 3.9 (precedence of operators) we can see that many operators are having the same precedence. Hence, associativity decides the order in which the operators with same precedence are executed. There are two types of associativity. One is left-to-right and other is right-to-left. In left-to-right associativity, the operator of same precedence are executed from the left side first and in right-to- left associativity, the operator of same precedence are executed from the right side first. Most of the operators in Python have left-to-right associativity. Examples for left-to-right associative operators are multiplication,floor division, etc and ** operator is right-to-left associative. >> > 2 3 * 4 // 6 #Output >> > 0 3 * (4 // 6) #Output >> > 3 ** 4 ** 2 # 3^16 Note When two operators have the same precedence, then operators are evaluated from left to right direction Let us now look at an example of a mathematical expression with operators having the same precedence: 10 * 5 / 5
  • 28.
    <DEPARTMENT OF PGMATHEMATICS> PLAN-ACT-SUCCEED 28 Example >>> x = 12 >>> +x 12 >>> -x -12 >>> ~x -13 #Output #Output #Output Note The invert(~) operator returns the bit-wise inversion of long integer arguments. The bit-wise inversion of y can be computed as –(y+1). Hence, in the above example, we get the ~(12)as -13. In the above expression, the multiplication operator is evaluated before the division operator is evaluated.Based on the number of operands, operators are classified into following two types: 1.Unary Operator 2.Binary Operator Unary Operator Unary operators are operators with only one operand. These operators are basically used to provide sign tothe operand. The format of the unary operator is: Operator operand Some unary operators are as follows: ● + ● - ● ~ ● Binary Operator Binary operators are operators with two operands that are manipulated to get the result. They are also usedto compare numeric values and string values. The format of binary operator is: Operand1 Operator Operand2 Some binary operators are as follows: **, *, /, %, +, -, <<,>>, &, | ,^,<,>,<= ,>=, == ,!= ,<> We saw many examples of binary operators in the section above.
  • 29.
    <DEPARTMENT OF PGMATHEMATICS> PLAN-ACT-SUCCEED 29 STATEMENT AND EXPRESSION Statement A statement can be thought as an instruction that can be interpreted by the Python interpreter. In Section3.9, we came across print and assignment statements. A statement is interpreted by the interpreter and after execution displays some result (if there is a need for displaying it). For e.g., print statement produces some result to display but it does not happen in case of assignment statement. A program can contain many statements in sequence. If there are multiple statements, the result isdisplayed after every statement. As we move ahead in the chapter, we will study more statements such as whilestatement, for statement, if statement, print statement, etc. Let us look at an example of the assignmentstatement: >>> message=”Hello world” Due to the assignment operator (=), the message variable stores the Hello worldstring.Let us look at an example of the printstatement: >>> print 1 1 #simply prints 1 >>> x=2 >>>print x 2 #prints the value of x Check Your Understanding 1. What are the different types of operators in Python? Ans. ● Arithmetic Operator ● Comparison Operator ● Assignment Operator ● Logical Operator ● Bitwise Operator ● Membership Operator ● Identity operator
  • 30.
    <DEPARTMENT OF PGMATHEMATICS> PLAN-ACT-SUCCEED 30 Example >>> 1+1 2 # Output Note In the given example, we assigned a value “Hello Python” to the variable program.Now, when we type only program, we get the output ‘Hello Python.’ This is the term wetyped when we assigned a value to the variable. When we use a print statement with program it gives the value of the variable, i.e., the value after removing quotes. Expression An expression is a combination of variables, operators, values and a reserve keyword. Whenever you type an expression in the command line, the interpreter evaluates it and produces the result. Evaluation of Expression The evaluation of an expression produces a value. In an assignment statement, an expression is always thereon the right side. Let us look at an example of an expression: >>> 2+3 5 # Output >>>program=”Hello Python” >>>program ‘Hello Python’ # Output >>>print program Hello Python # Output An expression is not always a mathematical expression in Python. A value by itself is an expression. In above example, the “Hello Python” is an expression. The interpreter reads the expression and displays the string written in quotes as it is.
  • 31.
    <DEPARTMENT OF PGMATHEMATICS> PLAN-ACT-SUCCEED 31 STRING OPERATIONS The contiguous set of characters kept within quotation marks in Python is termed string. Either single quotes ordouble quotes can be used to represent strings. A string in Python can be a combination of alphabets, numerals and symbols. Mathematical operations cannot be performed on the string even if we have numeral values in it. There are many operations which can be performed on a string such as slice operator ([]) and [:]), concatenation operator (+) and repetition operator (*). Slicing is used to take out a subset of the string,concatenation is used to combine two or more than two strings and repetition is used when we want to repeat same string several times. Let us look at an example of how a string is declared in Python. >>>test=”Test string” As mentioned earler, a string supports various types of operations: Concatenation The concatenation operation is done with the + operator in Python. Concatenation means joining the stringsby linking the last end of the first string with the first end of the second string and so on. Two separate stringstransform into one single string after concatenation. Let us look at an example of concatenation: >>>test=”Test string” >>> “Hello” + test ‘HelloTest string’ # Output >>> Repetition The repetition operation is performed on the strings in order to repeat the string several times. It is donewith * operator. Let us look at an example of repetition: >>> ‘Spam’*3 SpamSpamSpam # Output >>>
  • 32.
    <DEPARTMENT OF PGMATHEMATICS> PLAN-ACT-SUCCEED 32 Get Particular Character To access a single item of the string square brackets[] are used. To access the third element of the string, thestring name is typed followed by the [2]. Remember, the index of the string starts with 0 and not 1. >>>test=”Test string” >>>test[3] ‘t’ # Output >>> Slicing In Python, you can extract a substring by using a colon inside the square bracket [:]. The resultant substringis a part of the long string. >>>test=”Test string” >>>test[1:7]# substring between index 1 to 7 (excludes 7) ‘est st’ # Output >>>test[:3] # substring from index 0 to 3(excludes 3) ‘Tes’ # Output >>>test[2:] # substring from index 2 to last ‘st string’ # Output >>> Python also provides various in-built commands or methods for string operation (Table 3.10). These methods are used to convert the lower case letter to upper case, to determine the length of string, etc. TABLE 3.10 List of in-built commands Method Description .lower() Convert all upper case letters into lower case. .upper() Convert all lower case letters into upper case. .isalpha() Return true if string contain only alphabetical characters. .isdigit() Return true if string contain only digits characters.
  • 33.
    <DEPARTMENT OF PGMATHEMATICS> PLAN-ACT-SUCCEED 33 Check Your Understanding 1. What is slicing? Ans. In Python, you can extract a substring by using a colon inside the square bracket [:]. Theresultant substring is a part of the long string. 2. What are statement and expression in Python? Ans. A statement is the instruction that can be interpreted by the Python interpreter. An expressionis a combination of variables, operators, values and reserve keyword. .isspace() Return true if string contain space. .find(“string”) Return the first index of search string. .replace(“ old”,”new”) Replace the string with other string. .count(“character”) Return the occurrence of particular character in string. len(“string”) Return the length of string. Example >>> s = “Hello Python” >>> print s.lower() hello python >>> print s.upper() HELLO PYTHON >>> print s.find(“l”) 2 >>> print s.replace(“l”,”p”) Heppo Python >>> print s.count(“o”) 2 >>> print len(s) 12 #Defining a string #Converts the string in lower case #Converts the string in upper case #returns the index of first ‘l’ #Replace each “l” to “p” #count the number of “o” #Length of the string >>> s = “Hello” >>> print s.isalpha() True >>> print s.isdigit() False #String contains only alphabets #String doesn’t contain digits
  • 34.
    <DEPARTMENT OF PGMATHEMATICS> PLAN-ACT-SUCCEED 34 BOOLEAN EXPRESSIONS A Boolean expression may have only one of two values: TRUEor FALSE. The simplest Boolean expressions in Python are True and False. The following example uses the operator ==, which compares two operands and prints true if they are equal otherwise print false: >>> 5 == 5 True # Output >>> 5 == 6 False # Output >>> True True # Output >>> False False # Output CONTROL STATEMENTS The for Loop The Python for loop is an iterator-based for loop. It goes through the elements in any ordered sequence list, i.e., string, lists, tuples, the keys of dictionary and other iterables. In each iteration step, a loop variable is set to a value. The for loop in Python is a bit different from the for loop in any other programming language you have gone through. Note We can see in the following example that bool is the name of the class representingPython’s Boolean expressions. >>>type(True) <type ‘bool’> >>>type(False) <type ‘bool’>
  • 35.
    <DEPARTMENT OF PGMATHEMATICS> PLAN-ACT-SUCCEED 35 Syntax >>>for x in y : Block 1 else: Block 2 # Optional # excuted only when the loop exits normally Example >>>for letter in ‘Python’ : print ‘Current Letter :’, letter Output: Current Letter : P Current Letter : y Current Letter : t Current Letter : h Current Letter : o Current Letter : n Example >>> subjects = [“Maths”, “English”, “Physics”, “Chemistry”, “Computer”] >>> for x in subjects:print(x) Example # Print first five even numbers. >>> count = 2 >>> while True: print count count = count + 2 if count >= 12: break # breaks the loop 2 4 6 8 10 # Output In the above section, we have seen the syntax of for loop. The for loop is used to iterate over a sequence. Here, xis used to iterate over yand when the loop exits normally then the elsepart of the forloop executes otherwise not.
  • 36.
    <DEPARTMENT OF PGMATHEMATICS> PLAN-ACT-SUCCEED 36 Example >>> for x in range(7): print(x) else: print(‘Else Part’) 0 1 2 3 4 5 6 Else Part In the above example, we have printed the value from 0 to 6 by using the for loop and an else parthaving a print statement is also been used. In this case, the for loop is ended normally then the else part also executed but when the loop stops because of break statement then the else part doesn’t execute. Example >>> range(8) [0, 1, 2, 3, 4, 5, 6, 7] Example >>> range(3,9) [3, 4, 5, 6, 7, 8] range()Function The range()function is a built-in function in Python that helps us to iterate over a sequence of numbers. It produces an iterator that follows arithmetic progression. range(8)provides a sequence of numbers 0-7. That is to say, range(n)generates a sequence of numbersthat starts with 0and ends with (n-1). range()function can also be passed with two arguments: beginand end. Maths English Physics Chemistry Computer #Output
  • 37.
    <DEPARTMENT OF PGMATHEMATICS> PLAN-ACT-SUCCEED 37 Example >>> range(3,40, 5) [3, 8, 13, 18, 23, 28, 33, 38] We provided the begin index with 3 and the end index with 9. Hence, the range function generates a sequence iterator of numbers that starts from 3and ends at 8. Till now, we have seen that all the numbers in the sequence have a difference of 1. We can also change this difference if we want to. For this purpose, we have to use another parameter, step, along with begin and end. This range() function gives us a sequence that starts from 3and ends at 38; every number in the list hasa difference of 5. Example >>> subjects = [“Maths”, “English”, “Physics”, “Chemistry”, “Computer”] >>> for x in subjects:print(x) >>> for index in range(len(subjects)): print ‘Current Subject : ‘, subjects[index] Current Subject :maths #Output Current Subject :physics Current Subject : chemistry Current Subject : computer In the above example, a list subjects is defined which has 4 elements or items in it. Now, it is required to print all the elements in list subjects one by one with the for loop and taking help of range() function. Now, we initialized a for loop in next statement which will iterate over the sequence of number given by the range() function. In our example, we have used range(len(subjects))which meansrange(4)that is because the length of the list subjectsis 4 which is computed by the function len.
  • 38.
    <DEPARTMENT OF PGMATHEMATICS> PLAN-ACT-SUCCEED 38 Syntax >>> while condition :block else: #Optional statement While Statement The while statement is used when you have a piece of code and you want to repeat it ‘n’ number of times or forever. With whileloop, we have to give a conditional statement that tells the interpreter when the loop will halt. Here, conditionis a statement by which interpreter decides when to halt the loop and blockis thepiece of code that we want to repeat. Break and continue Statements The breakand continuestatements are often useful in a whileloop as well as in a forloop. The breakstatement exits from the loop and transfers the execution from the loop to the statement that is immediately following the loop. The continue statement causes execution to immediately continue at the start of the loop, it skips the execution of the remaining body part of the loop.
  • 39.
    <DEPARTMENT OF PGMATHEMATICS> PLAN-ACT-SUCCEED 39 Example Write a while statement that prints integers from zero to 5. >>> count = 0 >>> while count < 6:print count count += 1 0 1 2 3 4 5 # Output Example # Print first four even numbers. >>> for i in range(1,10): Note If the break statement in a for loop is executed then the else part of that for loop is skipped. Note The break and continue statements are often useful in a while statement. The break statement exits from the loop. The continue statement causes execution to immediately continue at the start of the loop. if elif else Statement The ifstatement is known as the decision-making statement in programming languages. With an if clause,a condition is provided; if the condition is True then the block of statement written in the if clause will be executed, otherwise not. if i % 2 != 0: continue # if condition becomes true, it skips the print part print i 2 4 6 8 # Output
  • 40.
    <DEPARTMENT OF PGMATHEMATICS> PLAN-ACT-SUCCEED 40 Example >>>var = 100 if (var ==100) : print “Value of expression is 100” Output: Value of expression is 100 Syntax >>>if expression : statement1 else : statement2 Syntax >>>if expression1 : statement1 elif expression2 : statement2 elif expression3 : statement3 else expression4 : statement4 Check Your Understanding 1. What is a for statement? Ans. The for statement in Python differs a bit from what you may be used to in C. In C, for loop gives the user the ability to define both the iteration step and the halting condition, but in Python, the for statement iterates over the items any ordered sequence (a list or a string), in the order that they appear in the sequence. An else statement can be combined with an if statement. It contains the block of code that executes if the conditional expression in the if statement resolves to 0 or FALSE value. It is an optional statement.Please note there can be at the most one elsestatement following if. We can check multiple expressions for TRUEwith the help of elifstatement and execute a block of codewritten just below the elifstatement whose condition is TRUE. Similar to else, the elifstatement is optional. However, there can be more than one elif statementfollowing an if.
  • 41.
    <DEPARTMENT OF PGMATHEMATICS> PLAN-ACT-SUCCEED 41 Alternative Executions The alternative execution provides two possibilities. The condition determines which possibility is executed. If the condition is TRUE, the first block is executed but if condition is FALSE, another block of code is executed. This is the second form of the if statement. The syntax looks like: >>>if x % 2 == 0 : print ‘x is even’else print ‘x is odd’ The condition can be either true or false. So, only one alternative will be executed. The alternatives arecalled branches, because they are branches in the flow of execution. Conditional Execution In programming languages, conditional statements or conditional constructs are the statements that are generally used with some conditions. The actions performed by these conditional statements are entirely dependent on the value of the condition, on whether the value is TRUE or FALSE. The condition usually uses comparisons and arithmetic expressions with variables. These expressions are evaluated to the Boolean values True or False. The statements for the decision- making are called conditional statements or conditional expressions. The simplest form is the ifstatement: >>>if x > 0 : print “x is positive” TIP The Boolean expression after the if statement is called the condition. If the condition is true, then the intended statement is executed. If the condition is not true, the statement isnot executed. Here’s an example of the syntax for an ifstatement: >>>if BOOLEAN EXPRESSION:
  • 42.
    <DEPARTMENT OF PGMATHEMATICS> PLAN-ACT-SUCCEED 42 Note The set of intended statements that follow a conditional statement or a loop statement is called block. Indentation can be done by 'tabs' or 'spaces'. Using 4 spaces for indentation of a block is standard. A statement block inside a compound statement is called the body of the statement. The intended statements that follow the conditional statements are called block. The first unintended statement marks the end of the block. A statement block inside the compound statement is called the body of the statement. Syntax The syntax of a while loop in Python programming language is as follows: >>> while expression : statement(s) else: # Optional statement # executes only when while condition becomes false STATEMENTS There are no bounds on the number of statements that can appear in the body of an ifstatement, but therehas to be at least one statement. Occasionally, it is useful to have a body with no statements. In that case, you can use the pass statement, which does nothing. >>>if True : # This is always true pass # so this is always executed, but it does nothing ITERATION – while STATEMENT A while loop statement in Python programming language is the command that repeats a piece of code up to several times. The number of times the piece of code is executed depends on the condition expression written with the whilestatement. Here, statement(s) may be a single statement or a block of statements. The condition may be any expression, and whenever the expression resembles a non-zero value, it will be treated as TRUE, otherwise it will be treated as FALSE. The loop iterates while the condition is TRUE.
  • 43.
    <DEPARTMENT OF PGMATHEMATICS> PLAN-ACT-SUCCEED 43 Example >>>count = 0 while (count < 9) : print ‘The count is :’, countcount = count + 1 Output: The count is : 0 The count is : 1 The count is : 2 The count is : 3 The count is : 4 The count is : 5 The count is : 6 The count is : 7 The count is : 8 Unlike other programming languages, whileloop in Python makes use of an optional elseclause whichis executed when the condition of whilestatement fails. When the condition becomes false, program control passes to the line immediately following the loop.
  • 44.
    <DEPARTMENT OF PGMATHEMATICS> PLAN-ACT-SUCCEED 44 Flow Diagram Figure 3.8 represents a flow diagram. While has an optional‘else’ block Figure 3.8 Working of a While Loop The block here, consisting of the print and increment statements, is executed repeatedly until count is no longer less than 9. With each iteration, the current value of the index count is displayed and then increased by 1. INPUT FROM KEYBOARD In a programming language, the input from keyboard by user plays the most important role in executing a program. There is hardly any program which executes without some input. The input in many programs is prompted by the user and the user uses the keyboard in order to provide input for the program to execute. Python programming language also provides the facility to user to provide input from keyboard. That is done by two ways in Python. Note If there is a continue statement inside a while loop or a for loop then also the else part of that loop is executed. while expression: statements(s) condition If condition is ture If condition is false conditional code
  • 45.
    <DEPARTMENT OF PGMATHEMATICS> PLAN-ACT-SUCCEED 45 Example >>> name = input(“What is your Name?”) >>> print (“Hello “ + name + “!”) What is your Name? ‘John’ Hello John! #Output >>> age = input(“Enter your age? “) >>> print age Enter your age? 32 32 #Output >>> hobbies = input(“What are your hobbies? “) >>> print hobby What are your hobbies? [‘playing’, ‘travelling’] #Output [‘playing’, ‘travelling’] >>> type(name) <type ‘str’> >>> type(age) input()Function The first function for prompting the input from user in Python is through input() function. input() function has an optional parameter, which is the prompt string. When the input() function is called, in order to take input from the user then the execution of program halts and waits for the user to provide an input. The input is given by the user through keyboard and it is ended by the return key. input()function interprets the input provided by the user, i.e. if user provides an integer value as input then the input function will return this integer value. On the other hand, if the user has input a String, then the function will return a string. <type ‘int’> >>> type(hobbies) <type ‘list’>
  • 46.
    <DEPARTMENT OF PGMATHEMATICS> PLAN-ACT-SUCCEED 46 Example # No casting >>> age = raw_input(“What is Your Age? “) What is Your Age? 46 >>> type(age) <type ‘str’> #Input is stored as string #Using casting function to convert input to integer >>> age = int(raw_input(“What is your age? “)) What is your age? 46 >>> type(age) <type ‘int’> #Input is stored as integer Check Your Understanding 1. What is Alternative Execution? Ans. The alternative execution provides two possibilities and the condition determines which one is to be executed. This is the second form of the if statement. 2. What is the syntax for ifelse and elif statements? Ans. >>> if expression1 : statement(s) elif expression2 : statement(s) elif expression3 : statement(s) else expression4 : statement(s) raw_input() Function raw_input() is somewhat different from the input() function provided by Python programming language. raw_input() also takes the input from the user but it does not interpret the input and also it returns the input of the user without doing any changes, i.e. raw. Afterwards, we can change this raw input into any data type which is needed for our program. In order to take input from the user in desired data type, we can use the casting function with raw_input(). This is the reason, why raw_input()is most preferred over the input()function. ● In Python, forstatement iterates over the items in a sequence (a list or a string) in the order in which they appear in the sequence. ● Syntax for whilestatement in Python is:
  • 47.
    <DEPARTMENT OF PGMATHEMATICS> PLAN-ACT-SUCCEED 47 >>> while condition :Block SELF-ASSESSMENT 1. Fill in the Blanks Questions – minimum ten questions MultipleChoiceQuestions 1. Which of the following is not a data type? a. String b. Numeric c. Array d. Tuples 2. Which character is used for commenting in Python? a. # b. ! c. @ d. * 3. What is the output of [‘name!’] * 2? a. [‘name!’] * 2 b. [‘name’!, ‘name’!] c. [‘name!’, ‘name!’] d. [‘name’!] * 2 4. Which is not a reserved keyword in Python? a. Insert b. Pass c. Class d. Lambda 5. What is the output of >>> 4+? a. 4+ b. 4 c. 5 d. Invalid syntax 6. What will be the output of str[0:4] if str=”Hello”? a. ‘Hello’ b. ‘H’ c. ‘Hel’ d. ‘Hell’ 7. Which of the following is the floor division operator? a. / b. % c. // d. 8. Which of the following is used to find the first index of search string? a. .find(“string”) b. .search(“string”) c. (“string”).find d. (“string”).search 9. Which of the following is used to access single character of string? a. [:] b. () c. [.] d. [] 10. What is the order of precedence in Python? i. Addition ii. Multiplication iii. Division iv. Subtraction v. Exponential vi. Parenthesis a. ii, i, iii, iv, vi, v b. vi, v, iii, ii, i, iv
  • 48.
    <DEPARTMENT OF PGMATHEMATICS> PLAN-ACT-SUCCEED 48 c. vi, v, ii, i, iii, iv d. ii, vi, iii, i, iv, v 11. Which of the following will be printed? x =4.5 y =2 print x//y a. 2.0 b. 2.25 c. .25 d. 0.5 12. What gets printed? Nums=set([1,1,2,3,3,3,4]) Print len(nums) a. 2 b. 4 c. 5 d. 7 2. Match the Following – minimum five options 3. Short Answer Questions – minimum five Write a Program to find the square root of a number. Solution. >>> x = int(input(‘Enter an integer number: ‘)) >>> sqrt_x = x ** 0.5 >>> print (sqrt_x) Enter an integer number: 64 8.0 #Output 1. Write a program to find the area of a Rectangle. Solution. >>> l = float(input(‘Enter the length of the Rectangle: ‘)) >>> b = float(input(‘Enter the breadth of the Rectangle: ‘)) >>> area = l * b >>> print (area) Enter the length of the Rectangle: 14Enter the breadth of the Rectangle: 7 98.0 #Output 2. Write a program to swap the values of two variables. Solution.
  • 49.
    <DEPARTMENT OF PGMATHEMATICS> PLAN-ACT-SUCCEED 49 >>> num1 = input(‘Enter the value of num1: ‘) >>> num2 = input(‘Enter the value of num2: ‘) >>> temp = num1 >>> num1 = num2 >>> num2 = temp >>> print “num1 = “, num1 >>> print “num2 = “, num2 Enter the value of num1: 4Enter the value of num2: 7 num1 = 7 #Output num2 = 4 3. Write a program to convert kilogram into pound. Solution. >>> kg = float(input(‘Enter the value in kilogram: ‘)) >>> kg_to_pound = 2.20462 >>> pound = kg * kg_to_pound >>> print “%0.3f kg = %0.3f pounds” %(kg,pound) Enter the value in kilogram: 60 60.000 kg = 132.277 pounds #Output 4. Write a program to find whether a number is even or odd. Solution. >>> number = int(input(“Enter an integer number: “)) >>> if (number % 2) == 0: print “Number is even” else: print “Number is odd” Enter an integer number: 6 Number is even #Output 5. Write a program to check the largest among the given three numbers. Solution. >>> x = int(input(“Enter the first number: “))
  • 50.
    <DEPARTMENT OF PGMATHEMATICS> PLAN-ACT-SUCCEED 50 Enter the first number: 14 >>> y = int(input(“Enter the second number: “)) Enter the second number: 21 >>> z = int(input(“Enter the third number: “)) Enter the third number: 10 >>> if (x > y) and (x > z):l = x elif (y > x) and (y > z):l = y else: l = z >>> print “The largest among the three is “,l The largest among the three is 21 #Output 6. Write a Python program to check if the input year is a leap year or not. Solution. # Python program to check if the input year is a leap year or not >>> year = int(input(“Enter year: “)) >>> if(year % 4)==0:if(year%100)==0: if(year%400)==0: print (year, ‘ is leap year’) else: else: print (year, ‘ is not leap year’) print (year, ‘ is leap year’) else: print (year, ‘ is leap year’) Output: Enter a year: 20162016 is leap year Output:
  • 51.
    <DEPARTMENT OF PGMATHEMATICS> PLAN-ACT-SUCCEED 51 Enter a year: 19851985 not leap year 4. Long Answer Questions – minimum two 5. Case Study Questions – minimum one, where Possible 6. Problem Solving Questions – minimum one, where Possible 7. Assignment – minimum one
  • 52.
    <DEPARTMENT OF PGMATHEMATICS> PLAN-ACT-SUCCEED 52 SUMMARY (in bullet points) ● Python is a high-level general-purpose programming language. The code written in Python is automaticallycompiled to byte code and executed. ● The printstatement is used to display the output screen. ● In Python, the Hash character (#) is used for commenting. Codes or texts that come after the hash character are not considered as a part of the program. ● In Python, an identifier (name) must begin with a letter or underscore and can include any number ofletters, digits, or underscore. ● Writing the name of a variable is called declaring a variable whereas assigning a value to a variable iscalled initialising a variable. ● Python supports six data types which are as follows: 1. Numeric 2. String 3. List 4. Tuple 5. Dictionary 6. Boolean ● The main differences between lists and tuples are that lists are enclosed in brackets ([]) and their elements and size can be changed, while tuples are enclosed in parentheses(()) and cannot be updated. Tuples can be thought of as read-only lists. ● The items cannot be modified in tuple, but can be modified in the list. ● APython dictionary works on the basis of key-value pairs. Key used in dictionary can be an integer valueor a string value. ● On the basis of functionality, operators in Python are categorised into following seven types: 1. Arithmetic operator 2. Comparison operator 3. Assignment operator 4. Logical operator 5. Bitwise operator 6. Membership operator 7. Identity operator ● A statement is a unit of code that the Python interpreter can execute. ● An expression is a combination of variables, operators, values and reserve keyword. ● A string is a combination of characters (alphabets, digits and symbols). A string value is always enclosedwithin double or single quotes.
  • 53.
    <DEPARTMENT OF PGMATHEMATICS> PLAN-ACT-SUCCEED 53 ● The concatenation operation is done with the + operator. Concatenation means joining the strings togetherby linking them end to end. ● The repetition operation is performed on the strings in order to repeat the string several times. ● In Python, you can extract substring by using the colon inside the square bracket [:]. The resultant substring is a part of the long string. KEYWORDS ✓ COMMENT: The part of the program not executed by the interpreter. It is used by other persons tounderstand the program thoroughly. ✓ CONCATENATION: The process of joining strings end-to-end. ✓ DICTIONARY: A mapping of keys to their corresponding values. ✓ FLOATING POINT: A type of numeral that has a fractional part. ✓ HIGH-LEVEL LANGUAGE: A programming language such as Python that is designed to be easy forhumans to read and write. ✓ INDEX: An integer value that represents an element in a sequence. ✓ INTEGER: A type of numeral that represents whole numbers including negative numbers. ✓ INTERACTIVE MODE: A way of using Python language where we type command and expressions. ✓ INTERPRET: To execute a program in a high-level language by executing it one line at a time. ✓ ITEM: An element or a value in a series. ✓ ITERATION: The repetition of a set of statements or a piece of code. ✓ KEYWORD: A word that is reserved in a programming language for a specific purpose. We cannot usekeywords such as if and else as variable names. ✓ OPERAND: The value on which an operator operates. ✓ SLICE: A subset or a part of a string. TEXT BOOKS(with indicative page numbers) E Balagurusamy, Introduction To Computing And Problem Solving Using Python, McGraw Hill Education (India) Private Limited, P-24, Green Park Extension, New Delhi 110 016, 2016. UNIT I : Chapter 3 : Sections 3.1 – 3.15 UNIT II : Chapter 4 : Section 4.1 – 4.10 UNIT III : Chapter 5 : Section 5.1, 5.2
  • 54.
    <DEPARTMENT OF PGMATHEMATICS> PLAN-ACT-SUCCEED 54 UNIT IV : Chapter 6 : Sections 6.1, 6.2 UNIT V: Chapter 7 : Section 7.1 – 7.5 REFERENCE BOOKS (with indicative page numbers) 1. Kenneth A. Lambert, Martin Osborne, Fundamentals of Python, Cengage, Learning India Pvt Ltd, 2020 2. Mark Summerfield, Programming in Python 3 – Developer’s Library, Pearson Education, Delhi 110 092, 2009 3. Robert Sedgewick, Kevin Wayne Robert Dondero, Introduction to Programming in Python – An Inderdisciplinary Approach, , Pearson Education, Chennai 600 115, 2018 E-RESOURCES(Websites, YouTube, etc) http://www.pitt.edu/~peterb/0012-161/syllabus.html