0% found this document useful (0 votes)
3 views

chapter 2

The document provides an introduction to Python, describing it as a high-level, interpreted, and open-source programming language with a clear syntax and rich libraries. It outlines the steps for problem-solving, including analyzing the problem, developing algorithms, coding, and testing/debugging. Additionally, it covers the representation of algorithms through flowcharts and pseudocode, and discusses key concepts such as variables, identifiers, and execution modes in Python.

Uploaded by

ASHOKA
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

chapter 2

The document provides an introduction to Python, describing it as a high-level, interpreted, and open-source programming language with a clear syntax and rich libraries. It outlines the steps for problem-solving, including analyzing the problem, developing algorithms, coding, and testing/debugging. Additionally, it covers the representation of algorithms through flowcharts and pseudocode, and discusses key concepts such as variables, identifiers, and execution modes in Python.

Uploaded by

ASHOKA
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 117

5.

1 INTRODUCTION TO PYTHON

A program written in a high-level language is called source code. Python uses an


interpreter to convert its instructions into machine language, so that it can be understood
by the computer. An interpreter processes the program statements one by one, first
translating and then executing. This process is continued until an error is encountered
or the whole program is executed successfully

5.1.1 Features of Python

• Python is a high level language. It is a free and open source language.


• It is an interpreted language, as Python programs are executed by an
interpreter.
• Python programs are easy to understand as they have a clearly defined
syntax and relatively simple structure.
• Python is case-sensitive. For example, NUMBER and number are not
same in Python.
• Python is portable and platform independent, means it can run on various
operating systems and hardware platforms.
• Python has a rich library of predefined functions.
• Python is also helpful in web development. Many popular web services
and applications are built using python.
• Python uses indentation for blocks and nested blocks.

5.1.2 Working with Python

To write and run (execute) a Python program, we need to have a Python interpreter
installed on our computer or we can use any online Python interpreter.
5.1.3 Execution Modes

There are two ways to use the Python interpreter:

a) Interactive mode

b) Script mode

Interactive Mode:

Without passing python script file to the interpreter, directly execute code to Python
(Command line).
Example:
>>>6+3
Output: 91. INTRODUCTION

Computers are used for solving various day-to-day problems.

It is pertinent to mention that computers themselves cannot solve a problem.

Precise step-by-step instructions should be given by us to solve the problem.

Thus, the success of a computer in solving a problem depends on how correctly and
precisely we define the problem, design a solution (algorithm) and implement the
solution (program) using a programming language.

Thus, problem solving is the process of identifying a problem, developing an algorithm


for the identified problem and finally implementing the algorithm to develop a
computer program.

2. Steps for Problem Solving

There are four steps in problem solving


Analysing the problem

Developing an Algorithm

Coding

Testing and Debugging

2.1 Analysing the problem

It is important to clearly understand a problem before we begin to find the solution for
it.

If we are not clear as to what is to be solved, we may end up developing a program


which may not solve our purpose.

By analysing a problem, we would be able to figure out what are the inputs that our
program should accept and the outputs that it should produce.

2.2 Developing an Algorithm

The solution for a problem is represented in step by step procedure called an algorithm.

For a given problem, more than one algorithm is possible and we have to select the
most suitable solution.

2.3 Coding

After finalising the algorithm, we need to convert the algorithm into the format which
can be understood by the computer to generate the desired solution.

2.4 Testing and Debugging

The program created should be tested on various parameters.

The program should meet the requirements of the user.

In the presence of syntactical errors, no output will be obtained.

In case the output generated is incorrect, then the program should be checked for logical
errors, if any.
3. Algorithm

Algorithm is the step by step procedure for solving the problem. Suppose following are
the steps required for an activity ‘riding a bicycle’:

remove the bicycle from the stand,

sit on the seat of the bicycle,

start peddling,

use breaks whenever needed and

stop on reaching the destination.

Example:

Algorithm to find square of a number.

Step 1: Input a number and store it to num

Step 2: Compute num * num and store it in square

Step 3: Print square

3.1 Why do we need an Algorithm

Writing an algorithm is mostly considered as a first step to programming.

Once we have an algorithm to solve a problem, we can write the computer program for
giving instructions to the computer in high level language.

If the algorithm is correct, computer will run the program correctly, every time.

So, the purpose of using an algorithm is to increase the reliability, accuracy and
efficiency of obtaining solutions.

Characteristics of a good algorithm


• Precision — the steps are precisely stated or defined.

• Uniqueness — results of each step are uniquely defined and only depend on the input
and the result of the preceding steps.

• Finiteness — the algorithm always stops after a finite number of steps.

• Input — the algorithm receives some input.

• Output — the algorithm produces some output.

While writing an algorithm, it is required to clearly identify the following:

• The input to be taken from the user

• Processing or computation to be performed to get the desired result

• The output desired by the user

4. Representation of Algorithms

There are two common methods of representing an algorithm —flowchart and


pseudocode. Either of the methods can be used to represent an algorithm while keeping
in mind the following:

• it showcases the logic of the problem solution, excluding any implementational details

• it clearly reveals the flow of control during execution of the program

4.1 Flowchart — Visual Representation of Algorithms

A flowchart is a visual representation of an algorithm.

A flowchart is a diagram made up of boxes, diamonds and other shapes, connected by


arrows.

Symbols / Functions / Descriptions / Start/End .


Also called “Terminator” symbol. It indicates where the flow starts and ends.
Process

Also called “Action Symbol,” it represents a process, action, or a single step.


Decision

A decision or branching point, usually a yes/no or true/ false question is asked, and
based on the answer, the path gets split into two branches.

Input/Output

Also called data symbol, this parallelogram shape is used to input or output data

Arrow

Connector to show order of flow between shapes.

Flowchart to calculate square of a number

4.2 Pseudocode

A pseudocode (pronounced Soo-doh-kohd) is another way of representing an


algorithm. It is considered as a non-formal language that helps programmers to write
algorithm. The word “pseudo” means “not real,” so “pseudocode” means “not real
code”. Following are some of the frequently used keywords while writing

pseudocode:

• INPUT

• COMPUTE

• PRINT

• INCREMENT

• DECREMENT

• IF/ELSE

• WHILE
• TRUE/FALSE

Example:

Pseudocode for the sum of two numbers will be:

input num1

input num2

COMPUTE Result = num1 + num2

PRINT Result

4.5 Flow of Control

The flow of control depicts the flow of events as represented in the flow chart.

4.5.1 Sequence

Sometimes the algorithm to either does some routine tasks in a repeated manner or
behave differently depending on the outcomes of previous steps.

The statements are executed one after another is known as sequence.

4.5.2 Selection

Let us look at some other examples where decision making is dependent on certain
conditions. For example,

(i) Checking eligibility for voting.

Depending on their age, a person will either be allowed to vote or not allowed to vote:

• If age is greater than or equal to 18, the person is eligible to vote

• If age is less than 18, the person is not eligible to vote

(ii) Let us consider another example


If a student is 8 years old and the student likes Maths put the student in Group A

Otherwise

Put the student in Group B

Actions depending on true or false of a condition

Conditionals are written in the algorithm as follows:

If <condition> then

steps to be taken when the

condition is true/fulfilled

There are situations where we also need to take action when the condition is not
fulfilled (In above Figure). To represent that, we can write:

If <condition> is true then

steps to be taken when the condition is

true/fulfilled

otherwise

steps to be taken when the condition is

false/not fulfilled

4.6 Verifying Algorithms

The software designer should make sure that the functioning of all the components are
defined correctly, checked and verified in every possible way.

When we were told that the formula for the sum of first N natural numbers is N(N+1)
/ 2 , how did we verify it?
Well, we can check this for small numbers, for which we can manually calculate the
sum.

Let N = 6, then the sum is 1 + 2 + 3 + 4 + 5 + 6 = 21 Using formula we get sum =


6x(6+1) / 2

The method of taking an input and running through the steps of the algorithm is
sometimes called dry run. Such a dry run will help us to:

1. Identify any incorrect steps in the algorithm

2. Figure out missing details or specifics in the algorithm

Write an algorithm to calculate the time taken to go from place A to C (T_total) via B
where time taken to go from A to B (T1) and B to C (T2) are given. That is, we want
the algorithm to add time given in hours and minutes. One way to write the algorithm
is:

PRINT value for T1

INPUT hh1

INPUT mm1

PRINT value for T2

INPUT hh2

INPUT mm2

hh_total = hh1 + hh2 (Add hours)

mm_total = mm1 + mm2 (Add mins)

Print T_total as hh_total, mm_total

Now let us verify. Suppose the first example we take is T1 = 5 hrs 20 mins and T2 = 7
hrs 30 mins. On dry run, we get the result 12 hrs and 50 mins. This looks fine.

4.7 Comparison of Algorithm


There can be four different ways to write algorithms to check whether a given number
is prime or not as shown below:

(i) Starting with divisor 2, divide the given number (dividend) and check if there are
any factors. Increase the divisor in each iteration and repeat the previous steps as long
as divisor < dividend. If there is a factor, then the given number is not prime

(ii) In (i), instead of testing all the numbers till the dividend, only test up to half of the
given value (dividend) because the divisor can not be more than half of the dividend

(iii) In method (i), only test up to the square root of the dividend (numbers)

(iv) Given a prior list of prime number till 100, divide the given number by each number
in the list. If not divisible by any number, then the number is a prime else it is not prime

All these four methods can check if a given number is prime or not. Now the question
is which of these methods is better or efficient?

Algorithm (i) requires large number of calculations (means more processing time) as it
checks for all the numbers as long as the divisor is less than the number. If the given
number is large, this method will take more

time to give the output.

Algorithm (ii) is more efficient than (i) as it checks for divisibility till half the number,
and thus it reduces the time for computation of the prime number.

Algorithm (iii) is even more efficient as it checks for divisibility till square root of the
number, thereby further reducing the time taken.

As algorithm (iv) uses only the prime numbers smaller than the given number for
divisibility, it further reduces the calculations. But in this method we require to store
the list of prime numbers first. Thus it takes additional

memory even though it requires lesser calculations.

Hence, algorithms can be compared and analysed on the basis of the amount of
processing time they need to run and the amount of memory that is needed to execute
the algorithm. These are termed as time complexity and space complexity, respectively.
The choice of an algorithm over another is done depending on how efficient they are
in terms of processing time required (time complexity) and the memory they utilize
(space complexity).
4.8 Coding

Once an algorithm is finalised, it should be coded in a high-level programming


language as selected by the programmer.

The ordered set of instructions are written in that programming language by following
its syntax.

Syntax is the set of rules or grammar that governs the formulation of the statements in
the language, such as spellings, order of words, punctuation, etc.

4.9 Decomposition

The basic idea of solving a complex problem by decomposition is to 'decompose' or


break down a complex problem into smaller sub problems

Answer the Following Questions (Very Short Annswers)

Define Algorithm

What is decomposition?

Why do we need Algorithm?

What is meant by Debugging?

Answer the Following Questions (Short Answers)

Write an algorithm to find the greatest among two different numbers

Write a pseudocode to calculate the factorial of a number

Write an algorithm to fing greates among three numbers

Answer the Following Questions (LongAnswers)

Write pseudocode and draw flowchart to accept numbers till the user enters 0 and then
find their average.
Write a pseudocode and draw a flowchart where multiple conditions are checked to
categorize a person as either child (<13), teenager (>=13 but <20) or adult
(>=20),based on age specified:

Write an algorithm that accepts four numbers as input and find the largest and smallest
of them.

REVISION NOTES

CLASS XI

GETTING STARTED WITH PYTHON

5.1 INTRODUCTION TO PYTHON

A program written in a high-level language is called source code. Python uses an


interpreter to convert its instructions into machine language, so that it can be understood
by the computer. An interpreter processes the program statements one by one, first
translating and then executing. This process is continued until an error is encountered
or the whole program is executed successfully

5.1.1 Features of Python

Python is a high level language. It is a free and open source language.

• It is an interpreted language, as Python programs are executed by an interpreter.

• Python programs are easy to understand as they have a clearly defined syntax
and relatively simple structure.

• Python is case-sensitive. For example, NUMBER and number are not same in
Python.
• Python is portable and platform independent, means it can run on various
operating systems and hardware platforms.

• Python has a rich library of predefined functions.

• Python is also helpful in web development. Many popular web services and
applications are built using python.

• Python uses indentation for blocks and nested blocks.

5.1.2 Working with Python

To write and run (execute) a Python program, we need to have a Python interpreter
installed on our computer or we can use any online Python interpreter.

Script Mode:
In this mode source code is stored in a file with the .py extension and use the
interpreter to execute the contents of the file. To execute the script by the interpreter,
you have to tell the interpreter the name of the file.
Example:
If you have a file name Demo.py , to run the script you have to follow the
following steps:

Step-1: Open the text editor i.e. Notepad


Step-2: Write the python code and save the file with .py file extension.
(Default directory is C:\Python33/Demo.py)
Step-3: Open IDLE ( Python GUI) python shell
Step-4: Click on file menu and select the open option
Step-5: Select the existing python file
Step-6: Now a window of python file will be opened
Step-7: Click on Run menu and the option Run Module.
Step-8: Output will be displayed on python shell window

5.2 PYTHONKEYWORDS

Reserved words in the library of a language. There are 33 keywords in python.

All the keywords are in lowercase except 03 keywords (True, False, None)

5.3 IDENTIFIERS
Identifier: The name given by the user to the entities like variable name, class-name,
function-name etc.

Rules for identifiers:

• It can be a combination of letters in lowercase (a to z) or uppercase (A to Z)


or digits (0 to 9) or an underscore.
• It cannot start with a digit.
• Keywords cannot be used as an identifier.
• We cannot use special symbols like !, @, #, $, %, + etc. in identifier.
• _ (underscore) can be used in identifier.
• Commas or blank spaces are not allowed within an identifier.

5.4 VARIABLES
• A variable in a program is uniquely identified by a name (identifier).
• Variable in Python refers to an object — an item or element that is stored in the
memory.
• Value of a variable can be a string (e.g., ‘b’, ‘Global Citizen’), numeric (e.g.,
345) or any combination of alphanumeric characters (CD67).
• In Python we can use an assignment statement to create new variables and assign
specific values to them.
gender = 'M'
message = "Keep Smiling"
price = 987.9
Program Write a program to display values of variables in Python.
#To display values of variables
message = "Keep Smiling"
print(message)
userNo = 101
print('User Number is', userNo)
Output:
Keep Smiling
User Number is 101
5.5 COMMENTS
• Comments are not executed.
• Comments explain a program and make a program understandable and
readable.
• All characters after the # and up to the end of the physical line are part of the
comment and the Python interpreter ignores them.
Example
#Variable amount is the total spending on grocery
amount = 3400
#totalMarks is sum of marks in all the tests of Mathematics
totalMarks = test1 + test2 + finalTest

5.6 EVERYTHING IS ANOBJECT


Python treats every value or data item whether numeric, string, or other type (discussed
in the next section) as an object in the sense that it can be assigned to some variable
or can be passed to a function as an argument.
Example
>>> num1 = 20
>>> id(num1)
1433920576 #identity of num1
>>> num2 = 30 - 10
>>> id(num2)
1433920576 #identity of num2 and num1
#are same as both
refers to #object 20

5.7 DATATYPES
5.7.1 Number

Number data type stores numerical values only. It is further classified into three
different types: int, float and complex.

Table Numeric data types

Boolean data type (bool) is a subtype of integer. It is a unique data type, consisting of
two constants, True and False.

Example
>>> num1 = 10
>>> type(num1)
<class 'int'>

>>> float1 = -1921.9


>>> type(float1)
<class 'float'>
>>> float2 = -9.8*10**2
>>> print(float2, type(float2))
-980.0000000000001 <class 'float'>

>>> var2 = -3+7.2j


>>> print(var2, type(var2))
(-3+7.2j) <class 'complex

5.7.2 Sequence
String
String is a group of characters. These characters may be alphabets, digits or special
characters including spaces.
>>> str1 = 'Hello Friend'
>>> str2 = "452"
We cannot perform numerical operations on strings, even when the string contains a
numeric value, as in str2.
List
List is a sequence of items separated by commas and the items are enclosed in square
brackets [ ].
Example
#To create a list
>>> list1 = [5, 3.4, "New Delhi", "20C", 45]
#print the elements of the list list1
>>> print(list1)
[5, 3.4, 'New Delhi', '20C', 45]
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 the tuple.
Example
#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')
Set
Set is an unordered collection of items separated by commas and the items are enclosed
in curly brackets { }. A set is similar to list, except that it cannot have duplicate
entries. Once created, elements of a set cannot be changed.

Example
#create a set
>>> set1 = {10,20,3.14,"New Delhi"}
>>> print(type(set1))
<class 'set'>
>>> print(set1)
{10, 20, 3.14, "New Delhi"}
#duplicate elements are not included in set
>>> set2 = {1,2,1,3}
>>> print(set2)
{1, 2, 3}
5.7.4 None
None is a special data type with a single value.
Example
>>> myVar = None
>>> print(type(myVar))
<class 'NoneType'>
>>> print(myVar)
None
5.7.5 Mapping
Mapping is an unordered data type in Python. Currently, there is only one standard
mapping data type in Python
called dictionary.
Dictionary
Dictionary in Python holds data items in key-value pairs.Items in a dictionary are
enclosed in curly brackets { }.
Example
#create a dictionary
>>> dict1 = {'Fruit':'Apple', 'Climate':'Cold', 'Price(kg)':120}
>>> print(dict1)
{'Fruit': 'Apple', 'Climate': 'Cold', 'Price(kg)': 120}
>>> print(dict1['Price(kg)'])
120
5.7.6 Mutable and Immutable Data Types
Mutable Immutable
The objects can be modified after the Objects can not be modified after the
creation as well. creation of the objects.
Classes that are mutable are not considered Classes that are immutable are
final. considered final.
Thread unsafe. Thread-safe.
Classes are not made final for the mutable Classes are made final for the immutable
objects. objects.
Example: Lists, Dicts, Sets, User-Defined Example: int, float, bool, string,
Classes, Dictionaries, etc. Unicode, tuple, Numbers, etc.

5.8 OPERATORS
5.8.1 Arithmetic Operators
5.8.2 Relational Operators
5.8.3 Assignment Operators
5.8.4 Logical Operators

5.8.5 Identity Operators


5.8.6 Membership Operators

5.9 EXPRESSIONS

An expression is defined as a combination of constants, variables, and operators.

An expression always evaluates to a value.

1. 100
2. 3.0 + 3.14
3. num
4. 23/3 -5 * 7(14 -2)
5. num – 20.4
6. "Global" + "Citizen"
5.9.1 Precedence of Operators
Example
How will Python evaluate the following expression?
(20 + 30) * 40
Solution:
= (20 + 30) * 40 # Step 1
#using parenthesis(), we have forced precedence of + to be more than that of *
= 50 * 40 # Step 2
= 2000 # Step 3
Example
How will the following expression be evaluated in Python?
15.0 / 4 + (8 + 3.0)
Solution:
= 15.0 / 4 + (8.0 + 3.0) #Step 1
= 15.0 / 4.0 + 11.0 #Step 2
= 3.75 + 11.0 #Step 3
= 14.75 #Step 4

5.10 STATEMENT
In Python, a statement is a unit of code that the Python interpreter can execute.
Example
>>> x = 4 #assignment statement
>>> cube = x ** 3 #assignment statement
>>> print (x, cube) #print statement
4 64

5.11 INPUT AND OUTPUT


The input() function prompts the user to enter data. It accepts all user input as string.
The user may enter a number or a string but the input() function treats them as strings
only.
The syntax for input() is:
input ([Prompt])
Example 5.14
>>> fname = input("Enter your first name: ")
Enter your first name: Arnab
>>> age = input("Enter your age: ")
Enter your age: 19
>>> type(age)
Example

5.12 TYPE CONVERSION


Consider the following program
num1 = input("Enter a number and I'll double it: ")
num1 = num1 * 2
print(num1)
The program was expected to display double the value of the number received and store
in variable num1.
So if a user enters 2 and expects the program to display 4 as the output, the program
displays the following result:
Enter a number and I'll double it: 2
22
5.12.1 Explicit Conversion
Program
Program of explicit type conversion from int to float.
#Explicit type conversion from int to float
num1 = 10
num2 = 20
num3 = num1 + num2
print(num3)
print(type(num3))
num4 = float(num1 + num2)
print(num4)
print(type(num4))
Output: 30 30.0
Program
Program to show explicit type conversion.
#Explicit type conversion
icecream = '25'
brownie = '45' #String concatenation
price = icecream + brownie
print("Total Price Rs." + price) #Explicit type conversion - string to integer
price = int(icecream)+int(brownie)
print("Total Price Rs." + str(price))
Output: Total Price Rs.2545
Total Price Rs.70

5.12.2 Implicit Conversion


Implicit conversion, also known as coercion, happens when data type conversion is
done automatically by
Python and is not instructed by the programmer. Program 5-10 Program to show
implicit conversion from int to
float.
#Program
#Implicit type conversion from int to float
num1 = 10 #num1 is an integer
num2 = 20.0 #num2 is a float
sum1 = num1 + num2 #sum1 is sum of a float and an integer
print(sum1)
print(type(sum1))
Output: 30.0

5.13 DEBUGGING
A programmer can make mistakes while writing a program, and hence, the program
may not execute or may generate wrong output. The process of identifying and
removing such mistakes, also known as bugs or errors, from a program is called
debugging. Errors occurring in programs can be categorised as:
i) Syntax errors.
ii) Logical errors
iii) Runtime errors

5.13.1 Syntax Errors


Like other programming languages, Python has its own rules that determine its syntax.
The interpreter interprets the statements only if it is syntactically (as per the rules of
Python) correct. If any syntax error is present, the interpreter shows error message(s)
and stops the execution there. For example, parentheses must be in pairs, so the
expression (10 + 12) is syntactically correct, whereas (7 + 11 is not due to absence of
right parenthesis. Such errors need to be removed before the execution of the program
5.13.2 Logical Errors
Logical errors are also called semantic errors as they occur when the meaning of the
program (its semantics) is not correct.
For example, if we wish to find the average of two numbers 10 and 12 and we write the
code as 10 + 12/2, it would run successfully and produce the result 16. Surely, 16 is not
the average of 10 and 12. The correct code to find the average should have been (10 +
12)/2 to give the correct output as 11.
5.13.3 Runtime Error
A runtime error causes abnormal termination of program while it is executing. Runtime
error is when the statement is correct syntactically, but the interpreter cannot execute
it. Runtime errors do not appear until after the program starts running or executing.
Program
Example of a program which generates runtime error.
#Runtime Errors Example
num1 = 10.0 S.NO
TOPIC

Introduction , Steps for Problem Solving , Algorithm , , Representation of Algorithms

Flow of Control , Verifying Algorithms , Comparison of Algorithm , Coding ,


Decomposition
1. INTRODUCTION
Computers are used for solving various day-to-day problems.
It is pertinent to mention that computers themselves cannot solve a problem.
Precise step-by-step instructions should be given by us to solve the problem.
Thus, the success of a computer in solving a problem depends on how correctly and
precisely we define the problem, design a solution (algorithm) and implement the
solution (program) using a programming language.
Thus, problem solving is the process of identifying a problem, developing an algorithm
for the identified problem and finally implementing the algorithm to develop a
computer program.
2. Steps for Problem Solving
There are four steps in problem solving
Analysing the problem
Developing an Algorithm
Coding
Testing and Debugging

2.1 Analysing the problem


It is important to clearly understand a problem before we begin to find the solution for
it.
If we are not clear as to what is to be solved, we may end up developing a program
which may not solve our purpose.
By analysing a problem, we would be able to figure out what are the inputs that our
program should accept and the outputs that it should produce.

2.2 Developing an Algorithm


The solution for a problem is represented in step by step procedure called an algorithm.
For a given problem, more than one algorithm is possible and we have to select the
most suitable solution.

2.3 Coding
After finalising the algorithm, we need to convert the algorithm into the format which
can be understood by the computer to generate the desired solution.

2.4 Testing and Debugging


The program created should be tested on various parameters.
The program should meet the requirements of the user.
In the presence of syntactical errors, no output will be obtained.
In case the output generated is incorrect, then the program should be checked for logical
errors, if any.
3. Algorithm
Algorithm is the step by step procedure for solving the problem. Suppose following are
the steps required for an activity ‘riding a bicycle’:
remove the bicycle from the stand,
sit on the seat of the bicycle,
start peddling,
use breaks whenever needed and
stop on reaching the destination.

Example:
Algorithm to find square of a number.

Step 1: Input a number and store it to num


Step 2: Compute num * num and store it in square
Step 3: Print square

3.1 Why do we need an Algorithm


Writing an algorithm is mostly considered as a first step to programming.
Once we have an algorithm to solve a problem, we can write the computer program for
giving instructions to the computer in high level language.
If the algorithm is correct, computer will run the program correctly, every time.
So, the purpose of using an algorithm is to increase the reliability, accuracy and
efficiency of obtaining solutions.

Characteristics of a good algorithm


• Precision — the steps are precisely stated or defined.
• Uniqueness — results of each step are uniquely defined and only depend on the input
and the result of the preceding steps.
• Finiteness — the algorithm always stops after a finite number of steps.
• Input — the algorithm receives some input.
• Output — the algorithm produces some output.
While writing an algorithm, it is required to clearly identify the following:
• The input to be taken from the user
• Processing or computation to be performed to get the desired result
• The output desired by the user

4. Representation of Algorithms

There are two common methods of representing an algorithm —flowchart and


pseudocode. Either of the methods can be used to represent an algorithm while keeping
in mind the following:
• it showcases the logic of the problem solution, excluding any implementational details
• it clearly reveals the flow of control during execution of the program
4.1 Flowchart — Visual Representation of Algorithms
A flowchart is a visual representation of an algorithm.
A flowchart is a diagram made up of boxes, diamonds and other shapes, connected by
arrows.
Symbols
Functions
Descriptions

Start/End
Also called “Terminator” symbol. It indicates where the flow starts and ends.

Process
Also called “Action Symbol,” it represents a process, action, or a single step.
Decision
A decision or branching point, usually a yes/no or true/ false question is asked, and
based on the answer, the path gets split into two branches.

Input/Output
Also called data symbol, this parallelogram shape is used to input or output data

Arrow
Connector to show order of flow between shapes.

Flowchart to calculate square of a number

4.2 Pseudocode
A pseudocode (pronounced Soo-doh-kohd) is another way of representing an
algorithm. It is considered as a non-formal language that helps programmers to write
algorithm. The word “pseudo” means “not real,” so “pseudocode” means “not real
code”. Following are some of the frequently used keywords while writing
pseudocode:
• INPUT / • COMPUTE / • PRINT / • INCREMENT / • DECREMENT / • IF/ELSE /•
WHILE
• TRUE/FALSE

Example:
Pseudocode for the sum of two numbers will be:
input num1
input num2
COMPUTE Result = num1 + num2
PRINT Result

4.5 Flow of Control


The flow of control depicts the flow of events as represented in the flow chart.

4.5.1 Sequence
Sometimes the algorithm to either does some routine tasks in a repeated manner or
behave differently depending on the outcomes of previous steps.
The statements are executed one after another is known as sequence.

4.5.2 Selection
Let us look at some other examples where decision making is dependent on certain
conditions. For example,
(i) Checking eligibility for voting.
Depending on their age, a person will either be allowed to vote or not allowed to vote:
• If age is greater than or equal to 18, the person is eligible to vote
• If age is less than 18, the person is not eligible to vote
(ii) Let us consider another example
If a student is 8 years old and the student likes Maths put the student in Group A
Otherwise
Put the student in Group B

Actions depending on true or false of a condition

Conditionals are written in the algorithm as follows:

If <condition> then
steps to be taken when the
condition is true/fulfilled
There are situations where we also need to take action when the condition is not
fulfilled (In above Figure). To represent that, we can write:
If <condition> is true then
steps to be taken when the condition is
true/fulfilled
otherwise
steps to be taken when the condition is
false/not fulfilled

4.6 Verifying Algorithms

The software designer should make sure that the functioning of all the components are
defined correctly, checked and verified in every possible way.
When we were told that the formula for the sum of first N natural numbers is N(N+1)
/ 2 , how did we verify it?
Well, we can check this for small numbers, for which we can manually calculate the
sum.
Let N = 6, then the sum is 1 + 2 + 3 + 4 + 5 + 6 = 21 Using formula we get sum =
6x(6+1) / 2
The method of taking an input and running through the steps of the algorithm is
sometimes called dry run. Such a dry run will help us to:
1. Identify any incorrect steps in the algorithm
2. Figure out missing details or specifics in the algorithm
Write an algorithm to calculate the time taken to go from place A to C (T_total) via B
where time taken to go from A to B (T1) and B to C (T2) are given. That is, we want
the algorithm to add time given in hours and minutes. One way to write the algorithm
is:
PRINT value for T1
INPUT hh1
INPUT mm1
PRINT value for T2
INPUT hh2
INPUT mm2
hh_total = hh1 + hh2 (Add hours)
mm_total = mm1 + mm2 (Add mins)
Print T_total as hh_total, mm_total
Now let us verify. Suppose the first example we take is T1 = 5 hrs 20 mins and T2 = 7
hrs 30 mins. On dry run, we get the result 12 hrs and 50 mins. This looks fine.

4.7 Comparison of Algorithm

There can be four different ways to write algorithms to check whether a given number
is prime or not as shown below:
(i) Starting with divisor 2, divide the given number (dividend) and check if there are
any factors. Increase the divisor in each iteration and repeat the previous steps as long
as divisor < dividend. If there is a factor, then the given number is not prime
(ii) In (i), instead of testing all the numbers till the dividend, only test up to half of the
given value (dividend) because the divisor can not be more than half of the dividend
(iii) In method (i), only test up to the square root of the dividend (numbers)
(iv) Given a prior list of prime number till 100, divide the given number by each number
in the list. If not divisible by any number, then the number is a prime else it is not prime
All these four methods can check if a given number is prime or not. Now the question
is which of these methods is better or efficient?

Algorithm (i) requires large number of calculations (means more processing time) as it
checks for all the numbers as long as the divisor is less than the number. If the given
number is large, this method will take more
time to give the output.
Algorithm (ii) is more efficient than (i) as it checks for divisibility till half the number,
and thus it reduces the time for computation of the prime number.
Algorithm (iii) is even more efficient as it checks for divisibility till square root of the
number, thereby further reducing the time taken.
As algorithm (iv) uses only the prime numbers smaller than the given number for
divisibility, it further reduces the calculations. But in this method we require to store
the list of prime numbers first. Thus it takes additional
memory even though it requires lesser calculations.

Hence, algorithms can be compared and analysed on the basis of the amount of
processing time they need to run and the amount of memory that is needed to execute
the algorithm. These are termed as time complexity and space complexity, respectively.
The choice of an algorithm over another is done depending on how efficient they are
in terms of processing time required (time complexity) and the memory they utilize
(space complexity).

4.8 Coding
Once an algorithm is finalised, it should be coded in a high-level programming
language as selected by the programmer.
The ordered set of instructions are written in that programming language by following
its syntax.
Syntax is the set of rules or grammar that governs the formulation of the statements in
the language, such as spellings, order of words, punctuation, etc.

4.9 Decomposition
The basic idea of solving a complex problem by decomposition is to 'decompose' or
break down a complex problem into smaller sub problems

Answer the Following Questions (Very Short Annswers)


Define Algorithm
What is decomposition?
Why do we need Algorithm?
What is meant by Debugging?

Answer the Following Questions (Short Answers)

Write an algorithm to find the greatest among two different numbers


Write a pseudocode to calculate the factorial of a number
Write an algorithm to fing greates among three numbers

Answer the Following Questions (LongAnswers)

Write pseudocode and draw flowchart to accept numbers till the user enters 0 and then
find their average.
Write a pseudocode and draw a flowchart where multiple conditions are checked to
categorize a person as either child (<13), teenager (>=13 but <20) or adult
(>=20),based on age specified:
Write an algorithm that accepts four numbers as input and find the largest and smallest
of them.

WORKSHEETS

1. What is the difference between a keyword and an identifier?

2. How many ways are there in Python to represent an integer literal.

3. Which of the following identifier names are invalid and why?

i Serial_no. v Total_Marks
ii 1st_Room vi total-Marks
iii Hundred$ vii _Percentage
iv Total Marks viii True
4. Write logical expressions corresponding to the following statements in Python
and evaluate the expressions (assuming variables num1, num2, num3, first,
middle, last are already having meaningful values):
a) The sum of 20 and –10 is less than 12.
b) num3 is not more than 24
c) 6.75 is between the values of integers num1 and num2.
d) The string ‘middle’ is larger than the string ‘first’ and smaller than the string
‘last’
e) List Stationery is empty

5. Add a pair of parentheses to each expression so that it evaluates to True.

a) 0 == 1 == 2
b) 2 + 3 == 4 + 5 == 7
c) 1 < -1 == 3 > 4

6. Write the output of the following.


a) num1 = 4
num2 = num1 + 1
num1 = 2
print (num1, num2)
b) num1, num2 = 2, 6
num1, num2 = num2, num1 + 2
print (num1, num2)
c) num1, num2 = 2, 3
num3, num2 = num1, num3 + 1
print (num1, num2, num3)
7. Give the output of the following when num1 = 4, num2 = 3, num3 = 2
a) num1 += num2 + num3
print (num1)
b) num1 = num1 ** (num2 + num3)
print (num1)
c) num1 **= num2 + num3
d) num1 = '5' + '5'
print(num1)
e) print(4.00/(2.0+2.0))
f) num1 = 2+9*((3*12)-8)/10
print(num1)
g) num1 = 24 // 4 // 2
print(num1)
h) num1 = float(10)
print (num1)
i) num1 = int('3.14')
print (num1)
j) print('Bye' == 'BYE')
k) print(10 != 9 and 20 >= 20)
l) print(10 + 6 * 2 ** 2 != 9//4 -3 and 29>= 29/9)
m) print(5 % 10 + 10 < 50 and 29 <= 29)
n) print((0 < 6) or (not (10 == 6) and (10<0)))

8. Categorize the following as syntax error, logical error or runtime error:


a) 25 / 0
b) num1 = 25; num2 = 0; num1 / num2

9. Write a Python program to convert temperature in degree Celsius to degree


Fahrenheit. If water boils at 100 degree C and freezes as 0 degree C, use the
program to find out what is the boiling point and freezing point of water on the
Fahrenheit scale. (Hint: T(°F) = T(°C) × 9/5 + 32)

10. Write a Python program to calculate the amount payable if money has
been lent on simple interest.
Principal or money lent = P, Rate of interest = R% per annum and Time = T
years. Then Simple Interest (SI) = (P x R x T)/ 100.
Amount payable = Principal + SI. P, R and T are given as input to the program.

11. Write a program to enter two integers and perform all arithmetic
operations on them.

12. Write a program to swap two numbers without using a third variable.
ANSWER KEY

QUESTION 1
Keyword is a special word that has a special meaning and purpose. Keywords are
reserved and are few. For example : if, else, elif etc. Identifier is the user-defined
name given to a part of a program like variable, object, functions etc. Identifiers are
not reserverd. These are defined by the user but they can have letters, digits and a
symbols underscore. They must begin with either a letter or underscore. For example :
chess, _ch, etc.
QUESTION 2
Python allows three types of integer literals :
1. Decimal (base 10) integer literals.
2. Octal (base 8) integer literals.
3. Hexadecimal (base 16) integer literals. For example, decimal 12 will be written as
14 as octal integer and as OXC as hexa decimal integer. (12)10 = (14)8 = (OXC)16.
(as hexa decimal)
QUESTION 3

i) Serial_no.: Invalid - Identifier in python cannot contain any special character except
underscore(_).
ii) 1st_Room: Invalid - Identifier in Python cannot start with a number.
iii) Hundred$: Invalid - Identifier in Python cannot contain any special character
except underscore(_).
iv) Total Marks: Invalid - Identifier in Python cannot contain any special character
except underscore(_). If more than one word is used as a variable then it can be
separated using underscore ( _ ), instead of space.
v) Total_Marks: Valid
vi) total-Marks: Invalid - Identifier in Python cannot contain any special character
except underscore(_). If more than one word is used as a variable then it can be
separated using underscore ( _ ), instead of a hyphen ( - ).
vii) _Percentage: Valid
viii) True: Invalid - Identifier in Python should not be a reserved keyword.

QUESTION 4

a) (20 + (-10)) < 12


b) num3 <= 24 or not(num3 > 24)
c) (6.75 >= num1) and (6.75 <= num2)
d) (middle > first) and (middle < last)
e) len(Stationery) == 0

QUESTION 5
a) ( 0 == (1==2))
b) (2 + (3 == 4) + 5) == 7
c) (1 < -1) == (3 > 4 )
QUESTION 6
a) 2, 5
b) 6, 4
c) Error as num3 is used in RHS of line 2 (num3, num2 = num1, num3 + 1) before
defining it earlier.

QUESTION 7
a) num1 += 3 + 2
The above statement can be written as
num1 = num1 + 3 + 2 = 4 + 3 + 2 = 9
Therefore, print(num1) will give the output 9.
b) num1 = num1 ** (num2 + num3)
The above statement will be executed as per the following steps.
num1 = 4 ** (3 + 5) = 4 ** 5 = 1024
Therefore, print(num1) will give the output 1024.
c) num1 **= num2 + num3
The above statement can be written as
num1 **= 5
num1 = num1 ** 5
num1 = 4 ** 5
num1 = 1024
Therefore, the output will be 1024.

d) num1 = '5' + '5'


The RHS in the above statement is '5' + '5'. Please note that 5 is enclosed in quotes
and hence will be treated as a string. Therefore, the first line is just a string
concatenation which will give the output 55. The type of output will be a string, not
an integer.
e) print(4.00/(2.0 + 2.0))
The numbers written in the statement are in float data type therefore, the output will
be also in float data type.
print(4.00/(2.0 + 2.0))
print(4.0/4.0)
1.0
Therefore, the output will be 1.0.

f) num1 = 2 + 9 * ((3 * 12) - 8) /10


# The expression within inner brackets will be evaluated first
num1 = 2 + 9 * (36 - 8) /10
# The expression within outer brackets will be evaluated next
num1 = 2 + 9 * 28/10
# * and / are of same precedence, hence, left to right order is followed
num1 = 2 + 252/10
num1 = 2 + 25.2
num1 = 27.2
Therefore, the output will be 27.2.

g) num1 = 24 // 4 // 2
#When the operators are same, left to right order will be followed for operation
num1 = 6 // 2
#When floor division is used, return value will be int data type
num1 = 3
Therefore, the output will be 3

h) num1 = float(10)
float(10) will convert integer value to float value and therefore, the output will be
10.0.
i) num1 = int('3.14')
This will result in an error as we cannot pass string representation of float to an int
function.

j) print('Bye' == 'BYE')
As Python compares string character to character and when different characters are
found then their Unicode value is compared. The character with lower Unicode value
is considered to be smaller. Here, 'y' has Unicode 121 and 'Y' has 89. Therefore, the
output will be 'False'.

k) print(10 != 9 and 20 >= 20)


print(True and True)
print(True)
Therefore, the output will be 'True'.

l) print(10 + 6 * 2 ** 2 != 9//4 -3 and 29>= 29/9)


Taking the above statement in two separate parts
LHS:
10 + 6 * 2 ** 2 != 9//4 - 3
10 + 6 * 4 != 2 - 3
10 + 24 != -1
34 != -1
True

RHS:
29 >= 29/9
True

Now the complete equation can be written as


print(True and True)
Therefore, the output will be 'True'.

m) print(5 % 10 + 10 < 50 and 29 <= 29)


Taking the above statement in two separate parts

LHS :
5 % 10 + 10 < 50
5 + 10 < 50
15 < 50
True

RHS:
29 <= 29
True

Now, the complete equation can be written as


print(True and True)
Therefore, the output will be 'True'.

n) print( (0 < 6) or (not (10 == 6) and (10<0) ) )


print(True or (not False and False))
print(True or (True and False))
# not will be evaluated before and/or.
print(True or False)
print(True)
Therefore, the output will be 'True'.

QUESTION 8
a) Runtime Error. The syntax for the division is correct. The error will arise only
when 'interpreter' will run this line.

b) Runtime Error. The syntax is correct. The error will arise only when 'interpreter'
will run the line containing these statements.

QUESTION 9
#defining the boiling and freezing temp in celcius
boil = 100
freeze = 0
print('Water Boiling temperature in Fahrenheit::')
#Calculating Boiling temperature in Fahrenheit
tb = boil * (9/5) + 32
#Printing the temperature
print(tb)

print('Water Freezing temperature in Fahrenheit::')


#Calculating Boiling temperature in Fahrenheit
tf = freeze * (9/5) + 32
#Printing the temperature
print(tf)

OUTPUT:
Water Boiling temperature in Fahrenheit::
212.0
Water Freezing temperature in Fahrenheit::
32.0

QUESTION 10
#Asking the user for Principal, rate of interest and time
P = float(input('Enter the principal: '))
R = float(input('Enter the rate of interest per annum: '))
T = float(input('Enter the time in years: '))
#calculating simple interest
SI = (P * R * T)/100
#caculating amount = Simple Interest + Principal
amount = SI + P
#Printing the total amount
print('Total amount:',amount)

OUTPUT:-
Enter the principal: 12500
Enter the rate of interest per annum: 4.5
Enter the time in years: 4
Total amount: 14750.0

QUESTION 11
#Program to input two numbers and performing all arithmetic operations

#Input first number


num1 = int(input("Enter first number: "))
#Input Second number
num2 = int(input("Enter second number: "))

#Printing the result for all arithmetic operations


print("Results:-")
print("Addition: ",num1+num2)
print("Subtraction: ",num1-num2)
print("Multiplication: ",num1*num2)
print("Division: ",num1/num2)
print("Modulus: ", num1%num2)
print("Floor Division: ",num1//num2)
print("Exponentiation: ",num1 ** num2)

OUTPUT:
Enter first number: 8
Enter second number: 3
Results:-
Addition: 11
Subtraction: 5
Multiplication: 24
Division: 2.6666666666666665
Modulus: 2
Floor Division: 2
Exponentiation: 512

QUESTION 12

#defining two variables


x=5
y=6

#printing the values before swapping

print("The values of x and y are",x,"and",y,"respectively.")


# Using 'multiple assignment' to swap the values
x,y = y,x

#printing the values after swapping


print("The values of x and y after swapping are",x,"and",y,"respectively.")

OUTPUT:
The values of x and y are 5 and 6 respectively.
The values of x and y after swapping are 6 and 5 respectively.
SR NO QUESTIONS
The physical and tangible electronic components of a computer

system are known as _______. (Ans. Hardware)

The programs which provide commands to work upon and govern the
working on the computer is known as _______. (Ans. Software)

Which of the following function(s) does not require the user’s


involvement – Input, Process, Output, Storage (Ans. Process, Output,
Storage)

The ________ of CPU is responsible for supervising the requests received


1 from CPU. (Ans. CU)

Which part of the CPU carries out the arithmetic instructions and logical
comparison to complete the task? (Ans. ALU)

The computer follows the IPO cycle that refers to Input-Performance-


Output. (True/False)

The small units of data storage hold the places of data in the CPU is
_______. (Ans. Register)

When the power is turned off, data will be lost. This is known as
_________. (Ans. Volatility)
The ______ is volatile memory where ________ non-volatile memory.
(Ans. RAM, ROM)

The PROM is call _______, which stands for One Time Programmable
memory. (Ans. OTP)

The EPROM can take _______ minutes for erasing contents written on
them. (Ans. 20)

SRAM is faster memory than DRAM. (True/Fast)

The ________ memory is high-speed memory available inside CPU to


speed up access to data and instructions stored in RAM. (Ans. Cache)

The ________ is mobile system I/O unit. (Ans. Communications


Process Unit)

The Application Processing Unit (APU) is responsible for governing, and


controlling all the common tasks on mobile systems. (True/False)

The output carried out from the mobile system using _____________
systems. (Ans. Display)

The mobile system doesn’t have RAM and ROM. (True/False)

The external storage of mobile systems are known as ____________


storage. (Ans. Expandable)

The battery in the mobile system is known as ________. (Ans. Power


Management System)

The software that controls the internal operations of a computer is known


as _______ software. (Ans. System)

The program code written by the user is known as _________.


(Ans. Source Code)

The converted code into machine-readable form is known as ________


code. (Ans. Object)
Which language processor executes the program line-by-line?
(Ans. Interpreter)

Which language process executes the whole program in one go?


(Ans. Compiler)

The set of some basic applications are provided by _____ type for
application software. (Ans. Packages)

The software made to fulfill users need is known as ________ software.


(Ans. Tailor-made)

The pre-written code that can be used to develop applications are known
as _______. (Ans. Libraries)

The software provided in Operating Systems to assist the user is known as


_______. (Ans. Utilities)

Notepad is a very popular package for documentation. (True/False)

The _______ software rearranges the files in the computers and cleans up
the memory. (Ans. Disk defragmenter)

Lalit is a game programmer and he is designing a game where he has to


use different python functions as much as possible. Apart from other
things, following functionalities are to be implemented in the game.
(1) He is simulating a dice where random number generation is required.
(2) Since the program becomes too lengthy, Lalit wants a separate section
where he can store all the functions used in the game program.
2
Lalit is feeling difficulty in implementing the above functionalities. Help
him by giving answers following questions:
i) To implement functionality (1) which module can be used:
a) random
b) randomise
c) randint
d) math
ii) In functionality (2), Lalit should use
a) in-built functions
b) He should write another Python program
c) He should use a module with all the required functions
d) He should make a separate section in the same Python program

One student who is learning Python, is making a function-based program


to find the roots of a quadratic equation. He wrote the program but he is
getting some error. Help him to complete the task successfully:
from ……… import sqrt LINE-1
Def quad(b,c,a=1): LINE-2
x = b*b-4*a*c 4 LINE-3
if x < 0: LINE-4
return “Sorry,complex root(s)” LINE-5
d = sqrt(x) LINE-6
r1 = (-b + d)/(2*a) LINE-7
r2 = (-b – d)/(2*a) LINE-8
3 return r1,r2 LINE-9
print(quad(1,1,2)) LINE-10
root = quad(3) LINE-11
rt = quad(2,1) LINE-12
i) Which python module should be used in line 1
a) random
b) CMath
c) math
d) Either (b) or (c)
ii) Which statement is correct with reference to above program?
a) Two return statements are used and a function can use only one
return statement
b) Required module is not given
c) Syntax error in line 4
d) Error in line 11

What gets printed with the following code ?


x = True
y = False
z = False
if not x or y :
print 1
elif not x or not y and z:
print 2
4
elif not x or y or not y and x:
print 3
else:
print 4

Answer:
3

Which numbers are printed?


for i in range(2):
print i
for i in range(4,6):
5 print i
Answer:
0,1
4, 5
What gets printed?
country_counter = {}
def addone(country):
if country in country_counter:
country_counter[country] + = 1
else:
country_counter[country] = 1
6
addone(‘China’)
addone(‘Japan’)
addone(‘china’)
print len(country_counter)

Answer:
3
What gets printed?
namesl = [‘Amir’, ‘Barry’, ‘Chales’, ‘Dao’]
if ‘amir’ in namesl:
print 1
7
else:
print 2
Answer:
2
Start with the list[8,9,10].
Do the following using list functions
(a) Set the second entry (index 1) to 17
(b) Add 4, 5 and 6 to the end of the list.
8
(c) Remove the first entry from the list.
(d) Sort the list.
(e) Double the list.
(f) Insert 25 at index 3
answer

(a) list[1]=17
(b) list.append(4) list.append(5) list.append(6)
(c) list.pop(0)
(d) list.sort()
(e) list=list*2
(f) list.insert(3,25)
Find out the output generated by following code fragments:
(a) plane = (“Passengers”, ”Luggage”) plane [1] = “Snakes”
(b) (a, b, c) = (1,2,3)
(c) (a, b, c, d) = (1,2,3)
(d) a, b, c, d = (1,2,3)
(e) a, b, c, d, e = (p, q, r, s, t) = t1

9
answer:
(a) TypeError: 'tuple' object does not support item assignment
(b) This will assign 1 to a, 2 to b and 3 to c.
(c) ValueError: not enough values to unpack (expected 4, got 3)
(d) ValueError: not enough values to unpack (expected 4, got 3)
(e) If tuple t1 has 5 values then this will assign first value of t1 in to a and
p , next value to b and q and so on.
What is Authentication and Authorization? Why are these two used
together?
10
Difference between Authentication and Authorization. Both the terms are
often used in conjunction with each other in terms of security, especially
when it comes to gaining access to the system. Authentication means
confirming your own identity, while authorization means granting access
to the system.
FLOW OF CONTROL

CONTENT – REVIEW

Flow control statements are used to control the flow of execution depending upon the
specified condition/logic.
Sequential Flow of control - Sequential execution is when statements are executed one after
another in order. We don't need to do anything more for this to happen as python compiler
itself do it.
There are three types of control statements.
1. Selection Statements
2. Iteration Statements (Loop control statement)
3. Jump Statements (break, continue, pass)
Selection statement
These are used to selectively execute some statements and control the flow of execution of
program depending upon condition.
There are three types of decision making statement.
1. if statements
2. if-else statements
3. if elif statement
Simple if:
The statement inside the if block are executed only when condition is true, otherwise not.
Syntax
if <condition>:
Statement(s)
Example:
if a < b :
print(‘a is greater’)
if-else statement
The statements inside the if block are executed only when condition is true, otherwise the
statements in the else block are executed.
Syntax
if <condition>:
Statement(s)
else:
statements
Example:
if a < b :
print(‘a is greater’)
else:
print(‘b is greater’)
if elif statement
The if...elif...else statement allows you to check for multiple test expressions and execute
different codes for more than two conditions.
print('****program to find greatest of 3 numbers****')
num1,num2,num3=eval(input('enter 3 unique numbers: '))
if num1 > num2 and num1 > num3:
print('The greatest of the three nos. is : ',num1)
elif num2 > num3 and num2 > num1:
print('The greatest of the three nos. is : ',num2)
elif num3 > num1 and num3 > num2:
print('The greatest of the three nos. is :',num3)
else:
print('any two nos are equal')
Nested if-else Statements
#Check leap year / divisibility
year = int(input("Enter a year: "))
if (year % 4) == 0:
if (year % 100) == 0:
if (year % 400) == 0:
print("{0} is a leap year".format(year))
else:
print("{0} is not a leap year".format(year))

Iteration statements(loop)
These are used to execute a block of statements as long as the condition is true. Loops
statements are used when we need to run same code again and again.

Python Iteration (Loops) statements are of two type :-


1. While Loop
2. For Loop
While Loop
It is used to execute a block of statement if a given condition is true. And when the condition
become false, the control will come out of the loop. The condition is checked every time at
the beginning of the loop.
Syntax
while (condition):
[statements]
Counter=0 #initiation stmt

while Counter < 5: #test condition

print(Counter)

Counter += 2 #increment stmt

OUTPUT:

4 Loop
For
It is used to iterate over items of any sequence, such as a list or a string.
Syntax
for val in sequence: #here val will take value of each element in the sequence
statements
Example:
for I in [1,2,3,4,5]:
print(I*5)
OUTPUT:
5
10
15
20
25
range() Function
This function generates a sequence of numbers based on the parameters passed.
Parameters
start: Starting number of the sequence.
stop: Generate numbers up to, but not including this number.
step(Optional): Determines the increment between each numbers in the sequence.
Python use range() function in three ways:

a. range(stop)
b. range(start,stop)
c. range(start,stop,step)
Note:

 All parameters must be integers.


 All parameters can be positive or negative.

a. range(stop): By default, It starts from 0 and increments by 1 and ends upto stop,
but not including stop value.
Example:
for x in range(4):
print(x)
Output:
0
1
2
3

b. range(start,stop) : It starts from the start value and upto stop, but not including
stop value.

c. range(start, stop, step): Third parameter specifies to increment or decrement the


value by adding or subtracting the value.
Use with for loop:

for i in range(1,5): for i in range(5,3,-1):


print(i) print(i)
OUTPUT: Output
1 5
2 4
3

Jump Statements
Jump statements are used to transfer the program's control from one location to
another. Means these are used to alter the flow of a loop like - to skip a part of a loop or
terminate a loop
There are three types of jump statements used in python.
1.break / 2.continue / 3.pass
Break
It is used to terminate the loop.
e.g.
for val in "string":
if val == "i":
break
print(val)
print("The end")
Output
str
The end
Continue
• Used to skip the rest of the statements of the current loop block and to move to next
iteration, of the loop.
• Continue will return back the control to the beginning of the loop.
• Can be used with both while & for. Eg:
for letter in ‘Python’:
if letter == ‘h’:
continue
print (letter)
Output
Pyton
Pass Statement
This statement does nothing. It can be used when a statement is required syntactically but the
program requires no action.
Use in loop :
while True:
pass # Busy-wait for keyboard interrupt (Ctrl+C)

WORKSHEETS

Sr Question
no
Q1 Can we write if/else into one line in python?
a) Yes

b) No

c) if/else not used in python

d) None of the above


Q2 Which one of the following is a valid Python if statement. a) if a>=2
:
b) if (a >= 2)

c) if (a => 22)

d) if a >= 22

Q3 What keyword would you use to add an alternative condition to an if


statement?
a) else if

b) elseif

c) elif

d) None of the above

Q4 What will be the data type of the var in the below code snippet?
var = 10
print(type(var))
var = "Hello"
print(type(var))

a) int and str


b) int and int
c) str and str
d) float and str

d)Q5 How is a code block indicated in Python?


a) Brackets

b) Indentation
c) Key

d) None of the above

Q6 What will be the output of the following code snippet?

a = [1, 2, 3] a =
tuple(a) a[0] = 2
print(a)

a) [1,2,3]

b) (1,2,3)

c) [2,2,3]

d) error

Q7 What will be the output of the following code snippet?


print(type(5 / 2))
print(type(5 // 2))

a) int and int

b) str and str

c) int and float

d) float and int

Q8 What will be the output of the following Python code?


x = [ 'ab' , 'cd' ]
for I in x:
i. upper()
print ( x )

a) [ ‘ab’, ‘cd’ ]
b) [‘AB’, ‘CD’]
c) [None, None]

d) none of the mentioned


What will be the output of the following Python code?
i=5
Q9 while True:
if i%0O11 == 0:
break
print(i)
i += 1

a) 5 6 7 8 9 10
b) 5678
c) 56
d) error

Q10 What will be the output of the following Python code? i = 1 while
True: if i%3 == 0:
break
print(i)
i+=1

a) 1 2

b) 1 2 3

c) error

d) none of the mentioned

1 Find the output of the following program segments:


I. a = 10
while a > 2:
print (a)
a -= 2

II. for i in range (20, 30, 2):


print (i)

III. var = 7
while var > 0:
print (“current variable value: ” , var)
var = var – 1
if var == 3:
break
else:
if var == 6:
var = var – 1
continue
print (“Good bye!”)
2 Write a Python program to find the factorial of a positive number Q6)
What are the four elements of a while loop in Python?
3 What are endless loops ? Why do such loops occur? Give example.
4 Draw flowchart for displaying first 10 odd numbers.
5 What is a flowchart? How is it useful?
6 What is empty statement in Python? What is its need?
7 Write a program to check whether a years is leap year or not.

8 Write a program to check a character is vowel or not.

COMPETENCY BASED

SECTION A: MCQ
1.The first line of Python code can’t have an indentation. Say True or False
Ans: True
2. Which of the following expression is not allowed in if statement
a) arithmetic expression b) relational expression c) logical expression d) none
Ans: a.
3. x=[ ‘P’ , ‘ y’ , ‘t’ , ‘h’ , ‘o’ , ‘n’ ]
for i in x:
print(i,end=’’)
`a) P b) python c) P y t h o n d) PYTHON
Ans: c
4. Function range(3) is equivalent to :
a) range(1,3) b) range(0,3) c) range(0,3,1) d) range(1,3,0)
Ans: b or c
5. The else block of a loop will not get executed if a ……….statement has
terminated
the loop.
Ans: break
6. The range() function can only be used in ……… loops
Ans: for
7. The in and not in operators are also called as ………….
Ans: membership operators
8. For a while loop, an equivalent for loop can always be written. Say True or
False.
Ans: False
9. The range() function generates a sequence of …………type
Ans: list
10. for is a ……. loop whereas while is a ……….loop
Ans: counting, conditional

SECTION B : 2 marks question:


1) Define pass statement.
2) What is the difference between elif and else construct of if statement?
3) Write the equivalent while loop for the following for loop
n=20
for i in [1,10]:
n+=i
4) What is the output for the following code?
i=1
while(i<=7):
i*=2
print(i)
5) What is the output of the following loop?
for a in[1,4,7]:
print(a)
print(a*a)

FUNCTION - MODULES

CONTENT – REVIEW

TOPIC: FUNCTIONS
One of the main advantages of Python is the availability of a vast library of modules that can
be used for different purposes.
A module is a logical organization of Python code. Related code are grouped into a module
which makes the code easier to understand and use. Any python module is an object with
different attributes which can be bind and referenced.
Python programs can get access to code from another python module by importing the
file/function using import. The import statement is the most common way of invoking the
import machinery

There are three ways to access the code of other built-in/user defined modules using import

• import module_name
• from module_name import function_name/constant/object
• from module_name import *

import module_name
EXAMPLE
import math
print(math.pi)
# this searches for the module and links the module code to the module name in local scope.
#The module objects need to be prefixed with the module name to ensure name resolution.
from module_name import *

EXAMPLE:
from math import *
print(pi)
#this searches for the module and copies all the contents of the module into the global
memory of the importing program.

from module_name import function_name/constant/object


from math import pi
print(pi)
#this searches for the module and copies only the specific objects/methods into memory of
the importing program, thus reducing memory usage.

math Module
Python has a built-in module that you can use for mathematical tasks.
The math module has a set of methods and constants. Some of the important ones are:
Method Description
math.ceil() Rounds a number up to the nearest integer
math.cos() Returns the cosine of a number
math.fabs() Returns the absolute value of a number
math.factorial() Returns the factorial of a number
math.floor() Rounds a number down to the nearest integer
math.pow() Returns the value of x to the power of y
math.prod() Returns the product of all the elements in an iterable
Returns the closest value that can make numerator completely
math.remainder() divisible by the denominator
math.sin() Returns the sine of a number
math.sqrt() Returns the square root of a number
math.tan() Returns the tangent of a number
math.trunc() Returns the truncated integer parts of a number
Math Constants
Constant Description
Returns Euler's number
math.e (2.7182...)
Returns a floating-point positive
math.inf infinity
Returns a floating-point NaN
math.nan (Not a Number) value
math.pi Returns PI (3.1415...)
math.tau Returns tau (6.2831...)

Random Module
Python has a built-in module that you can use to make random numbers. Some of the methods
in the random module are:
Method Description

Returns a random number between the given


randrange() range
Returns a random number between the given
randint() range
Takes a sequence and returns the sequence in a
shuffle() random order
random() Returns a random float number between 0 and 1
Returns a random float number between two
uniform() given parameters

Statistics module
Python has a built-in module that you can use to calculate mathematical statistics of numeric
data.
Method Description
Calculates the harmonic mean (central location) of
statistics.harmonic_mean() the given data
statistics.mean() Calculates the mean (average) of the given data
Calculates the median (middle value) of the given
statistics.median() data
statistics.median_grouped() Calculates the median of grouped continuous data
statistics.median_high() Calculates the high median of the given data
statistics.median_low() Calculates the low median of the given data
Calculates the mode (central tendency) of the given
statistics.mode() numeric or nominal data
Calculates the standard deviation from an entire
statistics.pstdev() population
Calculates the standard deviation from a sample of
statistics.stdev() data
statistics.pvariance() Calculates the variance of an entire population
statistics.variance() Calculates the variance from a sample of data

WORKSHEETS
SL QUESTION
NO
1 Predict the output:
from math import *
x=10
y=pi * sqrt(pow(x,4))
2 Identify the errors and correct them:
Import math
Y=25
S=sqrt(Y)
print(S)
3 Predict the output:
import math
num=90.23
print(math.ceil(num))
print(math.floor(num))
4 Predict the output: (What are the possible values?)
import random
print(random.random(5))
5 Predict the output:
li=[1,2,3,4,5,6,7,8,9,10]
from statistics import *
print(mean(li))
print(median(li))
6 Identify the errors and correct them:
li=[1,2,3,4,5,6,7,8,9,10]
from statistics import *
print(li.mean())
print(statistics.median(li))
7 Predict the output: (What are the possible values?)
import random
print(random.randint(5,10))
8 Predict the output: (What are the possible values?)
import random
print(random.randrange(10,20,2))
9 Write program to find square root of a function using math module
10 Predict the output:
li=[1,2,3,4,4,4,4,4,4,5,5,5,5,5,6,7,8,8,8,8,9,10]
from statistics import *
print(mode(li))
STRINGS

CONTENT – REVIEW
WORKSHEETS

CLASS: XI (LEVEL 1)
1. If first= “FIRE STOP” with string values then what will be the output of first[3] and
first[6].
2. Write the name of membership operators used for string data type.
3. What will be the result of following expression:
a. len(“Papaya”)
b. “Co” in “country
c. “divya”>”Divya
4. Evaluate following expressions for given string :
string1=”My work”
a. string1[3:6]
b. string1[: : 2]
c. string1*2
5. Write differences between upper() and isupper() functions.
6. Asha is using Python idle and try to capitalize first character of each word and using
following code:
address= “ ram sita radha riya”
address.upper()
But all the characters changed in uppercase , so suggest her the built in function name which
can fulfill her requirements.
7. Which of the following operator is used for concatenation of two strings?
a. - b. * c. + d. /
8. Which function will remove leading space from the given string?
9. Find out the errors and write the correct code :
a= “hello”
b=a* ”2”
c=a+b
10. Write a program which can check whether the given character is uppercase or lowercase
letter
CLASS: XI (LEVEL 2)

1. Which of the following function is used for checking whether the given value is number
or not:
a. isalpha() b. isdigit() c. isalnum() d. None of the above
2. How is capitalize() function different from upper() function?
3. What will be the output of following code:
str= “Hello India”
p=2 * str + 2* “wow”
print(p)
4. Write down the output after performing given function:
a. ”Very good”.title()
b. “ Bye Bye”.rstrip()
c. “favourite.index(‘u’)
5. What is the use of endswith() function?
6. Pooja is writing a program for entering mobile number of her friends and try to check
whether the given input is number and writing following code:
a= int(input(“enter phone no.”))
If a.isalnum()==True:
print(“valid number”)
else:
print(“not valid”)
So suggest her the correct function for getting her desired output and write correct code.
7. Find out the error in the given code and write the reason :
name=”priyanshi”
name[4]=a
8. Write the difference between endswith() and endswith()
9. Define slicing and explain with examples.
10.Write a program which replaces all vowels in the string with ’*’ .

WORKSHEET FOR COMPUTER SCIENCE

CLASS: XI (LEVEL 3)
1. What is the use of join () function and write one example?
2. Write the output of following code:
first=” Programming Language Learning work”
first.partition(“Language”)
3. What is the difference between join and partition?
4. Evaluate the following expression :
a. “$$”.join(“My”, “Godness”)
b. “No need “.rstrip()
c. “Going For walk”.split(“ “)
5. Find the output of following statements:
str1= “Interesting”
print(str1[2:7])
print(str1[-1:-5:-1])
print(str1[: : 2])
print(str1[-5:0:1])
6. Function………………… raises an exception if the substring is not found.
7. s= ‘ ‘ (single space).Then s.isalnum() will return .
a. True b. False c. Error d. None
8. Ravi wanted to search the index of the word “work” in his program and wrote the following
code in Python but it produced a value error. He did not understand what was wrong with the
code .
“My School work”.index(“ Work”)
Suggest him the code(other function name) which will not produce errors.
9. Write a program to input a string and calculate the length of each word present in string
and print length along with the word.
10.a Write a program to input a string and print the total number of uppercase and lowercase
letters in a given string.

COMPETENCY BASED

CASE BASED QUESTIONS

1. Asha is using Python idle and try to capitalize first character of each word and using
following code:
address= “ ram sita radha riya”
address.upper()
But all the characters changed in uppercase , so suggest her the built in function name
which can fulfill her requirements.
2. Pooja is writing a program for entering mobile number of her friends and try to check
whether the given input is number and writing following code:
a= int(input(“enter phone no.”))
If a.isalnum()==True:
print(“valid number”)
else:
print(“not valid”)
So suggest her the correct function for getting her desired output and write correct code.
3. Ravi wanted to search the index of the word “work” in his program and wrote the
following code in Python but it produced a value error. He did not understand what was
wrong with the code .
“My School work”.index(“ Work”)
Suggest him the code(other function name) which will not produce errors.
COMPETENCY BASED QUESTION

1. Write a program to input a string and calculate the length of each word present in string
and print length along with the word.
2. Write a program to input a string and print the total number of uppercase and lowercase
letters in a given string.
3. A string is given of three or more words, now the task is to write a Python program to
check whether a specific word is present in that given string.
4. program to read a string and display it in reverse order- display one character per line.
FLASH CARDS
LISTS MANIPULATION

CONTENT – REVIEW
WORKSHEETS

CLASS: XI - List (LEVEL 1)

1. If L= [15, 25, 30, 5, 10, ‘python’, ‘program’] then what will be the output of L[5] and
L[2].
2. Why are lists called mutable types?
3. Write the name of the joining operator used for list data type.
4. Evaluate following expressions for given list:
a = [5, 4, 3, 10, 6]
i. a[0]
ii. a[-2]
iii. a[2:5]
5. What will be the result of following expression:
L=[20, 3, 5, 11, 15]
a. len(L)
b. L + “abc”
c. L * 3
6. What is the difference between pop( ) and remove( ) method.
7. Which of the following operator is used for replicating a list?
a. - b. * c. + d. /
8. Which function will return the smallest element from a list?
9. Find out the errors and write the correct code :
a=[5, 6, 3, 4, 1]
b=a* ”3”
c=a+b
10. Write a program to find the largest and smallest number in a list.

CLASS: XI - List (LEVEL 2)


1. List can contain values of these types:
a. integers b. float c. lists d. all of these
2. Which of the following function is used to add an element at the end of the list.
a. extend() b. append() c. insert() d. None of the above
3. How to create a mixed data type list?
4. What will be the output of following code:
L=[3, 5, 1, 10, 2]
L.append(55)
print(L)
5. Write down the output after performing given function:
X = [5, 10, ‘python’, ‘XI’, 5.6]
a. X[X[0]]
b. X[-1 : -5]
c. X.insert(3, 99)
6. What is the use of the clear( ) function?
7. What will be the output of the following statements?
i) list1 = [12,32,65,26,80,10]
list1.sort( )
print(list1)
ii) list1 = [12,32,65,26,80,10]
sorted(list1)
print(list1)

iii)list1 = [1,2,3,4,5,6,7,8,9,10]
list1[::-2]
list1[:3] + list1[3:]

iv)list1 = [1,2,3,4,5]
list1[len(list1)-1]

8. Find out the error in the given code and write the reason :
sub=[‘eng’, ‘cs’, ‘ip’, ‘maths’, ‘che’]
sub + ‘phy’
9. Write the difference between sort( ) and sorted( ) functions.
10.Define slicing and explain with examples.
11.Write a program to input a list and an element, and remove all occurrences of the given
element from the list.

CLASS: XI - List (LEVEL 3)


1. What will be the output of following code:
l="Welcome to Python".split()
print(l)
2. What will be the output of following code:
a=[[[1,2],[3,4],5],[6,7]]
print(a[0][1][1] )
3. What will be the output of following program:
a=[2,1,3,5,2,4]
a.remove(2)
print(a)
4. Differentiate between append( ) and extend() function.
5. Write a Python Program to Find the Second Largest Number in a List .
6. What will be the output of following program:
my_list = ['p', 'r', 'o', 'b', 'l', 'e', 'm']
print('p' in my_list)
print('a' in my_list)
print('c' not in my_list)
7. What will be the output of the following program:
l=[6,12,18,24,30]
for i in l:
for j in range(1,i%4):
print(j,'#',end='')
print( )
8. Write a Program to Print list having numbers less than 10.
9. What will be the output of the following program:
10.l=[10,20,30,40,50,60]
for i in range(len(l)):
if(i%2==0):
print(l[i],end='#')
else:
print(l[i],end='@')
11.Take a list of 10 elements. Split it into middle and store the elements in two different lists.
E.g.- INITIAL list : 5 10 6 12 3 25 66 44 1 90
After splitting : 5 10 6 12 3
25 66 44 1 90
12.What will be the output of following program:
odd = [1, 9]
odd.insert(1,3)
print(odd)
odd[2:2] = [5, 7]
print(odd)
13.What will be the output of following program:
list("a#b#c#d".split('#'))

FLASH CARDS
TUPLES

CONTENT – REVIEW
WORKSHEETS

Tuple – Worksheet L1 1. A tuple is declared as T = (12,5,6,9,8) What will be the value of sum(T)?
2. Which of the following is a Python tuple?

3. Suppose t = (1, 2, 4, 3), which of the following is incorrect?

4. State the output t=(1,2,3,4,5) print(t[1:4])

5. What is the data type of (1)?

COMPETENCY BASED

1. Write a program to input your friends name and their phone numbers, and store them as key
value pair in Dictionary
Perform the following operations
a) Display name and phone number of all your friends
b) Search for a friends name in your list , if found display their phone number
c) Delete a particular friend
d) Modify the phone number of an existing friend
e) Display the dictionaries in sorted order of friends
2. Write a program to create a dictionary from a String which tracks down no of items a
character is present in the string

3.Write a program to read email IDs of n number of students and store them in a tuple. Create
two new tuples, one to store only the usernames from the email ids and second to store the
domain names from the email ids. Print all three tuples at the end of the program.[Hint : you
may use the function split()]

4. Write a program to print the frequency of a number accepted from the user in the given tuple.

5. Create a dictionary which contains dice combinations as( tuple) keys and the prizes awarded
as values.
Write a program to take lot or ask user to enter the dice combination, check in the dictionary
and print appropriate message

DICTIONARIES

CONTENT – REVIEW
Dictionary

 Unordered collection of items / elements. Each item has two parts - key : value

 A mapping between key and it’s value, separated by colon (:)


 Items are enclosed in {} and separated by comma.

 Are optimized to retrieve data using key. So key (values) should be unique.

 They can be integer, float, string or tuple.

 D[key] can be used for accessing element, also to add element in an existing dictionary.

Creation- Using
 built - in function dict()
 assignment operator creates deep copy
 copy() creates shallow copy
 {} to create blank dictionary
Shallow and Deep Copy
Accessing Items

Accessing Items…

Adding an item
Updating an Item

Traversing
Built – in Functions

Built – in Functions

A Sample code to find frequency of vowel letters


A Sample code to draw lot

WORKSHEETS

I. Write Python statements to:


1. Create a dictionary which contains the name of airlines corresponding to the
flight number.

b. Concatenate following dictionaries to create a new one


dic1={1:10, 2:20}
dic2={3:30, 4:40}
Expected Result : {1: 10, 2: 20, 3: 30, 4: 40}

3 Add a key to a dictionary.

4 sum all the items in a dictionary

5 Sort (ascending and descending) a dictionary by value.

6 check if a given key already exists in a dictionary

7. multiply all the items in a dictionary

8. get the maximum and minimum value in a dictionary

9 print all unique values in a dictionary


10. check a dictionary is empty or not

11. print a dictionary in table format

II . What will be the output of the following code?


1.
dictionary = {"Roll":9 , "Class":8, "Section":’A’, “Marks”:90}
print("Roll" in dictionary)

2.
b. a = {}
a[1] = 6
a['1'] = 2
a[1]= a[1]+1
count = 0
for i in a:
count += a[i]
print(count)

CYBER SAFETY / SECURITY /


SOCIETY LAW AND ETHICS

CONTENT – REVIEW

Society, Law and Ethics

You might also like