Python Chapter 2 Class 11
Python Chapter 2 Class 11
of Python 3
In this chapter
»» Introduction to Python
»» Python Keywords
“Don't you hate code that's not properly »» Identifiers
indented? Making it [indenting] part of »» Variables
the syntax guarantees that all code is »» Data Types
properly indented.” »» Operators
»» Expressions
— G. van Rossum »» Input and Output
»» Debugging
»» Functions
»» if..else Statements
3.1 Introduction to Python »» for Loop
»» Nested Loops
An ordered set of instructions or commands to be
executed by a computer is called a program. The
language used to specify those set of instructions
to the computer is called a programming language
for example Python, C, C++, Java, etc.
This chapter gives a brief overview of Python
programming language. Python is a very popular
and easy to learn programming language, created
by Guido van Rossum in 1991. It is used in a
variety of fields, including software development,
web development, scientific computing, big data
3.3 Identifiers
In programming languages, identifiers are names used
to identify a variable, function, or other entities in a
program. The rules for naming an identifier in Python
are as follows:
• The name should begin with an uppercase or a
lowercase alphabet or an underscore sign (_). This
may be followed by any combination of characters
a-z, A-Z, 0-9 or underscore (_). Thus, an identifier
cannot start with a digit.
• It can be of any length. (However, it is preferred to
keep it short and meaningful).
• It should not be a keyword or reserved word given in
Table 3.1.
• We cannot use special symbols like !, @, #, $, %, etc.
in identifiers.
For example, to find the average of marks obtained
by a student in three subjects namely Maths, English,
Informatics Practices (IP), we can choose the identifiers
as marksMaths, marksEnglish, marksIP and avg
rather than a, b, c, or A, B, C, as such alphabets do not
give any clue about the data that variable refers to.
avg = (marksMaths + marksEnglish + marksIP)/3
3.4 Variables
Variable is an identifier whose value can change. For
example variable age can have different value for
different person. Variable name should be unique in a
program. Value of a variable can be string (for example,
Dictionaries
Example 3.2
#To create a list
>>> list1 = [5, 3.4, "New Delhi", "20C", 45]
#print the elements of the list list1
>>> list1
[5, 3.4, 'New Delhi', '20C', 45]
(C) Tuple
Tuple is a sequence of items separated by commas and
items are enclosed in parenthesis ( ). This is unlike list,
where values are enclosed in brackets [ ]. Once created,
we cannot change items in the tuple. Similar to List,
items may be of different data types.
Example 3.3
#create a tuple tuple1
>>> tuple1 = (10, 20, "Apple", 3.4, 'a')
#print the elements of the tuple tuple1
>>> print(tuple1)
(10, 20, "Apple", 3.4, 'a')
3.5.3 Mapping
Mapping is an unordered data type in Python. Currently,
there is only one standard mapping data type in Python
called Dictionary.
(A) Dictionary
Dictionary in Python holds data items in key-value pairs
and Items are enclosed in curly brackets { }. dictionaries
permit faster access to data. Every key is separated from
its value using a colon (:) sign. The key value pairs of
a dictionary can be accessed using the key. Keys are
usually of string type and their values can be of any data
type. In order to access any value in the dictionary, we
have to specify its key in square brackets [ ].
Example 3.4
#create a dictionary
>>> dict1 = {'Fruit':'Apple',
'Climate':'Cold', 'Price(kg)':120}
>>> print(dict1)
{'Fruit': 'Apple', 'Climate': 'Cold',
'Price(kg)': 120}
#getting value by specifying a key
Python compares two >>> print(dict1['Price(kg)'])
strings lexicographically 120
(According to the
theory and practice of
composing and writing
3.6 Operators
dictionary), using ASCII An operator is used to perform specific mathematical or
value of the characters. logical operation on values. The values that the operator
If the first character of
works on are called operands. For example, in the
both strings are same,
the second character is expression 10 + num, the value 10, and the variable num
compared, and so on. are operands and the + (plus) sign is an operator. Python
supports several kind of operators, their categorisation
is briefly explained in this section.
3.6.1 Arithmetic Operators
Python supports arithmetic operators (Table 3.3) to
perform the four basic arithmetic operations as well as
modular division, floor division and exponentiation.
'+' operator can also be used to concatenate two
strings on either side of the operator.
>>> str1 = "Hello"
>>> str2 = "India"
>>> str1 + str2
'HelloIndia'
'*' operator repeats the item on left side of the
operator if first operand is a string and second operand
is an integer value.
>>> str1 = 'India'
>>> str1 * 2
'IndiaIndia'
3.7 Expressions
An expression is defined as a combination of constants,
variables and operators. An expression always evaluates
to a value. A value or a standalone variable is also
considered as an expression but a standalone operator
is not an expression. Some examples of valid expressions
are given below.
(i) num – 20.4 (iii) 23/3 -5 * 7(14 -2)
(ii) 3.0 + 3.14 (iv) "Global"+"Citizen"
3.9 Debugging
Due to errors, a program may not execute or may
generate wrong output. :
i) Syntax errors
ii) Logical errors
iii) Runtime errors
3.10 Functions
A function refers to a set of statements or instructions
grouped under a name that perform specified tasks.
For repeated or routine tasks, we define a function. A
function is defined once and can be reused at multiple
Example 3.13
>>> list(range(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
#start value is given as 2
>>> list(range(2, 10))
[2, 3, 4, 5, 6, 7, 8, 9]
#step value is 5 and start value is 0
>>> list(range(0, 30, 5))
[0, 5, 10, 15, 20, 25]
#step value is -1. Hence, decreasing
#sequence is generated
>>> list(range(0, -9, -1))
[0, -1, -2, -3, -4, -5, -6, -7, -8]
The function range() is often used in for loops for
generating a sequence of numbers.
Program 3-5 Program to print the multiples of 10 for
numbers in a given range.
#Program 3-5
#Print multiples of 10 for numbers in a range
for num in range(5):
if num > 0:
print(num * 10)
Output:
10
20
30
40
#Program 3-6
#Demonstrate working of nested for loops
for var1 in range(3):
print( "Iteration " + str(var1 + 1) + " of outer loop")
for var2 in range(2): #nested loop
print(var2 + 1)
print("Out of inner loop")
print("Out of outer loop")
Output:
Iteration 1 of outer loop
1
2
Out of inner loop
Iteration 2 of outer loop
1
2
Out of inner loop
Iteration 3 of outer loop
1
2
Out of inner loop
Out of outer loop
Summary Notes
• Python is an open-source, high level, interpreter-
based language that can be used for a multitude of
scientific and non-scientific computing purposes.
• Comments are non-executable statements in a
program.
• An identifier is a user defined name given to a
variable or a constant in a program.
• Process of identifying and removing errors from a
computer program is called debugging.
• Trying to use a variable that has not been assigned
a value gives an error.
• There are several data types in Python — integer,
boolean, float, complex, string, list, tuple, sets,
None and dictionary.
• Operators are constructs that manipulate the value
of operands. Operators may be unary or binary.
• An expression is a combination of values, variables,
and operators.
• Python has input() function for taking user input.
• Python has print() function to output data to a
standard output device.
• The if statement is used for decision making.
• Looping allows sections of code to be executed
repeatedly under some condition.
• for statement can be used to iterate over a range
of values or a sequence.
• The statements within the body of for loop are
executed till the range of values is exhausted.
Exercise
1. Which of the following identifier names are invalid and
why?
a) Serial_no. e) Total_Marks
b) 1st_Room f) total-Marks
c) Hundred$ g) _Percentage
d) Total Marks h) True
Notes