Unit-2 Computational Thinking and Programming
Unit-2 Computational Thinking and Programming
CHAPTER-5
COMPUTATIONAL THINKING AND GETTING STARTED WITH PYTHON
INTRODUCTION
Developed by Guido Van Rossum in February 1991.
Named after famous BBC comedy show “Monty Python’s Flying Circus”.
Powerful and easy to learn object oriented programming language.
Powerful as other high level languages like C++, Java etc.
COMPUTATIONAL THINKING
Computational thinking is an approach to solving problems using concepts and ideas from computer
science, and expressing solutions to those problems so that they can be run on a computer. It has
the following characteristics/principles:
Decomposition: it is the breaking down a complex problem, data or process into smaller,
more manageable parts.
Pattern recognition/Data Representation: It refers to looking for similarities, patterns and
trends in data.
Abstraction: It is the filtering out unnecessary details/information to focus only on the
important information.
Generalisation: It is identifying the common or shared characteristics.
Algorithms: It is a process of step-by-step development of instructions to solve a
problem.
Decomposition
The process of breaking down a big or complex problem into a set of smaller sub-processes in order
to understand a problem or situation better is known as decomposition. Examples:
Making cookies: mixing up the dough, forming into shapes, and baking
Construct a bridge: considering the site conditions, technology available, foundation etc.
Writing a computer program: determine well defined series of steps/functions to solve the
problem.
Pattern Recognition
It refers to observing or looking similarities or patterns among and within small, decomposed
problems; the identified pattern help to solve more complex problems more efficiently. E.g.:
While driving on roads, switching lanes promptly may cause accidents. So the drivers look for
patterns in traffic to decide whether and when to switch lanes.
Pattern recognition is required when categorizing rocks as igneous, metamorphic or
sedimentary.
Abstraction
Abstraction or data abstraction refers to focusing on information relevant to the problem and
suppressing other details. Examples:
When teaching driving to someone, you explain about gears and steering but not about
internal wiring of the engine.
A calculator only shows numbers and operations buttons and not show/gives the
algorithm/programs underneath.
Page 1 of 46
CLASS-XI COMPUTATIONAL THINKING AND PROGRAMMING UNIT-2
Generalization
It refers to identifying common or shared characteristics between two domains or problems such
that models or solutions of one could be adapted or applied to the other. Examples:
Mammals are warm blooded, give live birth, have hair, and so on. An elephant is a mammal.
Therefore, it is warm blooded, give live birth, have hair.
Solids dissolve faster if they are smaller and the solution is warmer. A specific solid is not
dissolving fast o either it is big in size or the solution is not warm.
Algorithm Design
An algorithm is sequence of steps that solves a problem by working on some input data and
producing a desired output. Algorithm design involves both creation and execution of an algorithm.
Example:
Writing a recipe Calculating simple interest
Evaluation
It aims to check to see whether a solution reached via decomposition, pattern recognition,
abstraction/generalisation, algorithm design is good and effective. It involves consideration of:
Algorithm correctness
Requirements (meeting constraints, design principles etc.)
Performance (usability, efficiency, speed, complexity, reliability etc.)
INTRODUTION TO PYTHON
1. Created by GUIDO VAN ROSSUM when he was working at CENTRUM VISKUNDE AND INFORMATICA.
2. Language was released in 1991.
3. Python got its name from a BBC comedy series from 70’s – ‘MONTY PYTHON’S FLYING CIRCUS’.
4. Can be used to follow both Procedural approach and object oriented approach of programming. It is
free to use.
PYTHON-PLUSES
1. Easy to Use (simple syntax rules)
2. Expressive Language (express the code’s purpose)
3. Interpreted Language: Python interprets and executes the code line by line at a time. Thus it
is easy to debug.
4. It’s Completeness: No need to download and install additional libraries. All types of required
functionality are available through various modules of python standard library.
5. Cross-platform/Portable Language: Can be run on Windows, Linux/Unix, Macintosh,
smartphones etc.
6. Free and Open Source: Python language is freely available and its source-code is also
available. (Open source means you can modify, improve an open source software)
7. Variety of Usage/Applications: Powerful, complete and useful language. Usage includes:
Scripting Rapid Prototyping
Web Applications GUI Programs
Game development Database Applications
System administrations
PYTHON-MINUSES
1. Not the Fastest Language: Python is an interpreted language not a fully compiled one.
Python program is first semi-compiled into an internal byte-code, which is then exerted by a
Python interpreter.
2. Lesser Libraries than C, Java, Perl
Page 2 of 46
CLASS-XI COMPUTATIONAL THINKING AND PROGRAMMING UNIT-2
3. Not Strong on Type-binding
4. Not easily Convertible: Since most other programming languages have strong syntax, the
translation from Python to another language is not easy.
WORKING IN PYTHON
Multiple Python distributions available:
CPython Installation: comes with python interpreter, Python IDLE (Python GUI) and Pip
(package installer). This is the default installation distribution available..
Anaconda Python
PyCharm IDE, Spyder IDE etc.
Understanding print ()
To print or display output to the output device (mostly monitor), Python 3.x provides print ()
function. Use print () as:
print (<objects to be printed>)
You can enclose your strings in either double quotes or in single quotes, but just ensure that opening
and closing quotes are of same type.
Page 4 of 46
CLASS-XI COMPUTATIONAL THINKING AND PROGRAMMING UNIT-2
CHAPTER-6
PYTHON FUNDAMENTALS
TOKENS
The smallest individual unit in a program is known as a Token or a lexical unit. Python has the
following tokens:
i) Keywords iv) Operators
ii) Identifiers (Names) v) Punctuators
iii) Literals
Keywords
Keywords are the words that convey a special meaning to the language compiler/interpreter. These
are reserved for special purpose and not be used as normal identifier names. Examples:
False, for, in, while, break, if, elif, else, True, and, or etc.
Identifiers (Names)
Identifiers are fundamental building blocks of a program and are used as the general terminology for
the names given to different parts of the programs i.e. variables, objects, functions, lists, dictionaries
etc. Identifier rules of Python are:
Identifiers can be a combination of letters in lowercase (a to z) or uppercase (A to Z) or digits (0 to
9) or an underscore _.
An identifier cannot start with a digit.
Keywords cannot be used as identifiers.
We cannot use special symbols like !, @, #, $, % etc. in our identifier.
Identifier can be of any length.
Python is case-sensitive as it treats upper and lower-case characters differently.
Literals/ Values
Literals (often referred to as constant-Values) are data items that have a fixed value. Python provides
several kinds of literals:
i) String literals iv) Special literal None
ii) Numeric literals v) Literal Collections
iii) Boolean literals
String Literals
A string literal is a sequence of characters surrounded by quotes (single or double or triple)
Non-Graphic characters are those characters that cannot be typed directly from keyboard e.g.
backspace, tabs etc. That is, no character is typed when these keys are pressed, only some action
takes place. These characters can be represented by using escape sequences. An escape
sequence is represented by a backslash (\) followed by one or more characters.
An escape sequence represents a single character and hence consumes one byte in ASCII
representaion.
Page 5 of 46
CLASS-XI COMPUTATIONAL THINKING AND PROGRAMMING UNIT-2
\f ASCII Form feed (FF) \uxxxx Character with 16-bit hex value xxxx.
Exactly four hexadecimal digits are
required.
String in Python
Python allow two types of strings:
i) Single-line Strings: The strings that you create by enclosing text in single or double quotes
are normally single line strings. They must terminate in one line.
ii) Multiline Strings: Create in two ways:
a. By adding a backslash at the end of single quote/ double quote string.
b. By typing the text in triple quotation marks (No backlash needed at the end of line)
For calculating size of strings created with triple quotes: EOL (end-of-line) character at the end of
the line is also counted in the size.
For calculating size of strings created with single/double quotes and backslash at the end of the
line: backslashes are not counted in the size of the string.
Use len(<object name>) function to get the size length of an object.
Numeric Literals
Python provides three different numeric types:
a. Integers or int: Positive or negative whole numbers with no decimal point.
i) Decimal: Positive or negative whole numbers with no decimal point.
ii) Octal: Begins with 0o (zero and small o)
iii) Hexadecimal: Begins with 0x or 0X.
b. Floats: Real numbers with a decimal point dividing the integer and fractional parts.
c. Complex numbers: a+bi where a and b can be int or float and i is equal to square root of -1. a
is real part of the number and b is imaginary part.
Boolean Literal
True and False are the only two Boolean literal values in Python.
Page 6 of 46
CLASS-XI COMPUTATIONAL THINKING AND PROGRAMMING UNIT-2
Special Literal None
None literal represents absence of a value. It is also used to indicate the end of lists in Python.
Operators
Operators are tokens that trigger some computation/action when applied to variables and other
objects in an expression. Variables and objects to which the computation is applied are called
operands.
i) Unary Operators: Requires only one d) Identity Operators
operand to operate on. is: Is the identity same?
+ Unary plus is not: Is the identity not
- Unary minus same?
~ Bitwise complement
not Logical negation e) Relational Operators
< Less than
ii) Binary Operators: Requires two > Greater than
operands to operate on. <= Less than or equal to
a) Arithmetic Operators >= Greater than or equal to
+ Addition == Equal to
- Subtraction != Not equal to
* Multiplication
/ Division f) Logical Operators
% Remainder/Modulus and Logical AND
** Exponentiation (raise to or Logical OR
power)
// Floor division g) Assignment Operators
= Assignment
b) Bitwise Operators += Assign sum
& Bitwise AND -= Assign difference
^ Bitwise exclusive OR (XOR) *= Assign product
| Bitwise OR /= Assign quotient
%= Assign remainder
c) Shift Operators **= Assign exponent
<< Shift left //= Assign floor division
>> Shift right
h) Membership Operators
in : whether variable in
sequence
not in : whether variable not
in sequence
Punctuators
Punctuators are symbols that are used in programming languages to organize sentence structures,
and indicate the rhythm and emphasis of expressions, statements and program structure. Examples:
‘, “, #, \, ( ), [ ], { }, @, :, `, = etc.
Page 7 of 46
CLASS-XI COMPUTATIONAL THINKING AND PROGRAMMING UNIT-2
Function
Expressions
An expression is any legal combination of symbols that represents a value. An expression represents
something, which Python evaluates and which then produces a value.
Statements
A statement is a programming instruction that does something i.e. some action takes place. A
statement executes and may or may not yield a value.
Comments
Comments are the additional readable information to clarify the source code. Comments begin with
symbol #.
A comment which starts in the middle of a line after Python code is known as inline comment.
sum = a + b #sums up two numbers a and b
Functions
A function is a code that has a name and it can be reused (executed again) by specifying its name in
the program, where needed.
Creating a Variable
Python variables are created by assigning value of desired type to them, e.g., to create a numeric
variable, assign a numeric value to variable_name.
Multiple Assignments
In Python, assigning a value to a variable means, variable’s label is referring to that value.
Assignments can be done in many ways:
1. Assigning a value to a variable: a = 10
2. Assigning same value to multiple variables: a = b = c = 10
3. Assigning multiple values to multiple variables: x, y, z = 10, 20, 30
Page 8 of 46
CLASS-XI COMPUTATIONAL THINKING AND PROGRAMMING UNIT-2
A variable is defined only when you assign some value to it. Using an undefined variable in an
expression/statement causes an error called NameError.
Dynamic Typing
A variable pointing to a value of a certain type can be made to point to a value/object of different
type. This is called Dynamic Typing.
Dynamic typing is different from static typing. In Static Typing a data type is attached with a variable
when it is defined first and it is fixed. That is, data type of a variable cannot be changed in static
typing whereas there is no such restriction in dynamic typing. Programming languages like C, C++
support static typing.
Use type(<object name>) function to determine the type of an object. Object can be a variable or a
literal etc.
When you try toperform an operation on a data type not suitable for it (e.g. dividing or multiplying a
string), Python raises an error called TypeError.
Reading Numbers
Python offers two functions int ( ) and float ( ) to be used with input ( ) to convert the values
received through input ( ) into int and float type. Example:
age = input(“Enter your age: “)
age = int(age)
or age = int(input(“Enter your age: “)
Ques. Accept three numbers from user and print their sum.
Ques. Accept length and breadth of a rectangle from user and calculate its area.
Ques. Accept a value in kilometres from user and convert and display the equivalent value in meters.
Page 9 of 46
CLASS-XI COMPUTATIONAL THINKING AND PROGRAMMING UNIT-2
CHAPTER-7
DATA HANDLING
INTRODUCTION
Python provides a predefined set of data types for handling the data it uses. Data can be stored in
any of these data types.
DATA TYPES
Python offers built-in data types:
i. Numbers iii. List v. Dictionary
ii. String iv. Tuple
Numbers
Numbers data types are used to store numeric values in Python. The numbers in Python have
following data types:
a. Integers
Integers (signed)
Booleans
b. Floating point numbers
c. Complex numbers
Integers
Integers are whole numbers. They have no fractional parts. They are represented by numeric values
with no decimal point.
Integers (signed): It is the normal integer representation of whole numbers. They can be of
any length; it can only be limited by the memory available. Signed Integers means, they can
both be positive and negative.
Booleans: They represent the truth values False and True. Boolean values False and True
behave like the values 0 and 1 respectively. To get the Boolean equivalent of 0 or 1, you can
type bool(0) or bool(1), Python will return False or True resp.
Complex Numbers
A complex number is a number of the form A+Bj where j is the imaginary number and A and B are
real numbers, equal to the square root of -1 i.e. j2 = -1. Let z=a+bj, then a is the real component and
b is the imaginary component of z.
For e.g. a=0+3.1j has 0 as real component and 3.1 as imaginary component. You can retrieve the two
components using attribute references a.real and a.imag.
Page 10 of 46
CLASS-XI COMPUTATIONAL THINKING AND PROGRAMMING UNIT-2
Range of Python Numbers
Data Type Range
Integers An unlimited range, subject to available memory
Booleans Two values True (1), False (0)
Floating Point Numbers An unlimited range, subject to available memory
Complex Numbers An unlimited range, subject to available memory
Strings
A string data type lets you hold string data, i.e., any number of valid characters into a set of
quotation marks. A string can hold letters, numbers and special characters.
You cannot change the individual letters of a string in place by assignment because strings are
immutable and hence item assignment is not supported. However, you can assign to a string
another string or an expression that returns a string using assignment.
Lists
A list in Python represents a list of comma-separated values of any data type between square
brackets. You can assign a list to a variable. Lists can be changed/ modified (i.e. mutable).
In list also the indexing starts from 0,1,2…. And so on.
Tuples
Lists and Tuples are Python’s compound data types. Tuples are represented as group of comma-
separated values of any data type within parenthesis. Tuples cannot be changed or modified (i.e.
immutable).
Dictionary
The dictionary is an unordered set of comma-separated key: value pairs, within { }, within a
dictionary, no two keys can be same (i.e., there are unique keys within a dictionary)
Page 11 of 46
CLASS-XI COMPUTATIONAL THINKING AND PROGRAMMING UNIT-2
MUTABLE AND IMMUTABLE TYPES
Immutable Types: They can never change their value in place. For e.g. integers, floating point
numbers, Booleans, strings, tuples.
Variable-names are just the references to value-object i.e. data values. The variable-names do not
store values themselves i.e. they are not storage containers.
The id( ) function returns the memory address to which a variable is referencing.
Mutable Types: they are those whose values can be changed in place. For e.g. lists, dictionaries, sets.
Variable Internals
Python is an object oriented language. Python calls every entity that stores any values or any type of
data as an object.
An object is an entity that has certain properties and that exhibit a certain type of behaviour, e.g.
integer values are objects- they hold whole numbers only and they have infinite precision
(properties); they support all arithmetic operations (behaviour).
Every Python object has three key attributes associated to it:
The type of an object: Type determines the operations that can be performed on the object.
Built-in function type( ) returns the type of an object.
The value of an object: It is the data-item contained in the object. For a literal, the value is
the literal itself and for a variable the value is the data-item it is currently referencing.
The id of an object: The id of an object is the memory location of the object. Built-in function
id( ) returns the id of an object. The id( ) of a variable is same as the id( ) of value it is storing.
OPERATORS
The symbols that trigger the operation/action on data are called Operators, and the data on which
operation is being carried out, i.e., the objects of the operation are referred to as Operands.
Arithmetic Operators
+ Addition % Remainder/Modulus
- Subtraction ** Exponentiation (raise to power)
* Multiplication // Floor division
/ Division
These are binary operators, i.e., it requires two values (operands) to calculate the answer.
Operators that act upon two operands are referred to as Binary Operators.
Unary Operators
Requires only one operand to operate on.
+ Unary plus - Unary minus
Unary +:- The operator unary ‘+’ precedes an operand. The operand of the unary + operator must
have arithmetic type and the result is the value of the argument.
Unary - :- The operator unary ‘-’ precedes an operand. The operand of the unary - operator must
have arithmetic type and the result is the negation of its operand’s value. this operator reverses the
sign of the operand’s value.
Page 12 of 46
CLASS-XI COMPUTATIONAL THINKING AND PROGRAMMING UNIT-2
Operation Description Comment
x+=y x=x+y Value of y added to the value of x and then result assigned to x
x-=y x=x-y Value of y subtracted from the value of x and then result assigned to x
x*=y x=x*y Value of y multiplied to the value of x and then result assigned to x
x/=y x=x/y Value of y divides the value of x and then result assigned to x
x//=y x=x//y Value of y does floor division to value of x and then result assigned to x
x**=y x=x**y xy computed and then result assigned to x
x%=y x=x%y Value of y divides the value of x and then remainder assigned to x
Relational Operators
Relational operators determine the relation among different operands. Also known as comparison
operators. If the comparison is true, the relational expression results into the Boolean value True
and to Boolean value False, if the comparison is false.
< Less than >= Greater than or equal to
> Greater than == Equal to
<= Less than or equal to != Not equal to
Rules for comparison:
1. For numeric types, the values are compared after removing trailing zeros after decimal point
from a floating point number.
2. Strings are compared on the basis of ASCII values or ordinal values.
3. Two lists or two tuples are equal if they have same elements in the same order.
Identity Operators
The identity operators are used to check if both the operands refer the same object memory, i.e.
they compare the memory locations of two objects and return True or False accordingly.
Logical Operators
Truth Value Testing
Values with truth value as false Values with truth value as true
None
False (Boolean value False)
Zero of any numeric type, for e.g. 0, 0.0, 0j All other values are considered true.
Any empty sequence, for e.g. ‘ ‘, ( ), [ ]
Any empty mapping, for e.g. { }
Page 13 of 46
CLASS-XI COMPUTATIONAL THINKING AND PROGRAMMING UNIT-2
The or Operator
The or operator can have relational expressions as operands, numbers or strings or lists as operands.
The or operator evaluates to True if either of its operands evaluates to True; False if both operands
evaluates to False.
The or operator will test the second operand only if the first operand is false, otherwise ignore it
Bitwise Operators
Bitwise operators are similar to logical operators, except that they work on smaller scale-on binary
representations of data. Bitwise operators are used to change individual bits in an operand.
Operator Operation Use Description
& Bitwise and op1 & op2 The AND operator compares two bits and generates
a result of 1 if both bits are 1; otherwise, it returns 0.
| Bitwise or op1 | op2 The OR operator compares two bits and generates a
(Inclusive OR) result of 1 if the bits are complementary; otherwise,
it returns 0.
^ Bitwise xor op1 ^ op2 The EXCLUSIVE-OR (XOR) operator compares two
(Exclusive OR) bits and returns 1 if either of the bits are 1; and it
gives 0 if both bits are 0 or 1.
~ Bitwise ~op1 The COMPLEMENT operator is used to invert all of
complement the bits of the operand.
bin( ) is used to get binary representation of a number.
Operator Precedence
Operator Description
Highest
() Parentheses (grouping)
** Exponentiation
~x Bitwise not
+x, -x Positive, negative (unary +, -)
*, /, //, % Multiplication, division, floor division, remainder
+, - Addition, subtraction
& Bitwise and
^ Bitwise XOR
| Bitwise OR
<, <=, >, >=, <>, !=, ==, is, is not Comparisons (Relational operators), identity operators
not x Boolean NOT
and Boolean AND
or Boolean OR
Page 14 of 46
CLASS-XI COMPUTATIONAL THINKING AND PROGRAMMING UNIT-2
Associativity is the order in which an expression (having multiple operators of same precedence) is
evaluated. Almost all the operators have left-to-right associativity except exponentiation (**), which
has right-to-left associativity.
EXPRESSIONS
An expression in Python is any valid combination of operators, literals, and variables.
The expressions can be of any type: arithmetic expression, string expression, relational expression,
logical expression, compound expression etc. The types of operators and operands used in an
expression determine the expression type.
1. Arithmetic Expressions: Involves numbers (integers, floating point numbers, and complex
numbers) and arithmetic operations.
2. Relational Expressions: Involves literals and variables of any valid type and relational
operators.
3. Logical Expressions: Involves literals and variables of any valid type and logical operators.
4. String Expressions: Two string operators + and *, when combined with string operands and
integers, form string expressions. + is the concatenation operator and * is the replication
operator.
Ques. What will be the final result and final data type?
a. a,b=3,6 b. a,b=3,6 c. a,b=3,6
c=b/a c=b//a c=b%a
Ques. What will be the output of the following statement when the inputs are:
i. a=10, b=23, c=23 ii. a=23, b=10, c=10
print(a<b)
print(b<=c)
print(a<b<=c)
Type Casting
The explicit type conversion is user defined conversion that forces an operand to be of specific type.
It is also called Type Casting. It is performed by <type>( ) function of appropriate data type
Examples of data conversion functions are: int ( ), float( ), complex( ), str( ), bool( ).
Assigning a value to a type with a greater range poses no problem; however, assigning a value of
larger data type to a smaller data type may result in losing some data.
Page 15 of 46
CLASS-XI COMPUTATIONAL THINKING AND PROGRAMMING UNIT-2
Python’s standard library provides a module math for math related functions that work with all
number types except for complex numbers. To work with functions of math module, you need to
import it first as: import math
Then you can use math library’s functions as math.<function-name>
Page 16 of 46
CLASS-XI COMPUTATIONAL THINKING AND PROGRAMMING UNIT-2
CHAPTER-8
CONDITIONAL AND ITERATIVE STATEMENTS
Empty Statement
The simplest statement is the empty statement i.e. a statement which does nothing. In Python an
empty statement is pass statement.
The pass statement of Python is a do nothing statement i.e. empty statement or null operation
statement. It is useful in those instances where the syntax of the language requires the presence of a
statement but where the logic of the program does not.
Simple Statement
Any single executable statement is a simple statement in Python. For e.g.
name = input(“your name”)
print(name)
Compound Statement
A compound statement represents a group of statements executed as a unit. The compound
statements of Python are written in a specific pattern as shown below:
<compound statement header>:
<indented body containing multiple simple and/or compound statements>
That is, a compound statement has:
A header line which begins with a keyword and ends with a colon.
A body consisting of one or more Python statements, each indented inside the header line.
All statements in the body are at the same level of indentation.
Sequence
The sequence construct means the statements are being executed sequentially. Every program
begins with the first statement of program. Each statement in turn is executed. When the final
statement of program is executed, the program is done.
Selection
The selection construct means the execution of statements depending upon a condition-test. If a
condition evaluates to True, a course-of-action (a set of statements) is followed otherwise another
set of instructions is followed. Selection construct is also called decision construct because it helps in
making decision about which set-of-statements is to be executed.
Iteration (Looping)
The iteration constructs mean repetition of a set-of-statements depending upon a condition-test. Till
the time a condition is True (or False depending upon the loop), a set-of-statements are repeated
Page 17 of 46
CLASS-XI COMPUTATIONAL THINKING AND PROGRAMMING UNIT-2
again and again. As soon as the condition becomes False (or True), the repetition stops. The iteration
construct is also called looping construct.
The set-of-statements that are repeated again and again is called the body of the loop. The condition
on which the execution or exit of the loop depends is called the exit condition or test-condition.
An algorithm is a set of ordered and finite steps (the subtasks) to solve a given problem.
Flowcharts
A flowchart is a graphical representation of an algorithm. A flowchart shows different subtasks with
different symbols.
Process
Data
Decision
Start/End
Arrows
Use Process symbol for any type of computation and internal operations like initialization,
calculation etc.
Use Decision symbol when there are two or more choices among which you need to
execute/choose one.
An Arrow is a connector that shows relationships between the representative shapes.
Use Data symbol for Input/output (I/O) operation (taking input and showing output).
Use Start/End symbol at the beginning and ending of flowchart.
Page 18 of 46
CLASS-XI COMPUTATIONAL THINKING AND PROGRAMMING UNIT-2
The if-else Statement
The block below if gets executed if the condition evaluates to true and the block below else gets
executes if the condition evaluates to false.
if <conditional expression>:
statement
[statements]
else:
statement
[statements]
An if-else in comparison to two successive if statements has less number of condition-checks i.e.
with if-else, the condition will be tested once in contrast to two comparisons if the same code is
implemented with two successive ifs.
Ques. Program to read two numbers and an arithmetic operator and displays the computed result.
Page 19 of 46
CLASS-XI COMPUTATIONAL THINKING AND PROGRAMMING UNIT-2
The nested if Statement
A nested if is an if that has another if in its if’s body or in elif’s body or in its else’s body.
Form 1: if inside if’s body Form 2: if inside elif’s body
if <conditional expression>: if <conditional expression>:
if <conditional [statements]
expression>: elif <conditional expression>:
[statements] if <conditional
else: expression>:
[statements] [statements]
elif <conditional expression>: else:
statement [statements]
[statements] else:
else: statement
statement [statements]
[statements]
Form 3: if inside else’s body Form 4: if inside if’s as well as else’s or elif’s
if <conditional expression>: body, i.e. multiple ifs inside
[statements] if <conditional expression>:
elif <conditional expression>: if <conditional
[statements] expression>:
else: [statements]
if <conditional else:
expression>: [statements]
[statements] elif <conditional expression>:
else: if <conditional
[statements] expression>:
[statements]
else:
[statements]
else:
if <conditional
expression>:
[statements]
else:
[statements]
Ques. Program that reads three numbers (integers) and prints them in ascending order.
Ques. Program to print whether a fgiven character is an uppercase or a lowercase character or a
digit or any other character.
Ques. Program to calculate and print roots of a quadratic equation: ax2 + bx +c = 0 (a!=0)
Storing Conditions
Sometimes the conditions being used in code are complex and repetitive. In such cases, to make
your program more readable, you can use named conditions i.e. you can store conditions in a name
and then use that named conditional in the if statements.
You can use named conditions in if statements to enhance readability and reusability of conditions.
LOOPS
To carry out repetitive tasks, Python provides iterative/looping statements:
Conditional loop while (condition based loop)
Counting loop for (loop for a given number of times)
Page 20 of 46
CLASS-XI COMPUTATIONAL THINKING AND PROGRAMMING UNIT-2
THE range( ) FUNCTION
The range( ) function of Python generates a list which is a special sequence type. A sequence in
Python is a succession of values bound together by a single name. some Python sequence types are:
strings, lists, tuples etc.
range(<lower limit>, <upper limit>)
The function in the form range(l, u) will produce a list having values starting from l, l+1, l+2,…(u-1) (l
and u being integers).
range(<lower limit>, <upper limit>, <step value>)
range(<number>)
for loop ends when the loop is repeated for the last value of the sequence.
The for loop repeats n number of times, where n is the length of sequence given in for-loop’s
header.
To cancel the running of an endless loop, you can press CTRL+C keys anytime during its endless
repetition to stop it.
Since in a while loop, the control in the form of condition-check is at the entry of the loop (loop is
not entered, if the condition is false), it is an example of an entry-controlled loop.
An entry-controlled loop is a loop that controls the entry in the loop by testing a condition.
Page 22 of 46
CLASS-XI COMPUTATIONAL THINKING AND PROGRAMMING UNIT-2
A loop can end in two ways:
1. If the while’s condition results in false or for loop executes with last value of the sequence
(NORMAL TERMINATION).
2. If during the loop execution, break statement is executed. In this case, even if the condition is
true or the for has not executed all the values of sequence, the loop will still terminate.
Ques. Program to implement ‘guess the number’ game. Python generates a number randomly in the
range[10,50]. The user is given 5 chances to guess a number in the range 10<=number<=50.
If the user’s guess matches the number generated, Python displays “You win” and the loop
terminated without completing the five iterations.
If, however, cannot guess the number in five attempts, Python displays “You lose”.
Hence to conclude, break statement is used to terminate all pending iterations of the loops; and
continue terminates just the current iteration, loop will continue with rest of the iterations.
Ques. Program to illustrate the difference between break and continue statements.
The loop-else suite executes only in the case of normal termination of loop.
The else clause works identically in while-loop, i.e. executes if the test-condition goes false and not in
case of break statement’s execution.
Ques. Program to input some numbers repeatedly and print their sum. The program ends when the
user say no more to enter (normal termination) or program aborts when the number entered is less
than zero.
Ques. Program to input a number and test if it is a prime number.
Sometimes the loop is not entered at all, reason being empty sequence in a for loop or test-
condition;s result as false before entering in the while loop. In these cases, the body of the loop is
not executed but loop-else clause will still be executed.
Nested Loops
A loop may contain another loop in its body. This form of a loop is called nested loop. But in a nested
loop, the inner loop must terminate before the outer loop.
The value of outer loop variable will change only after the inner loop is completely finished.
Page 23 of 46
CLASS-XI COMPUTATIONAL THINKING AND PROGRAMMING UNIT-2
1. for outer in range(5,10,4):
for inner in range(1, outer, 2):
print(outer, inner)
2. for a in range(3):
for b in range(5,7):
print(“for a-“, a, ”b now is”, b)
3. for a in range(3):
for b in range(5,7):
print(“*”, end=’ ‘ )
print( )
4. for a in range(3):
for b in range(5,8):
print(“*”, end=’ ‘)
print( )
Page 24 of 46
CLASS-XI COMPUTATIONAL THINKING AND PROGRAMMING UNIT-2
CHAPTER-9
STRING MANIPULATION
INTRODUCTION
Python strings are characters enclosed in quotes of any type-single quotation marks, double
quotation marks, and triple quotation marks. An empty string is a string that has 0 characters.
Python strings are immutable. Each character has a unique index. The indexes of a string begin from
0 to (length-1) in forward direction and -1, -2 …… -length in backward direction.
TRAVERSING A STRING
Traversing refers to iterating through the elements of a string, one character at a time. Using the
indexes you can traverse a string.
name="superb"
for ch in name:
print(ch,'-',end="")
STRING OPERATORS
String Concatenation Operator +
The + operator creates a new string by joining the two operand strings. For e.g. ‘123’ + ‘abc’ will
result into 123abc. Python creates a new string in the memory by storing individual characters of
first string operand followed by the individual characters of second string operand. Original strings
are not modified as strings are immutable; new strings can be created but existing strings cannot be
modified.
The + operator has to have both operands of the same type either of number types (for addition) or
of string types (for concatenation).
Membership Operators
1. in operator: Returns True if a character or a substring exists in the given string; False
otherwise.
2. not in operator: Returns True if a character or a substring does not exists in the given string;
False otherwise.
Both membership operators require two operands of same type.
Page 25 of 46
CLASS-XI COMPUTATIONAL THINKING AND PROGRAMMING UNIT-2
Comparison Operators
Comparison operators are relational operators (<, <=, >, >=, ==, !=), can be applied to strings also.
Python compares two strings through relational operators using character-by-character comparison
of their Unicode value.
Characters Ordinal Values
‘0’ to ‘9’ 48 to 57
‘A’ to ‘Z’ 65 to 90
‘a’ to ‘z’ 97 to 122
STRING SLICES
The term ‘string slice’ refers to a part of the string, where strings are sliced using a range of indices.
The string slice refers to a part of the string s[start:end] that is the elements beginning at start and
extending up to but not including end. In a string slice, the character at last index (the one following
colon ( : ) is not included in the result. If begin-index is missing, it will consider as 0 (the first index)
and for missing last value, it will consider the length of the string.
For any index n, s[:n]+s[n:] will give the original string s. n can be either positive or negative.
We can give a third (optional) index in string slice. For e.g. word[1:6:2], word[-7,-3,3], word[::-2],
word[::-1].
Index out of bounds causes error with strings but slicing a string outside the bounds does not cause
error but prints an empty string.
Reason behind this: when you use an index, you are accessing a constituent character of the string,
thus the index must be valid and out of bounds index causes error as there is no character to return
from the given index. But slicing always returns a subsequence and empty sequence is a valid
sequence. Thus when you slice a string outside the bounds, it still can return empty subsequence
and hence Python gives no error and returns empty subsequence.
1. string.capitalize( ) Returns a copy of the string with its first character capitalized.
2. String.find(sub[,start[,end]]) Returns the lowest index in the string where the substring sub
is found within the slice range if start and end. Returns -1 if sub is not found.
3. string.alnum( ) Returns True if the characters in the string are alphanumeric (alphabets or
numbers) and there is at least one character, False otherwise.
Page 26 of 46
CLASS-XI COMPUTATIONAL THINKING AND PROGRAMMING UNIT-2
4. string.isalpha( ) Returns True if all characters in the string are alphabetic and there is at least
one character, False otherwise.
5. string.islower( ) Returns True if all cased characters in the string are in lowercase. There
must be at least one cased character. It returns False otherwise.
6. string.isspace( ) Returns True if there are only whitespace characters in the string. There
must be at least one character. It returns False otherwise.
7. string.isdigit( ) Returns True if all the characters in the strings are digits. There must be at
least one character, otherwise it returns False.
8. string.isupper( ) Returns True if all cased characters in the string are in uppercase. There
must be at least one cased character. It returns False otherwise.
9. string.lower( ) Returns a copy of the string converted to lowercase.
10. string.upper( ) Returns a copy of the string converted to uppercase.
Page 27 of 46
CLASS-XI COMPUTATIONAL THINKING AND PROGRAMMING UNIT-2
CHAPTER-10
EXECUTION OF A PROGRAM
INTRODUCTION
1. Programmers write programs in a specific programming language like C, C++, Java, Python etc.
2. But computer cannot directly understand what the programmers have written because
computers understand a different language called machine language only.
3. Thus, for a computer to execute a program, it is important that the program must be converted
into machine code.
1. Pre-processing Phase
i) This phase removes comments from the source code.
ii) For languages like C/C++ that have pre-processor directives, this phase carries out all pre-
processor directives such as macro substitution, inclusion of header files etc.
iii) Modules imported in a program using import command, are also added to the code during
this phase.
iv) At the end of this phase, the source code is converted to just complete code that has
nothing extra and nothing yet to be added/ expanded.
2. Compilation Phase
This phase is further sub-divided into sub-phases:
a. Analysis [Front end phase] b. Synthesis [Back end phase]
Page 28 of 46
CLASS-XI COMPUTATIONAL THINKING AND PROGRAMMING UNIT-2
a. Analysis Phase
i) In this phase the compiler identifies all the tokens of the source code and their
requirements.
ii) Using this information, the compiler creates a special type of table, called the symbol
table that contains the details of all the tokens in the source code.
iii) This sub-phase is also called front-end phase of compilation.
b. Synthesis Phase
i) In this phase the compiler parses the code and generates syntax tree, analysing the syntax
of the source code.
ii) A syntax tree (or Abstract Syntax Tree) is a tree representation of syntactic structure of
source code.
iii) During both of these phases if the syntax and semantic rules of the programming language
are violated in source code, the compiler generates and error, with the line number of the
source code.
iv) Once the code is error free, the compiler converts into intermediate code that is in the
form of assembly level instructions.
3. Assembly Phase
This phase receives the assembly level instructions and then converts it into object code,
which is a form of machine code. This phase does the same work that an assembler does, i.e.
converts assembly code to binary code.
4. Linking
i) The object code received by this phase is very much binary code, but still computer cannot
execute it because linking of important libraries is yet to be done. This phase does this.
ii) The part of the computer which performs the linking of libraries is called Linker.
iii) In this phase, with the help of OS, all memory references are resolved and code is
converted to a form which requires nothing else to run: it has everything in it to execute
itself. That is, the code has become executable (.exe file) now.
5. Loader
i) The loader is a part of compiler that loads the computer executable module into memory
for execution.
ii) Now the computer can run the executable file without requiring any other software.
Hence the compiler is also not needed to run the executable file.
Interpretation Process
i) Unlike compiler (which works with whole program at all steps), the interpreter focuses on
one line of code or one unit of code at a time.
ii) The interpreter analyses one line of code, converts into object code, adds in required
libraries, if any and runs it.
iii) The first line of code is executed, even before the second line of code is converted to object
code.
iv) Once the interpreter finishes running one line of code successfully then only it will actually
move on to the next line.
Errors in a Program
An error or a bug is anything in the code that prevents a program from compiling and running
correctly. There are 3 types of errors: Compile-time errors, run-time errors and logical errors.
Page 29 of 46
CLASS-XI COMPUTATIONAL THINKING AND PROGRAMMING UNIT-2
Compile-Time Errors
Errors that occur during compile-time are compile-time errors. When a program compiles, its source
code is checked for whether it follows the programming language’s rules or not.
1. Syntax Errors: Syntax refers to formal rules governing the construction of valid statements in
a language. Syntax errors occur when rules of a programming language are misused.
2. Semantics Errors: Semantics refers to the set of rules which give the meaning of a statement.
Semantics Errors occurs when statements are not meaningful.
Run-Time Errors
Errors that occur during the execution of a program are run-time errors. Some run-time errors stop
the execution of the program which is then called program “crashed” or “abnormally terminated”.
Logical Errors
Sometimes, even if you don’t encounter any error during compile-time and run-time, your program
does not provide the correct result. This is because of the programmer’s mistaken analysis of the
program being solved. Such errors are logical errors.
Some examples of Logical runtime errors:
using the wrong variable name
indenting a block to the wrong level
using integer division instead of floating-point division
getting operator precedence wrong
making a mistake in a Boolean expression
off-by-one, and other numerical errors
Page 30 of 46
CLASS-XI COMPUTATIONAL THINKING AND PROGRAMMING UNIT-2
CHAPTER-11
LIST MANIPULATION
INTRODUCTION
Python lists are containers that are used to store a list of values of any type. Unlike other variables
Python lists are mutable (modifiable) i.e. you can change the elements of a list in place; Python will
not create a fresh list when you make changes to an element of a list.
Types of Lists
1. Empty List 2. Long Lists 3. Nested List
Accessing Lists
1. Lists are sequences just like strings.
2. Lists also index their individual elements, just like strings do.
3. Lists also have forward indexing and backward indexing.
4. Lists are stored in memory exactly like strings, except that because some of their objects are
larger than others, they store a reference at each index instead of single character as in
strings.
Difference between Strings and Lists: Strings are not mutable, while lists are.
Traversing a List
Traversal of a sequence means accessing and processing each element of it. The for loop makes it
easy to traverse or loop over the items in a list.
1. for <item> in <List>: 2. for index in range(len(L)):
process each item here process L[index] here
Ques. Program to print elements of a list [‘q’, ‘w’, ‘e’, ‘r’, ‘t’, ‘y’] in separate lines along with
element’s both indexes (positive and negative).
Page 31 of 46
CLASS-XI COMPUTATIONAL THINKING AND PROGRAMMING UNIT-2
Comparing Lists
We can compare two lists using standard comparison operators of Python i.e. <, >, ==, != etc. Python
internally compares individual elements of lists (and tuples). To compare equal, each corresponding
element must compare equal and the two sequences must be of same type i.e. having comparable
type of values else Python will raise an error.
LIST OPERATIONS
1. Joining Lists: The concatenation operator +, when used with two lists, joins two lists.
2. Repeating or Replicating Lists: We can use * operator to replicate a list specified number of
times. We can only use an integer with a * operator when trying to replicate a list.
3. Slicing the Lists: List slices are the sub part of a list extracted out. You can use indexes of list
elements to create list slices as: seq = L[start:stop]
For start and stop given beyond limits in a list slice, Python simply returns the elements that fall
between specified boundaries, if any, without raising any error.
L[start: stop: step] creates a list slice out of list L with elements falling between indexes start and
stop, not including stop, skipping step-1 elements in between.
Ques. Extract two list-slices out of a given list of numbers. Display and print the sum of elements of
first list-slice which contains every other element of the list between indexes 5 to 15. Program
should also display the average of elements in second list slice that contains every fourth element of
the list. The given list contains numbers from 1 to 20.
If we use del <lstname>, it will delete all the elements and the list object too. After this,
no object by the name lst would be existing.
We can also use pop( ) method to remove single element, not list slices. The pop( ) method removes
an individual item and returns it.
The del statement and the pop method do almost the same thing, except that pop method also
returns the removed item along with deleting it from the list. List.pop(<index>)
Page 32 of 46
CLASS-XI COMPUTATIONAL THINKING AND PROGRAMMING UNIT-2
The pop( ) method is useful only when you want to tore the element being deleting for later use.
The extend ( ) takes a list as an argument and appends all of the elements of the argument list to
the list on which extend( ) is applied.
b. After append( ), the length of the list will increase by 1 only; while after extend( ), the length
of the list will increase by the length of the inserted list.
Page 33 of 46
CLASS-XI COMPUTATIONAL THINKING AND PROGRAMMING UNIT-2
7. The clear method
This method removes all the item from the list and the list becomes empty list after this function.
This function returns nothing. List.clear( )
Unlike del <lstname> statement, clear( ) removes only the elements and not the list object. After
clear( ), the list object still exists as an empty list.
Ques. Program to find minimum element from a list of element along with its index in the list.
Ques. Program to calculate mean of a given list of numbers.
Ques. Program to search for an element in a given list of numbers.
Ques. Program to count frequency of a given element in a list of numbers.
Page 34 of 46
CLASS-XI COMPUTATIONAL THINKING AND PROGRAMMING UNIT-2
CHAPTER-12
TUPLES
INTRODUCTION
1. The Python tuples are sequences that are used to store a tuple of values of any type.
2. Tuples are immutable i.e. you cannot change the elements of a tuple in place; Python will create
a fresh tuple when you make changes to an element of a tuple.
Creating Tuples
Python tuples are sequences that are used to store a tuple of values of any type separated by
commas inside parentheses or round brackets.
1. The Empty Tuple
The empty tuple is ( ). It is the tuple equivalent of 0 or ‘’. T = tuple( ) will create an
empty tuple.
3. Long Tuples
If a tuple contains many elements, then to enter such long tuples, you can split it across
several lines.
4. Nested Tuples
If a tuple contains an element which is a tuple itself then it is called nested tuple.
t1 = (1, 2, (3, 4))
We can use this method for creating tuples of single characters or single digits via keyboard input.
a. t1 = tuple(input(“Enter tuple elements”))
With tuple( ) around input( ), if you do not put parenthesis, it will create a tuple using individual
characters as elements.
Page 35 of 46
CLASS-XI COMPUTATIONAL THINKING AND PROGRAMMING UNIT-2
Tuples are stored in memory exactly like strings, except that because some of their objects are larger
than others, they store a reference at each index instead of singe character as in strings. Each of the
individual items of the tuple are stored somewhere else in memory.
Membership Operators in and not in tells whether the element is present in the tuple or
not.
Concatenation and Replication operators + and *
While accessing the tuple elements, if you pass in a negative index, Python adds the length of the
tuple to the index to get element’s forward index.
Traversing a Tuple
Traversal of a sequence means accessing and processing each element of it.
for <item> in <Tuple>: for i in range(len(t)):
process each item here print(t[i])
Ques. Program to print elements of a tuple (“Hello”, “Isn’t”, “Python”, “fun”, “?”) in separate lines
along with elements both indexes (positive and negative).
TUPLE OPERATIONS
1. Joining Tuples: The concatenation operator is used to join two tuples. The + operator when
used with tuples requires that both the operands must be of tuple types.
2. Replicating Tuples: Like strings and lists, you can use * operator to replicate a tuple specified
number of times.
3. Slicing the Tuples: Tuple slices are the sub pats of the tuple extracted out. The tuple slice is a
tuple in itself. Seq = T[start : stop]
Seq = T[start : stop : step]
T[::step], T[start::step]
We can use the + and * operators with tuple slices too.
Comparing Tuples
For comparing two tuples, you can using use comparison operators i.e. <, >, ==, != etc. For
comparison purposes, Python internally compares individual elements of two tuples, applying all the
comparison rules.
Unpacking Tuples
Creating a tuple from individual values is called packing and its reverse i.e. creating individual values
from a tuple’s elements is called unpacking.
<var1>, <var2>, <var3>, <var4>, … = t
Page 36 of 46
CLASS-XI COMPUTATIONAL THINKING AND PROGRAMMING UNIT-2
Deleting Tuples
Since the Python tuples are immutable so we cannot delete individual elements of a tuple using del
statement. But we can delete a complete tuple with del statement as del <tuple_name>
Note: max( ) and min( ) can be applied on sequences like lists/tuples etc. will return a maximum/
minimum value ONLY IF the sequence contains values of same type.
tuple( ) can receive argument of sequence types only, i.e., either a string or a list or a
dictionary. Any other type of value will lead to an error.
b. Using the constructor functions of lists and tuples i.e. list( ) and tuple( )
1. Convert the tuple to list using list( )
2. Make changes in the desired element in the list.
3. Create a tuple from the modified list with tuple( ).
Page 37 of 46
CLASS-XI COMPUTATIONAL THINKING AND PROGRAMMING UNIT-2
CHAPTER-13
DICTIONARIES
INTRODUCTION
Python offers many different ways to organize collections (i.e. a bunch of values in a single variable)
of data items, such as strings, lists, dictionaries, tuples etc.
Creating a Dictionary
<dictionary-name> = {<key> :< value>, <key> :< value>…}
Internally, dictionaries are indexed (i.e. arranged) on the basis of keys.
Dict1 = { } #Empty dictionary with no elements
Dictionaries are also called associative arrays or mappings or hashes.
Note: Keys of a dictionary must be of immutable types, such as string, a number, a tuple
(containing only immutable entries)
Traversing a Dictionary
Traversal of a collection means accessing and processing each element of it.
for <item> in <dictionary>:
process each item
The loop variable will be assigned the keys of dictionary one by one, which can be used inside the
body of the loop.
Dictionaries are unordered set of elements, the printed order of elements is not same as the order
you stored the elements in it.
The only similarity between a list and a dictionary is that they both are mutable.
Ques. Write a program to create a phone dictionary for all your friends and then print it.
Page 38 of 46
CLASS-XI COMPUTATIONAL THINKING AND PROGRAMMING UNIT-2
You may write <dictionary>.keys( ) and <dictionary>.values( ) to see all the keys
and values in the dictionary in one go. These functions returns all the keys and values defined in a
dictionary in the form of a sequence which can be converted to a list using list( ) method.
Characteristics of a Dictionary
1. Unordered Set
A dictionary is an unordered set of key: value pairs. Its values can contain references to any
type of object.
2. Not a Sequence
Unlike a string, list and tuple, a dictionary is not a sequence because it is unordered set of
elements. The sequences are indexed by a range of ordinal numbers. Hence they are ordered
but a dictionary is an unordered collection.
5. Mutable
Dictionaries are mutable. We can change the value of a certain key “in place” using the
assignment statement as: <dictionary> [<key>] = <value>
We can add a new key: value pair also using the above syntax but the key should be unique.
Using dict( ) method to create a dictionary takes a longer time compared to traditional method of
enclosing values in {}. Thus, it should be avoided until it becomes a necessity.
Nesting Dictionaries
You can also add dictionaries as values inside a dictionary. Storing a dictionary inside another
dictionary is called nesting of dictionaries.
Ques. A dictionary contains details of two workers with their names as keys and other details in the
form of dictionary as value. Write a program to print the workers’ information in records format.
Employees = {'john':{'age':25,'salary':10000},'diya':{'age':26,'salary':20000}}
for key in Employees:
print("Employee", key,':')
print('Age:',str(Employees[key]['age']))
print('Salary:',str(Employees[key]['salary']))
Ques. Write a program to create a dictionary containing names of competition winner students as
keys and number of their wins as values.
n = int(input('How many students?: '))
CompWinners = {}
for a in range(n):
key=input('Name of the students: ')
value=int(input('Number of competitions won: '))
CompWinners[key]=value
print('The dictionary now is: ')
print(CompWinners)
Page 40 of 46
CLASS-XI COMPUTATIONAL THINKING AND PROGRAMMING UNIT-2
Deleting Elements from a Dictionary
1. del <dictionary>[<key>]
2. <dictionary>.pop(<key>)
The pop( ) method will not only delete the key: value pair for mentioned key but also return
the corresponding value. if you try to delete a key which does not exist, the Python returns
an error, KeyError.
The split( ) works on string type data and up a string into words and creates a list out of it.
By default, split( ) breaks up a text based on white spaces, but you can give a separator character
also.
Page 41 of 46
CLASS-XI COMPUTATIONAL THINKING AND PROGRAMMING UNIT-2
2. The clear( ) method
This method removes all items from the dictionary and the dictionary becomes empty
dictionary post this method. It takes no argument and returns no value.
<dictionary>.clear( )
This clear method does not delete the dictionary; it just deletes all the elements inside the
dictionary. If however, you want to delete the dictionary then you can use del statement.
del <dictionary>
As the items( ) function returns a sequence of (key value) pairs, you can write a loop having
two variables to access to access key value pairs.
seq = empl.items( )
for key, val in seq:
print(key, val)
Page 42 of 46
CLASS-XI COMPUTATIONAL THINKING AND PROGRAMMING UNIT-2
CHAPTER-14
UNDERSTANDING SORTING
WHAT IS SORTING?
Sorting means arranging the elements in a specific order i.e. either in increasing/ascending or
decreasing/descending order.
BUBBLE SORT
The basic idea of bubble sort is to compare two adjoining values and exchange them if they are not
in proper order. In every pass, the heaviest element settles at its appropriate position in the bottom.
Page 43 of 46
CLASS-XI COMPUTATIONAL THINKING AND PROGRAMMING UNIT-2
Outer for loop repeats n times (because n is 7)
Operations in Line 4..7 x 7 times
= Line 4 = 1 op
= Line 5..7 = Inner for loop
Inner for loop is repeated (n-i-1) times
(so 6 times first time, 5 times second time, 4 times third time and so on)
= Line 5 = 1 op
+Line 6 = 1 op
+ Line 7 = 1 op = 3 ops
Inner for loop performs 3 operations in single iteration
So putting this value in eq.(1), total operations = 3 ops + 70 ops + 1 op = 74 ops approx..
So, when n = 7, bubble sort takes 74 operations
When n = 8, bubble sort takes 96 operations
When n = 9, bubble sort takes 121 operations
When n = 6, bubble sort takes 55 operations
When n = 5, bubble sort takes 39 operations
Pass 1 2 3 … n-1
Comparisons n-1 n-2 n-3 … 1
The no. of swapping will vary depending upon the elements of the sequence:
In the best case, i.e. when all the elements of the sequence are already sorted, no swapping
will take place. = n2 comparisons + 0 swapping = n2 ops
In the worst case, i.e. when all the elements are in opposite order, every comparison will result
into a swapping. =n2 comparisons + n2 swapping = 2n2 ops
We determine the efficiency of a program using the highest degree term in the expression for
number of operations. The lesser degree terms do not really matter.
So programs with lesser degree in number of operations are considered more efficient program hat
programs with higher degree.
Page 44 of 46
CLASS-XI COMPUTATIONAL THINKING AND PROGRAMMING UNIT-2
INSERTION SORT
1. Insertion sort is a sorting algorithm that builds a sorted list one element at a time from the
unsorted list by inserting the element at its correct position in sorted list.
2. It virtually divided the list of elements in two sub-lists: sorted sub-list and unsorted sub-list.
3. Initially the entire list is unsorted sub-list and sorted sub-list is empty.
4. Then it takes one element from the unsorted sub-list and inserts it into the correct position in
the sorted sub-list.
5. Insertion sort is not very efficient on large datasets; it is an efficient sorting technique for small
datasets.
6. The insertion sort passes through the list only once.
Number of Operations
There are two costly operations, comparisons and swapping/exchanges.
The operations that affect the efficiency of insertion sort in terms of number of operations are:
1. The comparison operation in the inner loop
2. The exchange operation in the inner loop
Let us calculate number of operations of insertion sort with respect to each of these two operations
for a sequence having N number of elements.
i. The number of comparisons:
During the first iteration of the outer loop, in the inner loop, there is 1 comparison.
During the second iteration of the outer loop, there are at most 2 comparisons.
….
During the (N-1) th iteration of the outer loop, there are at most (N-1) comparisons.
Page 45 of 46
CLASS-XI COMPUTATIONAL THINKING AND PROGRAMMING UNIT-2
ii. The number of exchanges:
During the first iteration of the outer loop, there is at most 1 exchange.
During the second iteration of the outer loop, there are at most 2 exchanges.
…
During the (N-1)th iteration of the outer loop, there are at most (N-1) exchanges.
The maximum no. of exchanges = 1 + 2+ … + (N-2) + (N-1) = (N x (N-1))/2 = (N2-N)/2 < N2
That means there can be maximum N2 exchanges in insertion sort.
Note that the number of comparisons and exchanges depends on the sequence to be sorted, that is
insertion sort is sensitive to input sequence.
In the best case, the sequence has all the elements in the desired sorted order.
In the worst case, no element at the correct position i.e., sequence is completely reverse
order.
In the average case, the sequence will have a mix of these two: some elements are correct
position and some are not.
In the best case, when the sequence is already in desired sorted order, there will be
maximum N-1 number of comparisons and exchanges. (i.e. N-1 ops)
In the worst case, there will be maximum possible number (<N 2) of comparisons and
exchanges. (i.e. <N2 ops)
Calculating number of operations is always beneficial for determining the efficiency of an algorithm,
especially in cases where we have an option to choose from two or more algorithms that can
perform same task.
2. Insertion sort has been a preferred choice for sorting small datasets. It is easy to implement
and it does not require additional memory; it can be fat if the data is almost nearly sorted.
3. Practical usage of insertion sort is in sorting of answer sheets.
Page 46 of 46