0% found this document useful (0 votes)
151 views251 pages

GE3151

1. A computer is an electronic device that can store, process, and retrieve data quickly and accurately. It consists of five main components: input, memory, processing, output, and control units. 2. Computers are extremely fast, accurate, reliable, and can handle large volumes of repetitive tasks. They can store large amounts of data and recall it instantly. 3. While computers are powerful tools, they are limited in that they depend on human users and instructions. They also cannot express their own ideas. 4. Computers are used in many applications including homes, industries, education, entertainment, and medical fields to perform a wide range of tasks from online shopping to robot-assisted surger

Uploaded by

dropoutsree07
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
151 views251 pages

GE3151

1. A computer is an electronic device that can store, process, and retrieve data quickly and accurately. It consists of five main components: input, memory, processing, output, and control units. 2. Computers are extremely fast, accurate, reliable, and can handle large volumes of repetitive tasks. They can store large amounts of data and recall it instantly. 3. While computers are powerful tools, they are limited in that they depend on human users and instructions. They also cannot express their own ideas. 4. Computers are used in many applications including homes, industries, education, entertainment, and medical fields to perform a wide range of tasks from online shopping to robot-assisted surger

Uploaded by

dropoutsree07
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 251

GE3151 PROBLEM SOLVING AND PYTHON PROGRAMMING L T P C

3 0 0 3

COURSE OBJECTIVES: To understand the basics of algorithmic problem solving. To learn to solve problems
using Python conditionals and loops. To define Python functions and use function calls to solve problems. To
use Python data structures - lists, tuples, dictionaries to represent complex data. To do input/output with files in
Python.

UNIT I COMPUTATIONAL THINKING AND PROBLEM SOLVING 9


Fundamentals of Computing – Identification of Computational Problems -Algorithms, building blocks of algorithms
(statements, state, control flow, functions), notation (pseudo code, flow chart, programming language), algorithmic
problem solving, simple strategies for developing algorithms (iteration, recursion). Illustrative problems: find
minimum in a list, insert a card in a list of sorted cards, guess an integer number in a range, Towers of Hanoi.

UNIT II DATA TYPES, EXPRESSIONS, STATEMENTS 9

Python interpreter and interactive mode, debugging; values and types: int, float, boolean, string, and list;
variables, expressions, statements, tuple assignment, precedence of operators, comments; Illustrative programs:
exchange the values of two variables, circulate the values of n variables, distance between two points.

UNIT III CONTROL FLOW, FUNCTIONS, STRINGS 9

Conditionals: Boolean values and operators, conditional (if), alternative (if-else), chained conditional (if-elif-else);
Iteration: state, while, for, break, continue, pass; Fruitful functions: return values, parameters, local and global scope,
function composition, recursion; Strings: string slices, immutability, string functions and methods, string module;
Lists as arrays. Illustrative programs: square root, gcd, exponentiation, sum an array of numbers, linear search,
binary search.

UNIT IV LISTS, TUPLES, DICTIONARIES 9

Lists: list operations, list slices, list methods, list loop, mutability, aliasing, cloning lists, list parameters; Tuples: tuple
assignment, tuple as return value; Dictionaries: operations and methods; advanced list processing - list comprehension;
Illustrative programs: simple sorting, histogram, Students marks statement, Retail bill preparation.

UNIT V FILES, MODULES, PACKAGES 9


Files and exception: text files, reading and writing files, format operator; command line arguments, errors and
exceptions, handling exceptions, modules, packages; Illustrative programs: word count, copy file, Voter’s age
validation, Marks range validation (0-100).

TOTAL : 45 PERIODS

COURSE OUTCOMES: Upon completion of the course, students will be able to CO1: Develop algorithmic
solutions to simple computational problems. CO2: Develop and execute simple Python programs. CO3: Write simple
Python programs using conditionals and looping for solving problems. CO4: Decompose a Python program into
functions. CO5: Represent compound data using Python lists, tuples, dictionaries etc. CO6: Read and write data
from/to files in Python programs.

TEXT BOOKS:

1. Allen B. Downey, “Think Python: How to Think like a Computer Scientist”, 2nd Edition, O’Reilly Publishers,
2016.
2. Karl Beecher, “Computational Thinking: A Beginner's Guide to Problem Solving and programming”, 1st
Edition, BCS Learning & Development Limited, 2017.

REFERENCES:

1. Paul Deitel and Harvey Deitel, “Python for Programmers”, Pearson Education, 1st Edition, 2021.

2. G Venkatesh and Madhavan Mukund, “Computational Thinking: A Primer for Programmers and Data
Scientists”, 1st Edition, Notion Press, 2021.

3. John V Guttag, "Introduction to Computation and Programming Using Python: With Applications to
Computational Modeling and Understanding Data‘‘, Third Edition, MIT Press 2021.

4. Eric Matthes, “Python Crash Course, A Hands - on Project Based Introduction to Programming”, 2nd Edition, No
Starch Press, 2019.

5. https://www.python.org/ 6. Martin C. Brown, “Python: The Complete Reference”, 4th Edition, Mc-Graw Hill,
2018.
GE3151 Problem Solving and Python Programming

FUNDAMENTALS OF COMPUTING:
A computer is an electronic device that performs sequences of arithmetic or logical operations on
information or data. Computers can store, retrieve, and process data. A computer consists of five main
components: 1) Input Unit, 2) Memory Unit, 3) Processing Unit, 4) Output Unit, and 5) Control Units.

1. Input Unit accepts information from user using devices such as keyboards, mouse, etc. It
also accepts information from other computers over digital communication lines.
2. Memory Unit stores the information received from the user. The information is either
used later or processed immediately by the processing unit.
3. Processing Unit (or) Arithmetic and Logic Unit (ALU) transforms the input into
output. All calculations & comparisons are made in the processing Unit.
4. Output Unit sends back the results of processing unit to the user. Some output units are
monitor, printer, etc.

5. Control Unit coordinates all the actions of the computer. Control unit allows all units to
exchange information and coordinate their actions. It provides the sequence in which all
operations need to be performed.

Page 1 of 11 Rohini College of Engineering and Technology


GE3151 Problem Solving and Python Programming

Characteristics of Computers:

1. Speed - A computer works with high speeds than compared to humans. Speed of the
computer is measured in microseconds or nanoseconds. Computers can run millions of
instructions per second.
2. Accuracy - Computers perform operations with 100% accuracy. Errors may occur due to
wrong input by human.
3. Diligence - Computer perform repeated operations with the same consistency and
accuracy. It doesn’t feel any fatigue or lack of concentration.
4. Versatility - Versatility means a computer can perform different kinds of works with same
accuracy and efficiency.
5. Reliability - A computer gives consistent result for similar set of data. We will get the
same output, for the same input always.
6. Automation - Computers performs all the operations automatically, without human
intervention.
7. Memory - A computer has built-in memory called primary memory. Primary memory
stores data during execution. Secondary memory stores data permanently.

Page 2 of 11 Rohini College of Engineering and Technology


GE3151 Problem Solving and Python Programming

Capabilities of Computers:
1. Computers are extremely fast, accurate and reliable.
2. It can handle large volumes of repetitive tasks with high accuracy.
3. It stores large amounts of data in its memory, and it can recall data instantly.
4. It can communicate with other machines, called interactive processing.
5. It can do critical and dangerous jobs that may be hazardous to humans.
6. It can be used in decision making that answers either yes or no.
Limitation of Computers:
1. Computer's biggest limitation is their dependence on humans. A
computer can only accept instructions from users and cannot do
anything on their own.
2. Computers cannot express their ideas.
3. Only the user who knows computer can use the computer.
Applications of Computers:
Computers play an important role in every day human activities.
They are used in homes, business, educational institutions, research
organizations, medical field, government offices, entertainment, etc.

1. Home - Computers are used at homes for online bill payment, watching
movies at home, social media activities, playing games, etc. They help to
avail work-from-home facility for employees.

2. Medical Field - Computers are used in hospitals to maintain patients’


history, diagnosis, and live monitoring of patients, etc. Nowadays critical
surgeries can be done by robots. It also helps to monitor the fetus inside the
mother’s womb.

3. Industry - Computers are used for interior designing, video conferencing,


product manufacturing etc. Online marketing sells various products to every
part of the India. Many company products are auto-engineered by robots.

4. Education - Computers are used in online education, online examinations,


video classes, etc. Computer is used in education from Kinder Garden to
University.

Page 3 of 11 Rohini College of Engineering and Technology


GE3151 Problem Solving and Python Programming

5. Entertainment - Computers help to watch movies online, play games online,


listening to music, etc. Photo editors and Video creators are available with
many features.

6. Defense - Computers are used in country’s defense department. Computers


help in satellite communication, missile development, rocket launchers, etc.

7. Banking - Computers are used to perform online transactions, ATMs, Net-


Banking facilities, etc. Banks have reduced human works with the use of
computers.
8. Science and Engineering - Supercomputers are used in the area of Research
and Development (R&D). 3D images of buildings can be created through
computers. It is also used to detect earthquakes and other disasters sooner.

Generations of a Computer
Growth in the computer industry is determined by the development in technology. Based on
various stages of development, computers can be categorized into different generations.
Sl. Generation Period Main Merits/Demerits
No Component
used
1 First 1940-1956 Vacuum • Big in size
Generation Tubes • Consumed more power
• Malfunction due to overheat
• Machine language was used.
Eg: ENIAC , EDVAC , UNIVAC 1
2 Second 1956-1964 Transistor • Smaller compared to First
Generation Generation
• Generated less heat
• Consumed less power compared
to first generation
• Punched cards were used
• First operating system was
developed - Batch Processing
and Multiprogramming
Operating System
• Machine language as well as
Assembly language was used.
Eg: IBM 1401, IBM 1620

Page 4 of 11 Rohini College of Engineering and Technology


GE3151 Problem Solving and Python Programming

3 Third 1964-1971 Integrated • Computers were smaller, faster


Generation Circuits and more reliable
• Consumed less power
• High Level Languages were
used.
Eg: IBM 360 Series,
Honeywell 6000 Series
4 Fourth 1971-1980 Micro • Smaller and Faster
Generation Processors • Microcomputer series such as
IBM and APPLE were
developed
• Portable Computers were
introduced.
5 Fifth 1980 – Till Ultra Large- • Parallel Processing
Generation Date Scale • Super conductors
Integration • Computer’s size was drastically
reduced.
• Can recognise Images and
Graphics.
• Introduction of Artificial
Intelligence and Expert Systems
• Able to solve high complex
problems including decision
making and logical reasoning

6 Sixth In Future • Parallel and Distributed


Generation computing
• Computers have become
smarter, faster and smaller
• Development of robotics
• Natural Language Processing
• Development of Voice
Recognition Software

COMPUTING DEVICES

• A computing device is a functional unit that can perform substantial computations,


including numerous arithmetic operations and logic operations without human
intervention. A computing device can consist of a standalone unit or several
interconnected units.

• Computing devices are the mathematical devices which can do the math muchin faster
way. They do the math calculations on the streams of binary digits (0and 1) and produce

Page 5 of 11 Rohini College of Engineering and Technology


GE3151 Problem Solving and Python Programming

the results in different forms that we need.

• The computing devices include Personal Computers or desktops, Notebook computers


or laptops, Net book, Tablets, Hand-held computers or PDAs, Smart Phones, Mini
Computers, Mainframes, wearable computers and supercomputers.

Desktop Computer or Personal Computer (PC)

• It is a stand-alone machine that can be placed on the desk.

• It consists of three units. They are keyboard, monitor, and a system unit
containing the CPU, memory, hard disk drive, etc.
• It is not very expensive and it is used in home, small business units, and
organizations.
• Examples: Apple, Microsoft, HP, Dell and Lenovo are some of the PC
manufacturers.

Notebook Computers or Laptop

• Note book computers are portable computers.


• They are small in size, has a battery backup and costlier than desktopcomputers.
• They can be carried anywhere, and has all the functionality of the desktop.
• Laptops can be placed on the lap while working.

Page 6 of 11 Rohini College of Engineering and Technology


GE3151 Problem Solving and Python Programming

Net book

• Net book = Internet + Notebook.


• These are smaller notebooks optimized for low weight and low cost, and aredesigned
for accessing web-based applications.
• They can be used for streaming videos or music, emailing, web surfing orinstant
messaging.

Tablet Computer

• A tablet computer does not have keyboard and mouse. It can accept input froma stylus
or a pen.
• It is a portable computer.
• It is a new kind of PC.

Handheld computer or Personal Digital Assistant (PDA)

• It is small in size. Instead of the keyboard, PDA uses a pen or a stylus forinput.
• PDAs do not have a disk drive. They have a limited memory and are less
powerful.

Page 7 of 11 Rohini College of Engineering and Technology


GE3151 Problem Solving and Python Programming

• PDAs can be connected to the Internet via a wireless connection.


• Examples: Casio and Apple computers. PDAs have merged into mobilephones
to create smart phones.

Smart Phones

• They are cellular phones that function both as a phone and as a small PC.
• They may use a stylus or a pen, or may have a small keyboard.

• They can be connected to the Internet wirelessly.


• They are used to access the electronic-mail, download music, play games, etc.
• Blackberry, Apple, HTC, Nokia and LG are some of the manufacturers of smart
phones.

Minicomputers

• Minicomputers are digital computers, generally used in multi-user systems.


• They have high processing speed and high storage capacity than the
microcomputers.
• Minicomputers can support 4-200 users simultaneously.
• The users can access the minicomputer through their PCs or terminal. They are used for
real-time applications in industries, research centres, etc. PDP 11,IBM (8000 series) are
some of the widely used minicomputers.

Mainframe Computers

Page 8 of 11 Rohini College of Engineering and Technology


GE3151 Problem Solving and Python Programming

• Mainframe computers are multi-user, multi-programming and high- performance


computers.

• They are large powerful systems and operate at a very high speed. They havevery large
storage capacity centralized databases and can handle the workloadof many users.
• The mainframe computer accessed via a dumb terminal, an intelligent terminal or a PC.
They use the processing power and the storage facility of the mainframe computer.
• A dumb terminal cannot store data or do processing of its own. It has the inputand output
device only.
• An intelligent terminal has the input and output device, can do processing, butcannot
store data of its own. Mainframe computers are used in organizations like banks or
companies, where many people require frequent access to the same data.
• Examples: CDC 6600 and IBM ES000 series.

Wearable Computers

• A wearable computer or body-borne computer, is a computing device worn on the body.


Wearables are an example of mobile computing.
• They have specialized purposes such as fitness trackers. They mayincorporate special
sensors such as accelerometers, heart rate monitors, or on the more advanced side,
electrocardiogram (ECG) and blood oxygen saturation (SpO2) monitors.
• Wearable computers, include novel user interfaces such as Google Glass, an optical
head-mounted display controlled by gestures.
• Wearables are typically worn on the wrist (e.g., fitness trackers), hung from the neck
(like a necklace), strapped to the arm or leg (smartphones when exercising), or on the
head (as glasses or a helmet), though some have been located elsewhere (e.g., on a
finger or in a shoe).

Page 9 of 11 Rohini College of Engineering and Technology


GE3151 Problem Solving and Python Programming

Supercomputers

• Supercomputers are the fastest and the most expensive machines. They have high
processing speed compared to other computers.
• The speed of a supercomputer is generally measured in FLOPS (FLoating Point
Operations Per Second). Some of the faster supercomputers can perform trilions of
calculations per second.
• Supercomputers are built by interconnecting thousands of processors that canwork in
parallel.
• Supercomputers are used for highly calculation intensive tasks, such as, weather
forecasting, climate research (global warming), molecular research, biological
research, nuclear research and aircraft design.
• They are also used in major universities, military agencies and scientific research
laboratories.
• Some examples of supercomputers are IBM Roadrunner, IBM Blue gene andIntel ASCI
red.
• PARAM is a series of supercomputer assembled in India by C-DAC. PARAMPadma is
the latest machine in this series. The peak computing power of PARAM Padma is 1
TeraFLOP (TFLOP).

IDENTIFICATION OF COMPUTATIONAL PROBLEMS


• In computer science, a computational problem is a problem that a
computer might be able to solve or a question that a computer may be able
to answer.
• A computational problem can be viewed as a set of instances or cases
together with a possibly empty, set of solutions for every instance/case.
• Computation is any type of calculation that includes both
arithmetical and non- arithmetical steps and follows a well-defined
model. Eg.Algorithm.

Page 10 of 11 Rohini College of Engineering and Technology


GE3151 Problem Solving and Python Programming

Types of Computational Problems:


Decision Problems: Where the answer for every instance is either yer or no.
Search Problems: The answers can be arbitrary strings.
Counting Problems: Ask for the number of solutions to a given search
problem. Optimization Problems: Asks for finding a “best possible”
solution among the set of all possible solution to a search problem.
Core Concepts of Computational Thinking:
• Logical thinking
• Algorithmic thinking
• Decomposition
• Generalisation and pattern recognition
• Modelling
• Abstraction
• Evaluation
Computational
thinking allows us,
• To take a complex problem.
• Understand what the problem is.
• Develop possible solutions.
• Present these solutions in a way that a computer, a human,
or both, can understand.
In order to solve a problem computationally, two things are needed,
• A representation that captures all the relevant aspects of the problem.
• An algorithm that solves the problem by use of the representation.

Page 11 of 11 Rohini College of Engineering and Technology


GE3151 - Problem Solving And Python Programming

UNIT I: COMPUTATIONAL THINKING AND PROBLEM SOLVING


Fundamentals of computing, Identification of computational problems, Algorithms,
building blocks of algorithms (statements, state, control flow, functions), notation (pseudo code,
flow chart, programming language), algorithmic problem solving, simple strategies for developing
algorithms (iteration, recursion). Illustrative problems: find minimum in a list, insert a card in a
list of sorted cards, guess an integer number in a range, Towers of Hanoi.

- ALGORITHMS
An Algorithm is defined as step by step procedure for solving a problem. An Algorithm
is a well-defined computational procedure consists of a set of instructions that takes some values
as an input, then manipulate them by following prescribed texts in order to produce some values
as output.

INPUT ALGORITHM OUTPUT

–Two Phases of Algorithmic Problem Solving


• Derivation of an algorithm that solves the problem
• Conversion of an algorithm into code (or) program

–Data types and Data Structures:


In Algorithms the data are numbers, words, list & files. Algorithm provides the logic and
data provides the values.
Program = Algorithm + Data Structures
Data Structures refer to the types of data used and how the data are organized in the
program. The Programming languages provide simple data type such as Integers, real numbers
and characters.

– Characteristics of an Algorithm:
An algorithm should have the following characteristics.
Precision – the steps are precisely stated (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 stops after a finite number of instructions are executed.

Unit I Rohini College of Engineering and Technology Page 1.1


GE3151 - Problem Solving And Python Programming

Effectiveness – algorithm should be most effective among many different ways to solve
a problem.
Input – the algorithm receives input.
Output – the algorithm produces output.
Generality – the algorithm applies to a set of inputs.

1.1.4 – Qualities of an Algorithm:


The following factors will determine the quality of an algorithm.
Accuracy Algorithm should provide accurate results.
Memory It should require minimum computer memory.
Time The time taken to execute any program is considered as a main quality.
Sequence The procedure of an algorithm must be in a sequential form.

1.1.5 – Representation of an Algorithm:


An algorithm can be represented in a number of ways which include
Natural Language usually verbose and ambiguous.
Flow Chart pictorial representation of an algorithm
Pseudo Code resembles common elements of an language and no particular format
Programming Language Algorithms are the basis of programs. Expressed in High level
language.

Examples:
1. Write an algorithm to find the area of circle.
Step1: Start
Step2: Read the value of radius as r
Step3: Calculate area = 3.14*r*r
Step4: Print the value of area.
Step5: Stop

2. Write an algorithm to find the biggest of two numbers.


Step1: Start
Step2: Read the value of a and b
Step3: Compare the value of a sand b if a>b then

Unit I Rohini College of Engineering and Technology Page 1.2


GE3151 - Problem Solving And Python Programming

Print ‘A is largest” otherwise print ‘b is largest’


Step4: Stop

3. Write an algorithm for calculating total marks of specified number of subjects given as
66, 99, 98, 87, 89.
Step1: Start
Step2: Read Numbers as N
Step3: Initialize the value of Total as 0 and as 1
Step4: Repeat step 5 to step7 until i is less than n
Step5: Read the marks
Step6: Add mark to the total
Step7: Increment the value of i
Step6: Print the value of total
Step7: Stop

– Building Blocks of an Algorithm


There are four building blocks of algorithm which are
a) Instructions / Statement
i. Simple Statement
ii. Compound Statement
b) State
c) Control Flow
i. Sequence Control Structure
ii. Selection Control Structure
iii. Case Structure
d) Functions
a) Instructions / Statement
In Computer programming, a statement is a smallest standalone element which expresses
some action to be covered. It is an instruction written in a high level language that commands the
computer to perform a specified action. A program written in such language is formed by sequence
of one or more statements.
Ex:

Unit I Rohini College of Engineering and Technology Page 1.3


GE3151 - Problem Solving And Python Programming

An Algorithm to add two numbers:


Step-1: Start
Step-2: Declare variables num1, num2 and sum
Step-3: Read values num1, num2
Step-4: Add num1 and num2 and assign the result to sum
sum→num1+num2
Step-5: Display sum
Step-6: Stop
• There are two types of statements they are
i. Simple Statement
ii. Compound Statement
i) Simple Statement:
• Simple Statement consists of a single logical line.
Ex:
• Expression Statement
• Assignment Statement
• Print Statement
• Import Statement
ii) Compound Statement:
• Compound Statements consist of a group of statements. They control the execution of
other statements. It consists of one or more clauses.
Ex:
• if – statement
• while – statement
• for – statement
• try – statement
b) State
An algorithm is a deterministic automation for accomplishing a goal which given an
initial state, will terminate in a defined end state and internal state for performing an algorithm.
• Initial State starts by keyword “START” or “BEGIN”.
• Internal State starts from data, which is read as an input, written to an output and stored
for processing. The stored data is regarded as a part of Internal State.
• End State is nothing but the keyword “END”

Unit I Rohini College of Engineering and Technology Page 1.4


GE3151 - Problem Solving And Python Programming

c) Control Flow
Control Flow or Flow of Control is the order function calls, instructions and statement are
executed or evaluated when a program is running. Program Control structures are defined as the
program statements that specifies the order in which statements are executed. There are three types
of control structures. They are.
i. Sequence Control Structure
ii. Selection Control Structure
iii. Case Structure

i) Sequence Control Structure


• Sequence Control Structure is used to perform the actions one after another. It performs
process A and then performs process B and so on. This structure is represented by writing
one process after another.
• The logic is from top to bottom approach.

Start
Process 1

Read radius

Process 2 S=3.14*r*r

Print S

Process n
Stop

ii) Selection Control Structure


Selection Control Structure or Decision Control Structure allows the program to make a
choice between two alternate paths whether it is True or False.
1) IF….THEN
2) IF….THEN…ELSE
1) IF….THEN
• This choice makes between two processes.
o If the condition is true. It performs the process.

Unit I Rohini College of Engineering and Technology Page 1.5


GE3151 - Problem Solving And Python Programming

o If the condition is false. It skips over the process.

Pseudo code Flow Chart

IF Condition THEN
Process A
… IF
Condition


Process
END IF

2) IF….THEN…ELSE
• In this structure
o If the condition is true. It performs the process A.
o Else the condition is false. It executes process B.
• The process execution is depending on the condition.
Pseudo code Flow Chart
IF Condition THEN
Process A
IF
ELSE
Condition
Process B
Process A Process B
END IF

iii) Case Structure:


• This is a multi-way selection structures that is used to choose one option from many
options. If the value is equal to type 1 then it executes process-1, If the value is equal to
type 2 then it executes process-2 and so on. END CASE is used to indicate the end of the
CASE Structure.

Unit I Rohini College of Engineering and Technology Page 1.6


GE3151 - Problem Solving And Python Programming

Pseudo code Flow Chart


CASE TYPE
case Type-1:
Process 1 TYPE

case Type-2:
Process 2



Process 1 Process 2 Process N

case Type-n:
Process n
END CASE

d) Functions
Functions are "self-contained" modules of code that accomplish a specific task. Functions
usually "take in" data as INPUT, process it, and "return" a result as OUTPUT. Once a function is
written, it can be used over and over and over again. Functions can be "called" from the inside of
other functions. Functions "Encapsulate" a task (they combine many instructions into a single line
of code).
Ex:
>>>def add(num1,num2): #Function Definition
num3=num1+num2
print(“The sum is”,num3)
return num3
>>>a=10
>>>b=20
>>>c=add(a,b) #Function Call

Flow of a Function:
When a function is "called" the program "leaves" the current section of code and begins
to execute the first line inside the function. Thus the function "flow of control" is:
• The program comes to a line of code containing a "function call".
• The program enters the function (starts at the first line in the function code).

Unit I Rohini College of Engineering and Technology Page 1.7


GE3151 - Problem Solving And Python Programming

• All instructions inside of the function are executed from top to bottom.
• The program leaves the function and goes back to where it started from.
• Any data computed and RETURNED by the function is used in place of the function in
the original line of code.

Need for Functions


• Functions allow us to create sub-steps. (Each sub-step can be its own function and a
group of Instructions)
• They allow us to reuse code instead of rewriting it.
• Functions allow us to keep our variable namespace without any confusion.
• Functions allow us to test small parts of our program in isolation from the rest.

The Steps to Write a Function


• Understand the purpose of the function.
• Define the data that comes into the function (in the form of parameters).
• Define what data variables are needed inside the function to accomplish its goal.
• Decide the data produces as output to accomplish this goal.

Parts of a "black box" (or) Parts of a function


Functions can be called "black boxes" because we don't know how they work. We just
know what is supposed to go into them, and what is supposed to come out of them.
1. The Name - describes the purpose of the function. Usually a verb or phrase, such
as "compute_Average", or just "average".
2. The Inputs - called parameters. Describe what data is necessary for the function
to work.
3. The Calculation - varies for each function
4. The Output – The calculated values from the function and "returned" via the
output variables.
Function Workspace
Every function has its own Workspace which means that every variable inside the function
is only usable during the execution of the function. After that we cannot use the variable. The
variables can be created inside the function or passed as an argument.

Unit I Rohini College of Engineering and Technology Page 1.8


GE3151 - Problem Solving And Python Programming

Function Workspace
Every function has its own Workspace which means that every variable inside the function
is only usable during the execution of the function. After that we cannot use the variable. The
variables can be created inside the function or passed as an argument.

Formal Parameters vs. Actual Parameters


• Inside the circle function, the variable ‘r’ will be used in place to calculate radius.
• The parameter "r" is called a Formal parameter, this just means a place holder name for
radius.
The variable ‘radius’ is the Actual parameter, this means "what is actually used" for this call to
the function
Example:
Write a Python Program to find area of a circle:
>>>def circle(r): #Where ‘r’ is the Formal Parameter
rad=3.14*r*r
print(“The area of circle is”,rad)
>>>radius=9
>>>circle(radius) #Where ‘radius’ is the Actual Parameter

NOTATIONS (CLASSIFICATIONS OF AN ALGORITHM):


The Notations of an algorithm is classified into three
i. Pseudo code
ii. Flow Chart
iii. Programming Language
Pseudo Code:
• Pseudo code is a kind of structure English for designing algorithm.
• Pseudo code came from two words.
• Pseudo Means imitation
• Code means instruction
• Pseudo code is a text based tool for human understanding
• Pseudo cannot be compiled nor executed, and there are no real format or syntax rules
• The benefits of pseudo code is it enables the programmer to concentrate on the algorithm
without worrying about all syntactic details

Unit I Rohini College of Engineering and Technology Page 1.9


GE3151 - Problem Solving And Python Programming

Ex:
READ num1, num2
result = num1 + num2
WRITE result.

Basic Guidelines for writing Pseudo code:


• Write only one statement per line
• Each statement in your pseudocode should express just one action for the
computer
• Capitalize Initial Keyword
• The keywords should be written in capital letters. Ex – READ, WRITE, IF,
ELSE, WHILE
• Indent to show hierarchy (order)
• We use a particular Indentation in each design.
• For sequence statement Indent start from same column
• For selection & looping statement Indent will leave some space and fall inside
the column.
• Ex:
IF a>b then
print a
ELSE
print b
• End multi line Structures
• Each structure must be ended properly to provide more clarity
• Ex: END IF
• Keep statements language Independent.
• The statement should be Independent to the language we are using. The
language features should be used properly.

Advantages of Pseudo Code.


• Can be done easily on a word processor.
• Easily modified.
• Implements structured concepts well.
• No special symbols are used.
• It is simple because it uses English like statements.

Disadvantage of pseudo Code.


• It is not visual.
• There is no standard format.
• Cannot be compiled not executed.

Unit I Rohini College of Engineering and Technology Page 1.10


GE3151 - Problem Solving And Python Programming

Examples:
1. Write a pseudocode to find the area of circle.
BEGIN
READ radius r
INITIALIZE pi=3.14
COMPUTE Area=pi*r*r
PRINT r
2. Write a pseudocode to find the biggest of two numbers
BEGIN
READ A, B
IF A>B
PRINT “B is big”
ELSE
PRINT “A is big”
3. Write a pseudocode for calculating total marks of specified number of subjects given as
66, 99, 98, 87, 89
BEGIN
INITIALIZE total=0,i=1
WHILE i<n
READ mark
total=total+mark
INCREMENT i
PRINT i
END

Flowchart
• A flow chart is a diagrammatic representation that illustrates the sequence of operations
to be performed to arrive the solution.
• Each step in the process is represented by a different symbol and has a short description
of the process steps.
• The flow chart symbols are linked together with arrows showing flow directions.

Unit I Rohini College of Engineering and Technology Page 1.11


GE3151 - Problem Solving And Python Programming

Flow Chart Symbols:

S.No Name of the Symbol Symbol Meaning

Represent the start and stop of


1. Terminal
the program

Denoted either an input or


2. Input / Output
output operation.

Denotes the process to be


3. Process
carried out.

Represent decision making and


4. Decision
Branching
Represent the sequence of steps
5. Flow Lines
and directions of flow
Represent a circle and a letter or
6. Connectors digit inside the circle. Used to
connect two flow charts

Types of Flow Chart:

• High Level Flow Chart:


• Shows major steps in the process.
• Which also includes intermediate outputs of each step.

• Detailed Flow Chart:


• Which provides detailed picture of a process by mapping all steps
• Which gives the detail about all the steps
• Deployment or Matrix Flow Chart:
• Which maps out the process in terms of who is doing the steps.
• Which is in the matrix format.
• Which shows various participants and the flow of steps among those participants.

Unit I Rohini College of Engineering and Technology Page 1.12


GE3151 - Problem Solving And Python Programming

Basic Guidelines for preparing Flow Chart:


• Flow chart should have all necessary requirements and should be listed out in logical
order.
• The Flow Chart should be clear neat and easy to follow. There should not be any
ambiguity.
• The usual direction of the flow chart is from left to right and top to bottom.
• Only one flow line should come out from a process symbol

(or)

• Only one flow line should enter a decision symbol but two or three flow lines can leave.

• Only one flow line is used in conjunction with terminal symbol

Start Stop

• Write within standard symbols briefly. You can also use annotation symbol to describe
the data more clearly.

– – – Calculation Part

• If the flowchart becomes complex then it is better to use connector symbols to reduce the
number of flow lines.

• Flow chart should have a start and stop.

• Validity of a flow chart can be tested by passing through it with a simple test data.
Advantages of Flow Chart:
• Flow Charts are better in communication.

• A Problem can be analyzed in an effective way.

• Program Flow Charts Serve as a good documentation.

• Flow Charts acts as a blue print during system analysis and program development phase.

Unit I Rohini College of Engineering and Technology Page 1.13


GE3151 - Problem Solving And Python Programming

• The maintenance of operating program becomes easy with the help of flow chart.
Disadvantages of Flow Chart:
• Sometimes the program logic is quite complicated, In that case flowchart becomes
complex and clumsy.
• If alterations are required the flowchart may require re-drawing completely.
• As the flowchart symbols cannot be typed, reproduction of flowchart becomes a problem.
Example:
1. Draw a flowchart to find the area of circle.

Start

Read r

area=3.14*r*r

Print area

Stop

Unit I Rohini College of Engineering and Technology Page 1.14


GE3151 - Problem Solving And Python Programming

2. Draw a flowchart to find the biggest of two numbers

Start

Read a,b

If
yes No
a>b

print a is big print b is big

Stop

Unit I Rohini College of Engineering and Technology Page 1.15


GE3151 - Problem Solving And Python Programming

3. Draw a flowchart for calculating total marks of specified number of subject

Start

Read N

Total=0
i=1

Yes If No
i<n

Print total Read Mark

Stop Total=Total+Mark

i=i+1

Unit I Rohini College of Engineering and Technology Page 1.16


GE3151 - Problem Solving And Python Programming

1.3.3 Programming Languages:


A computer is the ideal machine to execute computational algorithms because:
• A computer can perform arithmetic operations
• It can also perform operations only if it satisfies some condition.
A Programming language is a specialized language used to instruct the computer to solve
a particular problem.
Types of Computer Programming Languages
There are three types of languages used in computer
i. Machine Language
ii. Assembly Language
iii. Programming Language
i) Machine Language
• Machine Language is also Known as Binary language or Low Level Language.
• Machine Language consists of 0’s and 1’s.
• Each Computer has its own machine language.
• The Machine Language encodes the instructions for the computer.
Ex:
01010010101

ii) Assembly Language


An Assembly language consists of English like mnemonics. There is one mnemonic for
each machine instructions of the computer.
An assembler is used to convert the assembly language into an executable machine code.
Ex for An Assembly language:
Start
add x,y
sub x,y


End

Unit I Rohini College of Engineering and Technology Page 1.17


GE3151 - Problem Solving And Python Programming

Difference between Pseudo Code and Assembly Language.

S.No Pseudo Code Assembly Language


Pseudo Codes are not compiled or Assembly Language should be compiled and
1.
executed. should be executed.
Pseudo Code should not have a Assembly Language should have a specified
2.
specified format. format known as mnemonics.

iii) High Level Programming Language


• A High Level Programming Language consist of people language to simplify the
computer algorithms.
• A High Level Programming Language allows the programmer to write sentence in the
language which can be easily translated into machine language.
• The sentence written in High Level Programming Language is called as statements.
Ex for High Level Programming Language:
main()
{
if(x<y)
{
print(“x is greater”)
}
else
{
print(“y is greater”)
}
}

Some High Level Programming Language:


1. Fortan
2. C
3. C++
4. Java
5. Pearl

Unit I Rohini College of Engineering and Technology Page 1.18


GE3151 - Problem Solving And Python Programming

Define Compiler:
• A Compiler is a computer software that transforms computer code written in High Level
Programming Language into Machine Language (0,1) as well as vice versa.
Define Interpreter:
• An Interpreter translates a High Level Programming Language into an immediate form of
Machine Level Language. It executes instructions directly without compiling.
Define Assembler:
• An Assembler is used to convert the Assembly Language into an executable Machine
Level Language.
Define Computer Program:
• A Computer Program is a combination of Computer algorithm and a Programming
language. Most programs are English like languages.
• A Computer Program will solve the problem specified in the algorithm.
Algorithmic Problem Solving:
A sequence of steps involved in designing and analyzing an algorithm is shown in the
figure below.

Understand the Problem

Decide on Computational Means,


exact vs approximate solving
algorithmic design technique

Design an algorithm

Prove Correctness

Analyze the algorithm

Code the algorithm

Unit I Rohini College of Engineering and Technology Page 1.19


GE8151 - Problem Solving And Python Programming

i) Understanding the Problem


• This is the first step in designing of algorithm.
• Read the problem’s description carefully to understand the problem statement
completely.
• Ask questions for clarifying the doubts about the problem.
• Identify the problem types and use existing algorithm to find solution.
• An Input to an algorithm specifies an instance of the problem and range of the input to
handle the problem.
ii) Decision making
The Decision making is done on the following:
a) Ascertaining the Capabilities of the Computational Device
• After understanding the problem one need to ascertain the capabilities of the
computational device the algorithm is intended for.
• Sequential Algorithms:
o Instructions are executed one after another. Accordingly, algorithms designed to
be executed on such machines.
• Parallel Algorithms:
o An algorithm which can be executed a piece at a time on many different
processing device and combine together at the end to get the correct result.
iii) Choosing between Exact and Approximate Problem Solving:
• The next principal decision is to choose between solving the problem exactly (or) solving
it approximately.
• An algorithm used to solve the problem exactly and produce correct result is called an
exact algorithm.
• If the problem is so complex and not able to get exact solution, then we have to choose an
algorithm called an approximation algorithm. i.e., produces an approximate answer.
Ex: extracting square roots.
iv) Deciding an appropriate data structure:
• In Object oriented programming, data structures is an important part for designing and
analyzes of an algorithm.
• Data Structures can be defined as a particular scheme or structure to organize the data.

Algorithms+ Data Structures = Programs

Unit I Rohini College of Engineering and Technology Page 1.20


GE3151 - Problem Solving And Python Programming

v) Algorithm Design Techniques


• An algorithm design technique (or “strategy” or “paradigm”) is a general approach
to solve problems algorithmically that is applicable to a variety of problems from
different areas of computing.
• First they provide guidance for designing an algorithm.
• Second, they classify algorithm according to the design idea.

vi) Methods of specifying an algorithm:


• Once an algorithm is designed, we need to specify it some way. There are three ways to
represent an algorithm.
o Pseudo code – is structured English.
o Flowchart – a pictorial representation of an algorithm.
o Programming Language – a high level language to instruct computer to do some
action.
vii) Proving an algorithm’s correctness:
• Once an algorithm has been specified, it has to be proved for its correctness.
• An algorithm has to prove with the input to yield a required output with respective of
time. A Common technique is mathematical induction.
viii) Analyze the algorithm:
• For an algorithm the most important is efficiency. In fact, there are two kinds of
algorithm efficiency. They are:
o Time efficiency, indicating how fast the algorithm runs, and
o Space efficiency, indicating how much extra memory it uses.
• The efficiency of an algorithm is determined by measuring both time efficiency and
space efficiency.
Some factors to analyze an algorithm are:
o Time efficiency of an algorithm
o Space efficiency of an algorithm
o Simplicity of an algorithm
o Generality of an algorithm
ix) Coding of an algorithm:
• The coding / implementation of an algorithm is done by a suitable programming language
like C, C++, JAVA, PYTHON.

Unit I Rohini College of Engineering and Technology Page 1.21


GE3151 - Problem Solving And Python Programming

• The transition from an algorithm to a program can be done correctly and it


should be checked by testing.
• After testing, the programs are executed and this solves our problem.

Simple Strategies for Developing Algorithms (Iteration, Recursion:


Iteration:
An Iterative function is one that repeats some parts of the codes again and again until one
condition gets false.
Ex:
Write a Python program to print 10 values:
>>>i=0
>>>while i<=10:
print(“The Value of i is”,i)
i++
>>>

Recursion:
A Recursive function is the one which calls itself again and again to repeat the code. The
recursive function does not check any condition. It executes like normal function definition and the
particular function is called again and again.

Difference between Recursion and Iteration:


S.No Recursion Iteration
Recursion is achieved through
1. Iteration is explicitly a repetition structure.
repeated function calls.
Recursion terminates when a base case Iteration terminates when loop continuation test
2.
is recognized. becomes false.
Recursion causes a copy of function
Iteration normally occurs within a loop so extra
3. and additional memory space is
memory is omitted.
occupied.

Unit I Rohini College of Engineering and Technology Page 1.22


GE3151 - Problem Solving And Python Programming

Examples:
Algorithm, Pesudocode, Flowchart for finding Factorial using Recursion
1. Algorithm to find the factorial of given number using recursion
Step1: Start
Step2: Read the value of n
Step3: Call factorial(n) and store the result in f
Step 4: Print the factorial f
Step5: Stop
Subprogram
Step1: Start factorial(n)
Step2: If n is equal to zero then return the value 1
else return n*factorial(n-1).
Sep 3: Stop factorial

2. Write the pseudocode for finding the factorial using recursion


BEGIN factorial
READ n
f=factorial(n)
PRINT f
subprogram
Begin Factorial (n)
IF n==0 THEN return 1
ELSE return n*factorial(n-1)
END

Unit I Rohini College of Engineering and Technology Page 1.23


GE3151 - Problem Solving And Python Programming

3. Draw the flowchart for finding the factorial using recursion

Start Factorial(n)

Read n
Return
No if
n*factorial(n-1)
n==0
f =factorial(n)
yes

Print f Return 1

Stop
Stop

ILLUSTRATIVE EXAMPLES
Find Minimum in a list:
Algorithm:
Step1:Start
Step2:Read total number of elements in the list
Step3:Read the first element as E
Step4:MIN=E
Step5:SET i=2
Step6:If i>n goto Step 11 ELSE goto Step 7
Step7:Read ith element as E
Step8:if E < MIN then set MIN=E
Step9:i=i+1
Step10:goto Step 6
Step11:Print MIN
Step12:stop

Pseudocode
BEGIN
READ total number of elements in the list

Unit I Rohini College of Engineering and Technology Page 1.24


GE3151 - Problem Solving And Python Programming

READ the first element as E


SET MIN=E
SET i=2
WHILE I <= n
Read ith element as E
if E < MIN then set MIN=E
Start
i=i+1
Print MIN
Read N
END
Flow chart:
Read first Element as E

Min= E I=2

IS I<N

Read I th Element as E

Is N
E<N

MIN=E

I=I+1

Print MIN

Stop

Unit I Rohini College of Engineering and Technology Page 1.25


GE3151 - Problem Solving And Python Programming

Find how to insert a card in a list of sorted cards:


Insterting a card in a list of sorted card is same as inserting an element into a sorted array.
Start from the high end of the list, check to see where we want to insert the data. If the element is
less than then move the high element one position and next check with next element repeat the
process until the correct position and then insert the element.

Position 0 1 2 3 4 5
Original list 4 6 9 10 11
7>11 4 6 9 10 11
7>10 4 6 9 10 11
7>9 4 6 9 10 11
7>6 4 6 7 9 10 11

Algorithm:
Step 1: Start
Step 2: Declare variables N, List[], i, and X.
Step 3: READ Number of element in sorted list as N
Step 4: SET i=0
Step 5: IF i<N THEN go to step 6 ELSE go to step 9
Step 6: READ Sorted list element as List[i]
Step 7: i=i+1
Step 8: go to step 5
Step 9: READ Element to be insert as X
Step 10: SET i = N-1
Step 11: IF i>=0 AND X<List[i] THEN go to step 12 ELSE go to step15
Step 12: List[i+1]=List[i]
Step 13: i=i-1

Pseudocode
READ Number of element in sorted list as N
SET i=0
WHILE i<N
READ Sorted list element as List[i]
i=i+1
ENDWHILE
READ Element to be insert as X
SET i = N-1
WHILE i >=0 and X < List[i]
List[i+1] =List[i]
i=i–1

Unit I Rohini College of Engineering and Technology Page 1.26


GE8151 - Problem Solving And Python Programming

END WHILE
List[i+1] = X
Flow Chart
Start

Read no of element as E

i=0

i<N

Read Sorted List List[i]

Read x
i=N-1

i>=0 &&
X<List[i] N

List[i+1]=List[i]
i=i+1

List[i+1]=X

Stop

Unit I Rohini College of Engineering and Technology Page 1.27


GE8151 - Problem Solving And Python Programming

Find how to guess an integer number within a range:


The computer randomly selects an integer from 1 to N and ask you to guess it. The
computer will tell you if each guess is too high or too low. We have to guess the number by making
guesses until you find the number that the computer chose.
.
Algorithm
Step 1: Start
Step 2: SET Count =0
Step 3: READ Range as N
Step 4: SELECT an RANDOMNUMBER from 1 to N as R
Step 5: READ User Guessed Number as G
Step 6: Count = Count +1
Step 7: IF R==G THEN go to step 10 ELSE go to step 8
Step 8: IF R< G THEN PRINT “Guess is Too High” AND go to step 5 ELSE go to step9
Step 9: PRINT “Guess is Too Low” AND go to step 5
Step 10: PRINT Count as Number of Guesses Took

Pseudocode:
SET Count =0
READ Range as N
SELECT an RANDOM NUMBER from 1 to N as R
WHILE TRUE
READ User guessed Number as G
Count =Count +1
IF R== G THEN
BREAK
ELSEIF R<G THEN
DISPLAY “Guess is Too High”
ELSE
DISPLAY “Guess is Too Low”
ENDIF
ENDWHILE
DISPLAY Count as Number of guesses Took

Unit I Rohini College of Engineering and Technology Page 1.28


GE8151 - Problem Solving And Python Programming
Start

Count=0

Read range N

R=random Number from 1 to N

Read User guessesed Number G

Count=Count+1

IS
Y
R==G

IS
N
R>G

IS R>G Print “Grade is high”

Y
Print “Grade is too low”

Print count

Stop

Unit I Rohini College of Engineering and Technology Page 1.29


GE3151 - Problem Solving And Python Programming

1.4 Find the towers of Hanoi:


The Tower of Hanoi puzzle was invented by the French mathematician it has three poles
and a stack of disks, each disk a little smaller than the one beneath it. Their assignment was to
transfer all the disks from one of the three poles to another.
• This should be done with two important constraints.
o We can only move one disk at a time.
o We cannot place a larger disk on top of a smaller one.
Figure 1 shows an example of a configuration of disks in the middle of a move from the
first pole to the third pole.

An outline to solve this problem, from the starting pole, to the goal pole, using an
intermediate pole:
1. Move a tower of height-1 to an intermediate pole, using the final pole.
2. Move the remaining disk to the final pole.
3. Move the tower of height-1 from the intermediate pole to the final pole using the
original pole.
we can use the three steps above recursively to solve the problem.

Unit I Rohini College of Engineering and Technology Page 1.30


GE3151 - Problem Solving And Python Programming

Python Program to solve Towers of Hanoi:


>>>def moveTower(height,fromPole, toPole, withPole):
if height >= 1:
moveTower(height-1,fromPole,withPole,toPole)
moveDisk(fromPole,toPole)
moveTower(height-1,withPole,toPole,fromPole)
>>>def moveDisk(fp,tp):
print("moving disk from",fp,"to",tp)
>>>moveTower(3,"A","B","C")

Output:
moving disk from A to B
moving disk from A to C
moving disk from B to C
moving disk from A to B
moving disk from C to A
moving disk from C to B
moving disk from A to B

A recursive Step based algorithm for Tower of Hanoi


Step 1: BEGIN Hanoi(disk, source, dest, aux)
Step 2: IF disk == 1 THEN go to step 3 ELSE go to step 4
Step 3: move disk from source to dest AND go to step 8
Step 4: CALL Hanoi(disk - 1, source, aux, dest)
Step 5: move disk from source to dest
Step 6: CALL Hanoi(disk - 1, aux, dest, source)
Step 7: END Hanoi

A recursive Pseudocode for Tower of Hanoi


Procedure Hanoi(disk, source, dest, aux)
IF disk == 1 THEN
move disk from source to dest
ELSE
Hanoi(disk - 1, source, aux, dest) // Step 1
move disk from source to dest // Step 2
Hanoi(disk - 1, aux, dest, source) // Step 3

Unit I Rohini College of Engineering and Technology Page 1.31


GE3151 - Problem Solving And Python Programming

END IF
END Procedure
Flow Chart for Tower of Hanoi Algorithm

Begin Hanoi(disk,source,dest,aux)

IS disk==1

Honai(disk-1,source,aux,dest)
Move disk from source to dest

Move disk from source to dest

Honai(disk-1,source,aux,dest)

Stop

Unit I Rohini College of Engineering and Technology Page 1.32


GE3151 - Problem Solving And Python Programming

WORKSHEETS
1.1 Draw a Flowchart and write a pesudocode to add two numbers.

Flowchart:

Pseudocode:

Unit I Rohini College of Engineering and Technology Page 1.33


GE3151 - Problem Solving And Python Programming

1. 2. Draw a Flowchart and write a pesudocode to find biggest between three numbers.

Flowchart:

Pseudocode:

Unit I Rohini College of Engineering and Technology Page 1.34


GE3151 - Problem Solving And Python Programming

1. 3. Draw a Flowchart and write a pesudocode to find quadratic equation.

Flowchart:

Pseudocode:

Unit I Rohini College of Engineering and Technology Page 1.35


GE3151 - Problem Solving And Python Programming

1. 4. Draw a Flowchart and write a pesudocode to check a students grade.

Flowchart:

Pseudocode:

Unit I Rohini College of Engineering and Technology Page 1.36


GE3151 - Problem Solving And Python Programming

1. 5. Draw a Flowchart and write a pesudocode to check a number is even or odd.

Flowchart:

Pseudocode:

Unit I Rohini College of Engineering and Technology Page 1.37


GE3151 - Problem Solving And Python Programming

Find the sum of n numbers

Flowchart:

Pseudocode:

Unit I Rohini College of Engineering and Technology Page 1.38


GE3151 - Problem Solving And Python Programming

Draw a Flowchart and write a pesudocode to find Fibonacci series

Flowchart:

Pseudocode:

Unit I Rohini College of Engineering and Technology Page 1.39


GE8151 - Problem Solving And Python Programming

Draw a Flowchart and write a pesudocode to find factorial

Flowchart:

Pseudocode:

Unit I Rohini College of Engineering and Technology Page 1.40


GE3151 - Problem Solving And Python Programming

TWO MARKS
1. What is an algorithm? (University question)
Algorithm is an ordered sequence of finite, well defined, unambiguous instructions for
completing a task. It is an English-like representation of the logic which is used to solve the
problem. It is a step- by-step procedure for solving a task or a problem. The steps must be ordered,
unambiguous and finite in number.

2. Write an algorithm to find minimum of 3 numbers in a list. (University question)


ALGORITHM : Find Minimum of 3 numbers in a list
• Step 1: Start
• Step 2: Read the three numbers A, B, C
• Step 3: Compare A and B.
If A is minimum, go to step 4 else go to step 5 Step 4: Compare A and C.
If A is minimum, output “A is minimum” else output “C is minimum”. Go to step 6.
• Step 5: Compare B and C.
If B is minimum, output “B is minimum” else output “C is minimum”.
• Step 6: Stop

3. List the building blocks of an algorithm.


• Statements
• Sequence
• Selection or Conditional
• Repetition or Control flow
• Functions

4. Define statements. List its type


Statements are instructions in Python designed as components for algorithmic problem
solving. For example. An input statement collects a specific value from the user for a variable
within the program. An output statement writes a message or the value of a program variable to
the user’s screen.
5. Write the pseudo code to calculate the sum and product of two numbers and display.
BEGIN
INITIALIZE variables sum, product, number1, number2

Unit I Rohini College of Engineering and Technology Page 1.41


GE3151 - Problem Solving And Python Programming

READ number1, number2 sum = number1+ number2


PRINT “The sum is “, sum
COMPUTE product = number1 * number2
PRINT “The Product is “, product
END
6. What is a function?
Functions are "self-contained" modules of code that accomplish a specific task. Functions
usually "take in" data, process it, and "return" a result. Once a function is written, it can be used
over and over again. Functions can be "called" from the inside of other functions.

7. Write the pseudo code to calculate the sum and product displaying the answer on the
monitor screen.
BEGIN
INITIALIZE variables sum, product, number1, number2 of type real
READ number1, number2 sum = number1 +number2
PRINT “The sum is “, sum
COMPUTE product = number1 * number2
PRINT “The Product is “, product
END program
8. Give the rules for writing Pseudo codes.
o Write one statement per line.
o Capitalize initial keywords.
o Indent to show hierarchy.
o End multiline structure.
o Keep statements to be language independent
.
9. Give the difference between flowchart and pseudo code.
• Flowchart is a graphical representation of the algorithm.
• Pseudo code is a readable, formally English like language representation.
10. Define a flowchart.
A flowchart is a diagrammatic representation of the logic for solving a task. A flowchart is
drawn using boxes of different shapes with lines connecting them to show the flow of control. The
purpose of drawing a flowchart is to make the logic of the program clearer in a visual form.

Unit I Rohini College of Engineering and Technology Page 1.42


GE3151 - Problem Solving And Python Programming

11. Give an example of Iteration. a = 0


for i from 1 to 3 // loop three times
{
a=a+I // add the current value of i to a
}
print a // the number 6 is printed (0 + 1; 1 + 2; 3 + 3)

12. Write down the rules for preparing a flowchart.


• A flowchart should have a start and end,
• The direction of flow in a flowchart must be from top to bottom and left to right
• The relevant symbols must be used while drawing a flowchart.

13. Mention the characteristics of an algorithm.


• Algorithm should be precise and unambiguous.
• Instruction in an algorithm should not be repeated infinitely.
• Ensure that the algorithm will ultimately terminate.
• Algorithm should be written in sequence.
• Algorithm should be written in normal English.
• Desired result should be obtained only after the algorithm terminates.

14. Define the two modes in Python.


Python has two basic modes: script and interactive.
The normal mode is the mode where the scripted and finished .py files are run in the Python
interpreter. Interactive mode is a command line shell which gives immediate feedback for each
statement, while running previously fed statements in active memory

15. Give the various data types in Python


Python has five standard data types
• Numbers
• String
• List
• Tuple
• Dictionary

Unit I Rohini College of Engineering and Technology Page 1.43


GE3151 - Problem Solving And Python Programming

16. List out the simple steps to develop an algorithm.


Algorithm development process consists of five major steps.
• Step 1: Obtain a description of the problem.
• Step 2: Analyze the problem.
• Step 3: Develop a high-level algorithm.
• Step 4: Refine the algorithm by adding more detail.
• Step 5: Review the algorithm.

17. Give the differences between recursion and iteration


Recursion Iteration
Function calls itself until the base condition is Repetition of process until the condition fails.
reached.
Only base condition (terminating condition) is It involves four steps: initialization, condition,
specified. execution and updation.
It keeps our code short and simple. Iterative approach makes our code longer.
It is slower than iteration due to overhead of Iteration is faster.
maintaining stack.
It takes more memory than iteration due to Iteration takes less memory.
overhead of maintaining stack.

18. What are advantages and disadvantages of recursion?


Advantages Disadvantages
Recursive functions make the code look clean Sometimes the logic behind recursion is hard to
and elegant. follow through.

A complex task can be broken down into Recursive calls are expensive (inefficient) as
simpler sub-problems using recursion. they take up a lot of memory and time.

Sequence generation is easier with recursion Recursive functions are hard to debug.
than using some nested iteration.

19. Define control flow statement.


A program's control flow is the order in which the program's code executes. The control
flow of a Python program is regulated by conditional statements, loops, and function calls.

Unit I Rohini College of Engineering and Technology Page 1.44


GE3151 - Problem Solving And Python Programming

20. Write an algorithm to accept two number. compute the sum and print the
result. (University question)
Step 1: Start
Step 2: READ the value of two numbers
Step 3:Compute sum of two numbers
Step 4 :Print the sum
Step 5:Stop
21. Write an algorithm to find the minimum number in a given list of numbers. (University
question)
• Step 1: Start
• Step 2:Read the total number of element in the list as N
• Step3:Read first element as E
• Step 4:MIN=E
• Step 5:Set i=2
• Step6:IF i>n goto Step 11 ELSE goto Step 7
• Step 7:Read i th element as E
• Step 8:IF E<MIN then set MIN=e
• Step 9:i=i+1
• Step 10:goto step 6
• Step 11:print MIN
• Step12:Stop

22. Outline the logic to swap the contents of two identifiers without using the third variable
(University question)
• Step1: Start
• Step 2:Read A,B
• Step 3 :A=A+B
• Step 4:B=A-B
• Step5:A=A-B
• Step 6:Print A ,B
• Step 7:Stop

Unit I Rohini College of Engineering and Technology Page 1.45


Rohini College of Engineering and Technology GE3151

UNIT 2

DATA, EXPRESSIONS, STATEMENTS

Python interpreter and interactive mode, debugging; values and types: int, float, boolean, string,
and list; variables, expressions, statements, tuple assignment, precedence of operators,
comments; Illustrative programs: exchange the values of two variables, circulate the values of n
variables, distance between two points

1
Rohini College of Engineering and Technology GE3151

DATA, EXPRESSIONS, STATEMENTS


2. PYTHON INTRODUCTION
Python is a general purpose interpreted, object oriented, interactive, high level
programming language. It was developed by “GUIDO VAN ROSSUM” in 1991 at the National
Research Institute for Mathematics and Computer Science in Netherlands. Many of the python
features are originated from an interpreted language called”ABC”. In order to overcome the
limitations in ABC, Python language was developed. Since the developer was the fan of the BBC
comedy show “Monty Pythons Flying Circus”, he named the language as “PYTHON”.
Features of Python:
Easy to learn: Python is a simple programming language with few keywords, simple syntax
which is easy to learn.
Interpreted: Python is processed at runtime by the interpreter.
Interactive: We interact with interpreter directly to write our programs.
Object oriented: Python program is built around objects which combine data and
functionalities.
High level language: When writing a program, no need to bother about the low level details
such as managing memory etc.
Simple: It is a simple language. Reading a Python program feels like reading English.
Portable: Python can run a variety of platforms.
Free and open source: We can freely distribute copy of Python software.
Extendable: We can add low level modules to the Python interpreter easily.
Easy to maintain: Python source code is easy to maintain.
PYTHON INTERPRETER AND INTERACTIVE MODE
Python is an interpreted programming language, because Python programs are executed
by the python interpreter. Interpreter takes high level program as input and executes the program.
Interpreter processes the source program without translating it into a machine language at a
minimum time. It read lines and performs computations alternatively. The diagrammatic
representation of Python interpreter mode is given below.

2
Rohini College of Engineering and Technology GE3151

Source code
Output
Python
data
Interpreter
Input data

Fig 2.1: Interpreter


Compiler:
Compiler reads the entire source program and translates it to machine readable form
called object code or executable code. Once a program in compiled, the program can be executed
repeatedly without further translations.

Source code Compiler Machine code

Input data Executable Output data


program

Fig 2.2: Compiler


Difference between interpreter and compiler:
Sl.No Interpreter Compiler

Scans the entire program and translates


1 Translate program one statement at a time
the whole into machine code

2 No intermediate code is generated Generates intermediate code

3 Execution is slower Execution is faster

4 It require less memory It require more memory

3
Rohini College of Engineering and Technology GE3151

5 Example: Python Example: C,C++

There are two different modes to use the interpreter.


Interpreter mode (or) Script mode.
Interactive mode.
Python interpreter mode
Python interpreter mode is a mode, where scripted and finished .py files are run in the
python interpreter. The Python file is stored in the extension (.py). Python programs can be
executed in the following methods.
i) Using command line window
ii)Using python’s IDLE
iii)Directly from command prompt
i) Using command line window
The following steps are followed to use the command line window.
Open command line window
At the >>>prompt, type the following
print “HELLO PYTHON”
Press enter
To exit from python, type the following.
exit.
ii) Using python’s IDLE
IDLE (Integrated Development and Learning Environment) is a tool, which is included in
Python’s installation package. If we click the IDLE icon, it open the following python shell
window.

4
Rohini College of Engineering and Technology GE3151

iii) Directly from command prompt


The following steps are followed to use the command prompt.
Open text editor to write the program.
Type and save it by filename.py
Open command prompt, type the name of the program.
Press enter.

Python interactive mode


Python interactive mode is a command line shell which gives immediate feedback for
each statement. We interact with Python interpreter to write a program. Here the execution is
convenient for smaller programs. In interactive mode, we do the following steps.
User type the expression.
Immediately expression is executed.
Result is printed.

5
Rohini College of Engineering and Technology GE3151

VALUES AND TYPES


Values:
Values are the basic units of data, like a number or a string that a program manipulates.
Example: 2,’Hello World’. These values belong to different data types. That is 2 is an integer
data type and Hello World is a string data type.
Types/ Data types:
A type is a category of values. Integers(type int),floating point(type float),Booleans(type
bool),strings(type str) and lists ,tuples, dictionaries are predefined data types in python. They are
called built-in data types.

Data types

Numbers None Sequence Sets Mappings

1. Complex 1. Strings
2. Integer
2. Tuples Dictionary
3. Floating
point 3. Lists
4. Boolean
Fig 2.3: List of data types in Python
Integer (type int)
An integer data type represents the whole numbers. It represents positive and negative
numbers. Integer data type have unlimited size in Python.
Example: -3, 2 etc
Types of integer data type:
i) Regular integer
ii) Binary literals (base 2)
iii) Octal literals (base 8)
iv) Hexa decimal literals (base 16)
6
Rohini College of Engineering and Technology GE3151

i) Regular integer
They are normal integers.
Example:
>>>a=9293
>>>b= -136
ii) Binary literals (base 2)
A binary literal is of the form zero followed by an uppercase B or lowercase b. The
literals are 0 and 1.
Example:
>>>bin=0b1111
>>>print(bin)
Output:
15
iii) Octal literals (base 8)
An octal literal is a number prefixed with zero followed by either uppercase O or lower
case o. The literals are 0 to 7.
Example:
>>>oct=0O24
>>>print(oct)
Output:
20
iv) Hexa decimal literals (base 16)
A hexa decimal literal is prefixed by 0(zero) followed by an upper case X or a lower case
x. The literals are 0 to9, [a-f/A-F].
Example:
>>>hex=0x9A
>>>print(hex)
Output:
154

7
Rohini College of Engineering and Technology GE3151

Floating point numbers (type float)


Numbers with fractions or decimal points are called floating point numbers. Floating
point data type is used to represent scientific notations where the upper case ‘E’ or lower case ‘e’
signifies the 10th power.
Example 1: Example 2: Example 3:
>>>3.3e3 >>>112.9e2 >>>c=2.1
3300.0 11290.0 >>>type(c)
<type ‘float’>
Boolean (type bool)
Boolean data type was found by George Boole(1815-1864).It takes 2 values(True or
False).These two values are used when evaluating comparisons, conditional expressions etc. The
common way to produce boolean value is relational operator. The various relational operators
used in python are <,>, <=,>= etc.
Example 1: Example 2: Example 3:
>>>3<4 >>>a= (3>4) >>>a= (3>4)
True >>>a >>>a
False >>>type(a)
<type ‘bool’>

Strings (type str)


String is defined as collection of characters which may consist of letters, numbers and
special symbols or a combination of these types within quotes. An individual character in a string
is accessed using an index. The index should always be an integer (positive or negative). An
index starts from 0 to n-1.
Strings are immutable i.e. the contents of the string cannot be changed after it is created.
Python will get the input at run time by default as a string. Python treats single quotes is same as
double quotes.eg: ’hello’ or “hello”.
String operators:
Consider, X holds “python” and Y holds “program”.

8
Rohini College of Engineering and Technology GE3151

Operator Description Example

>>>X+Y
+ Concatenation-Adds values of 2 strings
python program

Repetition-creates new string.(i.e.)concatenate multiple >>>X*2


*
copies of same string python python

>>>x[0:3]
[] Slice-Gives the character from the given range.
pyt

>>>x[1:2]
[:] Range slice-Give the characters from the given range.
y

Membership-returns true if a character exists in the >>>t in X


in
given string. true

Membership-returns true if a character not exists in the >>>m not in X


not in
given string. true

Built-in string methods:


capitalize()-This function capitalizes the first letter of a string.
islower()-It returns true, if all the characters in given string are lower case
isupper()-It returns true, if all the characters in given string are upper case.
len(string)-Returns the length of the string.
lower()-Convert all upper case letters to lower case letters.
Example Program:
>>>str=”HelloPython”
>>>print str
HelloPython
>>>print str[0]

9
Rohini College of Engineering and Technology GE3151

>>>print str[0:3]
Hel
>>>print str[5:]
Python
>>>print str*2
HelloPython HelloPython
>>>print str+”welcome”
HelloPython welcome
Lists
List data type contains elements of various data types. Values in a list are called elements
or items of list. The list is enclosed by square brackets [ ], where items are separated by commas.
List values can be accessed using slice operator ([] or [:]) .The index 0 represents beginning of
the list and -1 represents ending of the list.
 list[0] represents beginning of list.
 list[-1] represents ending of list.
Syntax:
listname= [value1,value2,…value n]
Example:
>>>mylist = [10, 10.5, ‘programming’]
Example Program:
>>>mylist= ()
>>>mylist=[‘python’,10,10.5,’program’]
>>>print mylist
[‘python’,10,10.5,’program’]
>>>print mylist[1:3]
[10, 10.5]
>>>print mylist[2:]
[10.5,’program’]
>>>print mylist*2
10
Rohini College of Engineering and Technology GE3151

[‘python’,10,10.5,’program’,’python’,10,10.5,’program’]

>>>print mylist[-1]
[‘program’]

VARIABLES
Variable is a name that is assigned to a value. The value can be changed during execution
of a program. While creating a variable, memory space is reserved in memory. Based on the data
type of a variable, the interpreter allocates memory.
Syntax: variable name=value
Example: price=20
Rules for naming variables
Variable name can be any length.
They can contain both letters and numbers. But they cannot begin with numbers.
Both upper case and lower case letters are used.
Variable names are case sensitive.
Example: midname, midName, MidName are different variables.
Variable name cannot be any one of the keywords.
Assigning values to variables
The equal (=) sign is used to assign the values to variables.
Left of = operator is the name of the variable.
Right of = operator is the value of variable.
Example:
>>>X=5
>>>name=”Python”
>>>print X
5
>>>print name
Python
In the above program X and name are variables. The value of X is 5 and the value of name is
Python.
11
Rohini College of Engineering and Technology GE3151

EXPRESSIONS
Expression is a combination of values, variables, operators and operands. A value itself is
considered as an expression.
Example:
17 #expression
X #expression
x+17 #expression
Expression consists of combination of operators and operands.
Example:
5+ (8*k) #expression
The above expression consists of 2 sub expressions. That is 5 and (8*k).Here sub expression
(8*k) is evaluated first.
Evaluation of expressions:
When expression is typed at the prompt, the interpreter evaluates it, and finds the value of
expression.
Program:
>>>12+8 #expression
20
>>>n=100 #expression
>>>print(n) #expression
100
>>>100 #expression
100
STATEMENTS (or) I/O STATEMENTS
Statement is a section of code (or) instruction that represents a command (or) action.
Types of statements
i) Assignment statements
ii) Simultaneous assignment statements
iii) Input statements
iv) Print statements
12
Rohini College of Engineering and Technology GE3151

i)Assignment statements
Assignment statements assigns right of = symbol to left of = symbol.
Example:
>>>Name=’CSE’
>>>age=100
>>>Name
CSE
>>>age
100
ii) Simultaneous assignment statements
Simultaneous assignment statement is used to assign more number of values to more
variables simultaneously.
Example:
>>>x,y=10,20
>>>x
10
>>>y
20
>>>sum, diff=x+y, y-x
>>>sum
30
>>>diff
10

iii) Input statements


In input statements ‘input’ function is used to get the input from user.
Example:
>>>Name=input (“Enter the Name :”)
Enter the Name: CSE
>>>Name

13
Rohini College of Engineering and Technology GE3151

CSE

>>>Age=input (“Enter the age :”)


Enter the age: 100
>>> Age
100
iv) Print statements
Here ‘print’ function is used to print values to screen. It takes a series of values are
separated by commas.
Example:
>>>Name=input (“Enter the Name :”)
Enter the Name: Jovitha
>>>print (‘Hello’, Name)
Hello Jovitha
>>>print (‘Welcome’, Jovitha)
Welcome Jovitha
>>>print (‘Hello \n’,Name)
Hello
Jovitha
TUPLE ASSIGNMENT
Tuple is an immutable sequence of values. (i.e.) we cannot change the elements of
tuples. Tuples are created by using parenthesis ().Tuple is an ordered collection of values of
different data types. Tuple values are indexed by integers.
Example:
>>>t=(‘a’,’b’,’c’)
>>>t
(‘a’,’b’,’c’)
Tuple assignment is an assignment with tuple of variables on left side and tuple of expressions
on right side.
>>> X, Y, Z=100, -45, 0
>>> print X, Y, Z
14
Rohini College of Engineering and Technology GE3151

100 -45 0

Here left side is a tuple of variable. The right side is a tuple of expression.
Working of tuple assignment
i) The first variable in the tuple of left side is assigned to first expression in tuple of right side.
ii) Similarly, the second variable in the tuple of left side is assigned to second expression in
tuple of right side. Number of variables on left side and the number of expressions on the right
side must be same.
Example: Program on tuple assignment
>>>#empty tuple
>>>mytuple=( )
>>>mytuple
()
>>>#tuples having same datatypes
>>>mytuple=(1,2,3,4,5)
>>>mytuple
(1, 2, 3, 4, 5)
>>>#tuples having different datatypes
>>>mytuple=(1,”Python”,2.5)
>>>mytuple
(1,”Python”, 2.5)
>>>#tuple assignment
>>>X, Y, Z= mytuple
>>>X
1
>>>Y
Python
>>>Z
2.5

15
Rohini College of Engineering and Technology GE3151

PRECEDENCE OF OPERATORS
Operator:
An operator is a special symbol that is used to perform particular mathematical or logical
computations like addition, multiplication, comparison and so on. The value of operator is
applied to be called operands. For e.g., in the expression 4 + 5, 4 and 5 are operands and + is an
operator. The following tokens are operators in Python:

+ - * ** / // %

<< >> & | ^ ~ <>


< > <= >= == !=

Operator precedence:
When an expression contains more than one operator, precedence is used to determine
the order of evaluation. The order of evaluation depends on rules of precedence.
Rules of precedence
i) Parenthesis has the highest precedence.
Example: 5*(9-3)
Here expression in parenthesis is evaluated first.
5*(9-3) = 5 * (6) = 30
ii) Exponentiation has next highest precedence.
Example: 1+2**3
1+2**3 = 1 + 8 = 9
iii) Multiplication and division have next higher precedence than addition and subtraction.
Example: 3*2-1
3*2-1 = 6 – 1 = 5
iv) Operators with same precedence are evaluated from left to right (Except exponentiation).
The following table summarizes the operator precedence in Python, from the highest
precedence to the lowest precedence. Operators in the same box have the same precedence and
group from left to right (except for comparisons statements).

16
Rohini College of Engineering and Technology GE3151

Operator Description Associativity


(expressions...) Binding or tuple display
[expressions...] list display
left to right
{ key: value...} dictionary display
'expressions...' string conversion
x[index] Subscription
x[index:index] Slicing
left to right
x(arguments...) Call
x.attribute Attribute reference
** Exponentiation right-to-left
+x , -x Unary plus and Unary minus
left to right
~x Bitwise NOT
* Multiplication
/ Division
left to right
// Floor division
% Remainder
left to right
+, - Addition and Subtraction

Bitwise Left Shift and Right


<<, >> left to right
Shift
& Bitwise AND left to right
^ Bitwise XOR left to right
| Bitwise OR left to right

in, not in Membership tests


is, is not Identity tests Chain from left to right
<,<=,>,>=,<>,!=,== Comparisons

not Boolean NOT left to right


and Boolean AND left to right
or Boolean OR left to right
17
Rohini College of Engineering and Technology GE3151

The acronym PEMDAS is useful way to remember the rules. That is,
P (parenthesis first)
E (Exponent)
MD (multiplication and division)
AS (addition and subtraction)
Arithmetic evaluation is carried out using two phases from left to right. During the first phase
highest priority operators are evaluated. The second phase lowest priority operators are
evaluated.
Example:
6+4/2 is 8, not 5.
Example:
>>>X, Y, Z=2, 3, 4
>>>value=X-Y/3+Z*3-1
>>>print(“Result=”,value)
Result=12
COMMENTS
Comments are the non-executable statements explain what the program does. For large
programs it often difficult to understand what is does. The comment can be added in the program
code with the symbol #.
Comment contains information for persons reading the program. Comment lines are
ignored during program execution. Comment lines have no effect on the program results.
Example:
print ‘Hello, World!’ # print the message Hello, World!; comment
v=7 # creates the variable v and assign the value 7; comment
Types of comments
i) Single line comments
ii) Multi line comments
i) Single line comments - Single line comments describes information in one line(short),and
they start with the symbol #.Everything from the # to the end of the line is ignored, it has no
effect on the execution of the program.
18
Rohini College of Engineering and Technology GE3151

Example:
>>>#This is a print statement
>>>print(“Hello python”)
Hello python
ii) Multi line comments - Multi line comments describes information in detail. Here, more than
one line of comments can be added to the program in between the triple quotes(“ ” ”).
Example:
”””This is print statement
This line print “Hello python”
Written by ABC, April 2017”””
DEBUGGING
Possible errors with Variables:
1. Variable names can contain both letters and numbers. But they cannot begin with
numbers.
2. Both upper case and lower-case letters can be used.
3. Variable names are case sensitive. For example, midname, midName, MidName are
different variables.
4. Variable name cannot be any one of the keywords.
5. Variable names cannot have space in between.
i) Syntax Error:
The text of the program does not comply with the rules of the language is known as a
syntax error. For syntax errors, the error messages don’t help much. The most common messages
are SyntaxError: invalid syntax and SyntaxError: invalid token, neither of which is very
informative. The syntax error you are most likely to make is:
1. An illegal variable name, like class and yield, which are keywords.
2. Variable names such as odd~job and US$, which contain illegal characters.
3. If you put a space in a variable name, Python thinks it is two operands without an
operator:
>>> bad name = 5
SyntaxError: invalid syntax
19
Rohini College of Engineering and Technology GE3151

ii) Runtime Error:


The error which occurs when the program is running is known as runtime error. The
runtime error you are most likely to make is
1. “use before def;” that is, trying to use a variable before you have assigned a value.
2. Runtime error can also happen if you spell a variable name wrong:
>>> principal = 327.68
>>> interest = principle * rate
NameError: name 'principle' is not defined
3. Variables names are case sensitive, so LaTeX is not the same as latex.
Possible errors with Statements:
Semantic error:
A semantic error occurs when a statement is syntactically valid, but does not do what the
programmer wants. The semantic error you are most likely to make is,
To evaluate 1 / 2π, you might be tempted to write
>>> 1.0 / 2.0 * pi
But the division happens first, so you would get π/2, which is not the same thing! So, in this case
you don’t get an error message; you just get the wrong answer. To get right answer, use
>>> 1.0 / ( 2.0 * pi )

ILLUSTRATIVE PROGRAMS
Exchange the values of two variables Swap
- Without using temp function:
def swap(a,b):
a,b=b,a
print(“After Swap:”)
print(“First number:”,a)
print(“Second number:”,b)
a=input(“Enter the first number:”)
b=input(“Enter the second number:”)

20
Rohini College of Engineering and Technology GE3151

print(“Before Swap: ”)
print(“First number:”,a)
print(“Second number:”,b)
swap(a,b)
Output:
Enter the first number: 20
Enter the second number: 10
Before Swap:
First number: 20
Second number: 10
After Swap:
First number: 10
Second number: 20
Swap - Using temp function:
n1=input (“Enter the value of a:”)
n2=input (“Enter the value of b:”)
print (“Before Swap:”)
print (“Value of a:”,n1)
print (“Value of b:”,n2)
temp =n1
n1=n2
n2=temp
print(“After Swap:”)
print(“Value of a:”,n1)
print(“Value of b:”,n2)
Output:
Before Swap:
Value of a: 10
Value of b: 15
After Swap:
21
Rohini College of Engineering and Technology GE3151

Value of a: 15
Value of b: 10
Circulate the values of n variables
def rotate(L,n):
newlist=L[ n: ]+L[ :n ]
return newlist
list = [1,2,3,4,5]
print(“The original list is:”,list)
mylist=rotate(list,1)
print(“List rotated clockwise by 1:”,mylist)
mylist=rotate(list,2)
print(“List rotated clockwise by 2:”,mylist)
mylist=rotate(list,3)
print(“List rotated clockwise by 3:”,mylist)
mylist=rotate(list,4)
print(“List rotated clockwise by 4:”,mylist)
Output:
The original list is: [1, 2, 3, 4, 5]
List rotated clockwise by 1: [2, 3, 4, 5, 1]
List rotated clockwise by 2: [3, 4, 5, 1, 2]
List rotated clockwise by 3: [4, 5, 1, 2, 3]
List rotated clockwise by 4: [5, 1, 2, 3, 4]
Distance between two points
import math
def distance(x1,y1,x2,y2):
dx=x2 - x1
dy=y2 - y1
dsquare=dx**2 - dy**2
result=math . sqrt(dsquare)
return result
22
Rohini College of Engineering and Technology GE3151

x1=int(input(“Enter the value of x1:”))


y1=int(input(“Enter the value of y1:”))
x2=int(input(“Enter the value of x2:”))
y2=int(input(“Enter the value of y2:”))
print(“The distance between two points:” ,distance(x1,y1,x2,y2))
Output:
Enter the value of x1:2
Enter the value of y1:4
Enter the value of x2:3
Enter the value of x1:6
The distance between two points:2.23

23
Rohini College of Engineering and Technology GE3151

PART A (2 Marks with Answers)


1. Write short notes on python.
Python is a general-purpose, interpreted, interactive, object-oriented, and high-level
programming language. Python is created by “Guido Van Rossum” in 1991. It is derived from
several languages, including ABC, Modula-3, C, C++, Algol-68, Smalltalk, and Unix shell and
other scripting languages.
2. Compare interpreter and compiler.
Sl.No Interpreter Compiler

Translate program one statement at a Scans the entire program and translates the
1
time. whole into machine code.

2 No intermediate code is generated. Generates intermediate code.

3 Execution is slower. Execution is faster.

4 It require less memory It require more memory

5 Example: Python Example:C,C++

3. What are the advantages and disadvantages of Python?


Advantages:
Python is easy to learn for even a novice developer
Supports multiple systems and platforms.
Object Oriented Programming-driven
Allows to scale even the most complex applications with ease.
A large number of resources are available for Python.
Disadvantages:
Python is slow.
Have limitations with database access.
Python is not good for multi-processor/multi-core work.
4. Define operator.
An operator is a special symbol that asks the compiler to perform particular
mathematical or logical computations like addition, multiplication, comparison and so on. The
24
Rohini College of Engineering and Technology GE3151

values the operator is applied to are called operands. For eg, in the expression 4 + 5, 4 and 5 are
operands and + is an operator.
5. What is the difference between * operator and ** operator?
* is a multiplication operator which multiplies two operands.
Example: 3*2 returns 6.
** is an exponent operator that performs exponential (power) calculation.
Example: 3**2 returns 9.
6. Compare arguments and parameters.
Arguments Parameters
1.It is the value, which is given to 1.It is the name, which is given in
function call. function definition.
2.Syntax: 2.Syntax:
functionname(arguments) def functionname(parameter):

7. What is the difference between = and == operator?


= is an assignment operator and = = is a relational operator.
= = operator returns true, if the values of two operands are equal.
= operator assigns values from right side operand to left side operand.
8. Define flow of execution in python.
Flow of execution is the order of statements run-in. A function should be defined before
its first use. The execution begins at first statements of program.
9. What are the comment lines in Python?
Comments are the non-executable statements explain what the program does. For large
programs it often difficult to understand what is does. The comment can be added in the program
code with the symbol #.Comment contains information for persons reading the program.
Comment lines are ignored during program execution. Comment lines have no effect on the
program results.
Example:
print ‘Hello, World!’ # print the message Hello, World!; comment

25
Rohini College of Engineering and Technology GE3151

v=7 # creates the variable v and assign the value 7; comment

10. What is the need of operator precedence?


When expressions contain more than one operator, precedence is used to determine the
order of evaluation. The order of evaluation depends on rules of precedence. The rules are,
(i) Parenthesis has the highest precedence.
(ii) Exponentiations have next highest precedence.
(iii) Multiplication and division have higher precedence than addition and subtraction
(iv)Operators with same precedence are evaluated from left to right (except
exponentiation).
11. Write the syntax of function definition.
Functions in python are defined using the block keyword def followed by the function
name and parentheses ( ).Function definition includes:
(i) A header, which begins with a keyword def and ends with a colon.
(ii) A body follows function header, consisting of one or more python statements.
Syntax:
def functionname( parameters ): #Function header
statements #Function body
12. Define keyword. List few Python keywords.
Keywords are certain reserved words that have standard and pre-defined meaning in
python. We cannot use a keyword as variable name, function name or any other identifier.
Example: False, class, finally, nonlocal, yield, lambda, assert.
13.What is a variable?
Variable is a name that is assigned to a value. The value can be changed during execution
of a program. While creating a variable, memory space is reserved in memory. Based on the data
type of a variable, the interpreter allocates memory.
Syntax: variable name=value
Example: price=20
14.What is RETURN statement?
It is used to return the control from calling function to the next statement in the program.

26
Rohini College of Engineering and Technology GE3151

It can also return some values.


Example: return, return 0, return (a+b)

15. Define function.


A function is a group of statements that perform a specific task. If a program is large, it is
difficult to understand the steps involved in it. Hence, it is subdivided into a number of smaller
programs called subprograms or modules. Built-in functions, user defined functions are the two
types of functions.
16.How tuple is assigned in python.
Tuple assignment is an assignment with tuple of variables on left side and tuple of
expression on right side.
>>> X,Y,Z=100, -45, 0
>>>print X,Y,Z
100 -45 0
Here left side is a tuple of variable. The right side is a tuple of expression
17. Write short notes on strings.
String is defined as collection of characters which may consist of letters, numbers, and
special symbols or a combination of these types within quotes. Python treats single quotes is
same as double quotes.eg: ’hello’ or “hello”.
18. What are pre-defined functions? Give example.
Pre-defined functions or Built-in functions are functions already built into Python
interpreter and are readily available for use.
Example: print(), abs(), len()
19. Write in short about relational operators.
Relational operators are used to compare any two values. An expression which uses a
relational operator is called a relational expression. The value of a relational expression is either
true or false.
Example: = =, !=,>, <
3>4
Output: False

27
Rohini College of Engineering and Technology GE3151

20. What are the Bitwise operators available in Python?


& - Bitwise AND
| - Bitwise OR
~ - One’s Complement
>> - Right shift
<< - Left shift
^ - Bitwise XOR
21. What ate the data types available in Python?
Python has five standard data types:
Numbers (int, long, float, complex)
String
List
Tuple
Dictionary
22. What are the features of the Python language?
Easy to learn
Interpreted
Interactive
Object Oriented
High Level language
23. Name four types of scalar objects in python has. (JANUARY 2018)
The commonly used scalar types in Python are:
Int- Any integer.
Float-Floating point number (64 bit precision).
Bool-True, False.
Str-A sequence of characters.
24. What is tuple? How literals of type tuple are written? Give example (JANUARY 2018)
Tuple is an immutable sequence of values, they are separated by commas. The value can
be any type and they are indexed by integer. The literals of type tuple are written as,
(), (9,), (8, 9, 0)
28
Rohini College of Engineering and Technology GE3151

25. What are keywords? Give example. (JANUARY 2019)


The python interpreter uses keywords to recognize the structure of the program and they cannot
be used as variable names.Python2 has 31 keywords. Example: class, print

26. State the reason to divide programs into functions. (JANUARY 2019)
Creating a new function gives an opportunity to name a group of statements, which makes
program easier to read and debug. Functions can make a program to smaller by eliminating the
repeated code.
27. Compare interpreter and compiler. What type of translator is used for Python?
(JANUARY 2020)
Interpreter - Translates program one statement at a time Compiler - Translates program one
statement at a time. Python uses interpreter as a translator
28. Write a python program to print sum of cubes of the values of n variables.
(JANUARY 2020)
n=int(input())
sum=0
for i in range(1,n+1):
sum=sum+i**3
print(sum)

29
Rohini College of Engineering and Technology GE3151

PART-B (Possible Questions)

1. Briefly discuss about the fundamental of python.


2. i) List some features of python.
ii) Explain about the input and output functions used in python.
3. i) Differentiate interactive mode and script mode.
ii) Explain operator precedence with suitable examples.
4. Define function. Explain the scope and lifetime of the variables with suitable examples.
5. Explain the various function arguments in detail.
6. Explain python modules in detail. Explain some of the built-in modules available in python.
7. Explain how variable is named and assigned in python.
8. Write a python program to exchange values of 2 variables without using functions.
9. Explain in detail about various literals used in python.
10. Write a python program to circulate values of n variables.
11. Write short notes on comments.
12. Write a python program to calculate distance between two points.
13. i )What is numeric literals? Give examples (4) (JANUARY 2018)
ii) Appraise the arithmetic operators in python with an example. (12)
14. i) Outline the operator precedence of arithmetic operators in python.(6) (JANUARY 2018)
ii) Write a python program to exchange the values of 2 variables.(4)
iii) Write a python program using function to find the sum of first ‘n’ even numbers and print
the result . (6)

30
Rohini College of Engineering and Technology GE3151

PART – C (Possible Questions)

1.Explain how to write and execute a program in python illustrate the steps for writing a python
program to check whether the number is palindrome or not.
2. Formulate with an example program to pass the list arguments to a function.
3. Do the Case study and perform the following operation in tuples i) Maxima ii) minima iii) sum
of two tuples iv) duplicate a tuple v) slicing operator vi) obtaining a list from a tuple vii)
Compare two tuples viii) printing two tuples of different data types.
4. Formulate with an example program to find out all the values in the list that is greater than the
specified number.
5. Write a program to find out the square root of two numbers.

31
Rohini College of Engineering and Technology GE3151

Additional Programs
1. Python program to calculate the average of numbers in a given list.
n=int(input("Enter the number of elements to be inserted: "))
a=[]
for i in range(0,n):
elem=int(input("Enter the element: "))
a.append(elem)
avg=sum(a)/n
print("Average of elements in the list",round(avg,2))
Output:
Enter the number of elements to be inserted: 3
Enter the element: 23
Enter the element: 45
Enter the element: 56
Average of elements in the list 41.33
2. Python program to exchange the values of two numbers without using a temporary
variable.
def swap(a,b):
a,b=b,a
print(“After Swap:”)
print(“First number:”,a)
print(“Second number:”,b)
a=input(“Enter the first number:”)
b=input(“Enter the second number:”)
print(“Before Swap: ”)
print(“First number:”,a)
print(“Second number:”,b)
swap(a,b)
Output:
Enter the first number: 20
32
Rohini College of Engineering and Technology GE3151

Enter the second number: 10


Before Swap:
First number: 20
Second number: 10
After Swap:
First number: 10
Second number: 20
3. Python program to reverse a given number.
n=int(input("Enter number: "))
rev=0
while(n>0):
dig=n%10
rev=rev*10+dig
n=n//10
print("Reverse of the number:",rev)
Output:
Enter number: 124
Reverse of the number: 421
4. Python program to check whether a number is positive or negative.
a=int(input("Enter number: "))
if(a>0):
print("Number is positive")
else:
print("Number is negative")
Output:
Enter number: 45
Number is positive
5. Python program to take in the marks of 5 subjects and display the grade.
sub1=int(input("Enter the marks of first subject: "))
sub2=int(input("Enter the marks of second subject: "))
33
Rohini College of Engineering and Technology GE3151

sub3=int(input("Enter the marks of third subject: "))


sub4=int(input("Enter the marks of fourth subject: "))
sub5=int(input("Enter the marks of fifth subject: "))
avg=(sub1+sub2+sub3+sub4+sub4)/5
if(avg>=90):
print("Grade: A")
elif(avg>=80&avg<90):
print("Grade: B")
elif(avg>=70&avg<80):
print("Grade: C")
elif(avg>=60&avg<70):
print("Grade: D")
else:
print("Grade: F")
Output:
Enter the marks of first subject: 85
Enter the marks of second subject: 95
Enter the marks of third subject: 99
Enter the marks of fourth subject: 93
Enter the marks of fifth subject: 100
Grade: A
6. Python program to print all numbers in a range divisible by a given number.
lower=int(input("Enter lower range limit:"))
upper=int(input("Enter upper range limit:"))
n=int(input("Enter the number to be divided by:"))
for i in range(lower,upper+1):
if(i%n==0):
print(i)
Output:
Enter lower range limit:1
34
Rohini College of Engineering and Technology GE3151

Enter upper range limit:50


Enter the number to be divided by:5
5
10
15
20
25
30
35
40
45
50
7. Python program to read two numbers and print their quotient and remainder.
a=int(input("Enter the first number: "))
b=int(input("Enter the second number: "))
quotient=a//b
remainder=a%b
print("Quotient is:",quotient)
print("Remainder is:",remainder)
Output:
Enter the first number: 15
Enter the second number: 7
Quotient is: 2
Remainder is: 1
8. Python program to print odd numbers within a given range.
lower=int(input("Enter the lower limit for the range:"))
upper=int(input("Enter the upper limit for the range:"))
for i in range(lower,upper+1):
if(i%2!=0):
print(i)
35
Rohini College of Engineering and Technology GE3151

Output:
Enter the lower limit for the range:1
Enter the upper limit for the range:16
1
3
5
7
9
11
13
15
9. Python program to find the sum of digits in a number.
n=int(input("Enter the number:"))
tot=0
while(n>0):
dig=n%10
tot=tot+dig
n=n//10
print("The total sum of digits is:",tot)
Output:
Enter the number:1892
The total sum of digits is: 20
10. Python program to count the number of digits in a number
n=int(input("Enter the number:"))
count=0
while(n>0):
count=count+1
n=n//10
print("The number of digits in the number are:",count)

36
Rohini College of Engineering and Technology GE3151

Output:
Enter the number:123
The number of digits in the number are: 3
11. Python program to check if a number is a palindrome.
n=int(input("Enter the number:"))
temp=n
rev=0
while(n>0):
dig=n%10
rev=rev*10+dig
n=n//10
if(temp==rev):
print("The number is palindrome")
else:
print("The number is not a palindrome")
Output:
Enter the number:121
The number is palindrome
12. Python program to take the temperature in Celsius and convert it to Fahrenheit.
Celsius=int(input("Enter the Temperature in Celsius:"))
f=(Celsius*1.8)+32
print("Temperature in Fahrenheit is:",f)
Output:
Enter the Temperature in Celsius:32
Temperature in Fahrenheit is: 89.6

37
Problem Solving and Python Programming GE3151

CHAPTER 3

CONTROL FLOW, FUNCTIONS

Conditionals: Boolean values and operators, conditional (if), alternative (if-else), chained
conditional (if-elif-else); Iteration: state, while, for, break, continue, pass; Fruitful functions: return
values, parameters, local and global scope, function composition, recursion; Strings: string slices,
immutability, string functions and methods, string module; Lists as arrays. Illustrative programs:
square root, gcd, exponentiation, sum an array of numbers, linear search, binary search.

101
Problem Solving and Python Programming GE3151

102
Problem Solving and Python Programming GE3151

CONTROL FLOW, FUNCTIONS

3.1 CONDITIONALS
3.1.1 Boolean values and operators
Boolean values:
Boolean data types have two values. They are 0 and 1.
0 represents False
1 represents True
True and False are keywords. Boolean values are used in comparisons and conditional
expressions. The most common way to produce boolean value is relational operators.

Operator Description Example


Equal to >>>4 = = 4
==
True
Not equal to >>> 4 != 3
!=
True
Greater than >>> 4 > 2
>
True
Less than >>> 4< 2
<
False
Greater than or equal to >>>4 >= 5
>=
False
Less than or equal to >>> 4<= 5
<=
True
3.1.2 Operators
Operators are the constructs which can manipulate the value of operands. Consider the
expression 4 + 5 = 9. Here, 4 and 5 are called operands and + is called operator.
Types of operators:
i) Arithmetic operators
ii) Comparison (Relational) operators
iii) Assignment operators

103
Problem Solving and Python Programming GE3151

iv) Logical operators


v) Bitwise operators
vi) Membership operators
vii) Identity operators
i) Arithmetic operators
They are used to perform mathematical operations like addition, subtraction, multiplication etc.

Operator Name of operator

+ Addition

- Subtraction

* Multiplication

/ Division

% Modulus-Divides left hand operand by right hand operand and


returns remainder
** Power-Performs exponential (power) calculation on operators

Floor Division - The division of operands where the result is


the quotient in which the digits after the decimal point are
//
removed

Example Program:
x=5
y=5
print(“x+y=”,x+y)
print(“x-y=”,x-y)
print(“x*y=”,x*y)

104
Problem Solving and Python Programming GE3151

print(“x/y=”,x/y)
print(“x%y=”,x%y)
print(“x//y=”,x//y)
Output:
x+y=30
x-y=20
x*y=125
x/y=5.0
x%y=0
x//y=5
ii) Comparison (Relational) operators
Comparison operators are used to compare values. It either returns True or False according
to the condition.

Operator Name of operator

== Equality
!= Not equal to
> Greater than
< Less than.
>= Greater than or equal to
<= Less than or equal to

Example Program:
x=10
y=20
print(“x>y=”,x>y)
print(“x<y=”,x<y)
print(“x==y=”,x==y)
print(“x!=y=”,x!=y)
105
Problem Solving and Python Programming GE3151

print(“x>=y=”,x>=y)
print(“x<=y=”,x<=y)
Output:
x>y=False
x<y=True
x==y=False
x!=y=True
x>=y=False
x<=y=true
iii) Assignment operators
Assignment operators are used in Python to assign values to variables.

Operator Description

= Assigns values from right side operands to left side


operand
+= It adds right operand to the left operand and assign the
result to left operand
-= It subtracts right operand from the left operand and assign
the result to left operand
*= It multiplies right operand with the left operand and assign
the result to left operand
/= It divides left operand with the right operand and assign the
result to left operand
Example Program:
x=6
x+=5
print(“x+=”,x)
Output:
x+=11

106
Problem Solving and Python Programming GE3151

iv) Logical operators


An expression containing logical operator returns either 0 or 1 depending upon whether
expression results true or false. Logical operators are and, or, not operators.

Operator Description Example


and True if both the operands are true x and y
or True if either of the operands is true x or y
not True if operand is false not x

Example Program:
x=True
y=False
print(“x and y=”,x and y)
print(“x or y=”,x or y)
print(“not x=”,not x)
Output:
x and y=False
x or y=True
not x=False
v) Bitwise operators

Bitwise operators are used to perform bit-level operations which makes processing faster.

Operator Name of operator


& Bitwise AND
| Bitwise OR
~ Bitwise NOT
^ Bitwise XOR
>> Bitwise right shift

107
Problem Solving and Python Programming GE3151

<< Bitwise left shift

Example Program:
x=2
y=3
print(“x&y=”,x&y)
Output:
x&y=2
vi) Membership operators
It evaluates to find a value or a variable is in the specified sequence of string, list, tuple,
and dictionary or not.
To check particular element is available in the list or not.
The membership operators are in and not in.

Operator Description
in True if value/variable is found in the sequence
not in True if value/variable is not found in the sequence

Example:
x=[5,3,6,4,1]
>>> 5 in x
True
>>> 5 not in x
False
vii) Identity operators
They are used to check if two values (or variables) are located on the same part of the
memory.

Operator Description
is True if the operands are identical(refer to the same object)

108
Problem Solving and Python Programming GE3151

is not True if the operands are not identical(do not refer to the same
object)
Example:
x=5
y=5
a = 'Hello'
b = 'Hello'
print(x is not y)
print(a is b)
Output:
False
True
3.1.3 Conditional Statements
i)Conditional if
If conditional is a decision making statement. It is always used with condition. It executes
code only if condition is satisfied.
syntax:
if condition:
statements
Flowchart:

False

condition

True

statements

109
Problem Solving and Python Programming GE3151

Example Program: To provide bonus mark if the category is sports.


a=input(“enter the number1”)
b=input(“enter the number2”)
if(a>b):
print(“Biggest number is:”,a)
Output:
enter the number1
85
enter the number2
80
Biggest number is:80
ii) Alternative (if-else)
In the alternative the condition must be true or false. If the condition is true statements
inside the if get executed otherwise else part gets executed. The alternatives are called branches,
because they are branches in the flow of execution.
Syntax:
if (condition):
True statements
else:
False statements
Flowchart:

True False
if
condition

110
Problem Solving and Python Programming GE3151

True statements False statements

111
Problem Solving and Python Programming GE3151

Example Program 1: Odd or even number


n=int(input("Enter a number:"))
if(n%2==0):
print("Even number")
else:
print("Odd number")
Output:
Enter a number :4
Even number
Example Program 2: Positive or Negative number
n=int(input("Enter a number:"))
if(n>0):
print("Positive number")
else:
print("Negative number")
Output:
Enter a number 4
Positive number
iii) Chained conditionals (if-elif-else)
The elif is short for else if. This is used to check more than one condition. If the condition1
is False, it checks the condition2 of the elif block. If all the conditions are False, then the else part
is executed.
Syntax:
if(condition1):
statement1
elif(condition2):
statement2
elif(condition3):
statement3
else:

112
Problem Solving and Python Programming GE3151

default statements

Flowchart:

False
Condition

True
True
False
Statement 1 Condition

True False
Statement 2 Condition

True

Statement 3 Default statement

Example Program: Roots of quadratic equation


a=int(input("enter a value:"))
b=int(input("enter b value:"))
c=int(input("enter c value:"))

113
Problem Solving and Python Programming GE3151

d=(b*b-4*a*c)
if(d==0):
print("same and real roots")
elif(d>0):
print("different real roots")
else:
print("imaginary roots")
Output:
enter a value:1
enter b value:0
enter c value:0
same and real roots
3.2 ITERATION/CONTROL STATEMENTS/LOOPING STATEMENTS
Iteration means repetition of loop until base condition is false. Repeated execution of set of
statements is called as iteration.
state
while
for
break
continue
pass
3.2.1 State
It is possible to have more than one assignment for the same variable. Reassignment
replaces existing value with new value.
Example Program1:
>>>x=10
>>>y=17
>>>print x
10
>>>x=18

114
Problem Solving and Python Programming GE3151

>>>print x
18
Example Program2:
>>>x=10
>>>y=176
>>>x=8
>>>print x
8
3.2.2 While loop
While loop statement in Python is used to repeatedly executes set of statement as long as a
given condition is true. In while loop, test expression is checked first. The body of the loop is
entered only if the test expression is True.
Syntax:
while(condition):
body of while statements
Flowchart:

False
Condition

True
Body of while
statements

exit from loop

115
Problem Solving and Python Programming GE3151

Example Program: Factorial of a numbers

n=input("enter the number”)


i=1
fact=1
while(i<=n):
fact=fact*i
i=i+1
print(“Factorial is”,fact)
Output:
enter the number
5
Factorial is 120
3.2.3 For loop
for in range:
We can generate a sequence of numbers using range () function. In range function have to
define the start, stop and step size as range(start, stop, step size).step size defaults to 1 if not
provided.
Syntax:
for loopvariable in range(start,step,stepsize)
Example Program: Factorial of a numbers

n=input("enter the number”)


fact=1
for i in range(1,n):
fact=fact*i
print(“Factorial is”,fact)
Output:
enter the number
5

116
Problem Solving and Python Programming GE3151

Factorial is 125
for in sequence:
The for loop in Python is used to iterate over a sequence (list, tuple, string).. Loop
continues until we reach the last element in the sequence.
Syntax:
for loopvariable in sequence:
Body of for statements

Flowchart:

False
Condition

Body of for
statements

Exit from loop


Sequence can be a list, strings or tuples:

Sl.No Sequences Example Output

R
for i in "Ramu": A
1. For loop in string
print(i) M
U
for i in [2,3,5,6,9]: 2
2. For loop in list
print(i) 3

117
Problem Solving and Python Programming GE3151

5
6
9
2
for i in (2,3,1):
3. For loop in tuple 3
print(i)
1

3.2.4 Break
Break statements can alter the flow of a loop. It terminates the current loop and executes
the remaining statement outside the loop.
Syntax:
i) while loop
while(condition):
if(condition):
break
ii) for loop
for loop variable in sequence:
if(condition):
break
Flowchart:

condition
a
True

Break?

Body of loop

118
Problem Solving and Python Programming GE3151

Example Program:

for i in "welcome":
if(i=="c"):
break
print(i)

Output:
w
e
l
3.2.5 Continue

It terminates the current iteration and transfer the control to the next iteration in the loop.
Syntax:
i) while loop
while(condition):
if(condition):
continue
ii) for loop
for loopvariable in sequence:
if(condition):
continue
Flowchart:

condition

Continue

Body of loop
119
Problem Solving and Python Programming GE3151

Example Program:

for i in "welcome":
if(i=="c"):
continue
print(i)
Output:
w
e
l
o
m
e
3.2.6 Pass
It is a null statement, nothing happens when it is executed.

Syntax:

pass

Example Program:

for i in “welcome”:

if (i == “c”):

pass

print(i)

Output:

w
e
l
c
o
120
Problem Solving and Python Programming GE3151

m
e

3.2.7 Difference between break and continue

Sl.No break continue

1 It terminates the current loop and It terminates the current iteration and
executes the remaining statement outside transfer the control to the next iteration in
the loop. the loop.
2 syntax: syntax:
break continue
3 for i in "welcome": for i in "welcome":
if(i=="c"): if(i=="c"):
break continue
print(i) print(i)
4 w w
e e
l l
o
m
e

3.3 FRUITFUL FUNCTION


A function that returns a value is called fruitful function.
Example program:
def add():
a=10
b=20
c=a+b
return c
c=add()
120
Problem Solving and Python Programming GE3151

Void function:
A function that does not return any value is called void function.
Example 1:
print(“Hello”)
Example 2:
def add():
a=10
b=20
c=a+b
print(c)
add()
3.3.1 Return values
Return statement may or may not send back any value to main program. The return
statement is also used to exit a function and go back to place where it was called, return keywords
are used to return the values from the function.
Syntax:
return(expression)

Fruitful function Return the value


Input
Example:

return a – return 1 variable


return a,b– return 2 variables
return a,b,c– return 3 variables
return a+b– return expression
return 8– return value
3.3.2 Parameters / Arguments
Parameters are the variables which used in the function definition. Parameters are inputs
to functions. Parameter receives the input from the function call. It is possible to define more than
one parameter in the function definition.
121
Problem Solving and Python Programming GE3151

Types of parameters/arguments:
i) Required/positional parameters
ii) Keyword parameters
iii) Default parameters
iv) Variable length parameters

i) Required/ positional parameter


The number of parameter in the function definition should match exactly with number of
arguments in the function call.
Example Output

def student( name, roll ):


print(name,roll) Ajitha 98
student(“Ajitha”,98)

ii) Keyword parameter


When we call a function with some values, these values get assigned to the parameter
according to their position. When we call functions in keyword parameter, the order of the
arguments can be changed.
Example Output
def student(name,roll,mark):
print(name,roll,mark) Mala 90 100
student("Mala",90,100)

iii) Default parameter


Python allows function parameter to have default values; if the function is called without
the argument, the argument gets its default value in function definition
Example Output
def student( name, age=20):
print (name, age) Latha 20
student( “Latha”): Aarika 20

122
Problem Solving and Python Programming GE3151

student( “Aarika”):

iv) Variable length parameter


Sometimes, we do not know in advance the number of arguments that will be passed into
a function. Python allows us to handle this kind of situation through function calls with number of
arguments. In the function definition we use an asterisk (*) before the parameter name to denote
this is variable length of parameter.
Example Output
def student( name,*mark):
print(name, mark) Vikash (102 ,90)
student (“Vikash”,102,90)

3.3.3 Global and Local scope


Global scope:
The scope of a variable refers to the places that you can see or access a variable. A variable
with global scope can be used anywhere in the program. It can be created by defining a variable
outside the function.
Example Output

a=50
def add():
b=20
c=a+b Global variable
print(c) 70
def sub():
b=30
Local variable
c=a-b
print(c) 20

123
Problem Solving and Python Programming GE3151

print(a) 50

3.3.4 Function composition


Function composition is the ability to call one function from within another function. It is a
way of combining functions such that the result of each function is passed as the argument of the
next function. -9/-
Example Program: Find sum and average using function composition
def sum(a,b):
sum=a+b
return sum
def avg(sum):
avg=sum/2
return avg
a=eval(input("enter a:"))
b=eval(input("enter b:"))
sum=sum(a,b)
avg=avg(sum)
print("the avg is",avg)
Output:
enter a:4
enter b:8
the avg is 6.0
3.3.5 Recursion
Recursion is a programming technique that has a recursive function that calls itself again
and again until the condition is reached.
Example Program: Factorial of a given number using recursion
def fact(n):
if(n==1):
return 1

124
Problem Solving and Python Programming GE3151

else:
return n*fact(n-1)
n=int(input("enter no. to find fact:"))
fact=fact(n)
print("Fact is",fact)
Output:
enter no. to find fact:5
Fact is 120
3.4 STRINGS
String is defined as sequence of characters represented in quotation marks (either single
quotes ( ‘ ) or double quotes ( “ ). An individual character in a string is accessed using a index.
The index should always be an integer (positive or negative). A index starts from 0 to n-1. Strings
are immutable i.e. the contents of the string cannot be changed after it is created.
String operators/operations:
i) Indexing
ii) Slicing
iii) Concatenation
iv) Repetition
v) Membership
vi)Comparision

i) Indexing

Positive indexing helps in accessing the string from the beginning. Negative subscript helps
in accessing the string from the end.

>>>a=”HELLO HAI”
>>>print(a[0])
>>>H
>>>print(a[-1])
>>>I
ii) Slicing

125
Problem Solving and Python Programming GE3151

The slice[start : stop] operator extracts sub string from the strings. A segment of a string
is called a slice.
print a[0:4] – HELL
print a[ :3] – HEL
print a[0: ]- HELLO
iii) Concatenation
The + operator joins the text on both sides of the operator.
a=”save”
b=”water”
>>>print(a+b)
savewater
iv) Repetition
The * operator repeats the string on the left hand side times the value on right hand side.
a=”python”
>>>print(3*a)
pythonpythonpython
v) Membership
Using membership operators to check a particular character is in string or not. Returns
true if present
>>> s="good morning"
>>>"m" in s
True
>>> "a" not in s
True
vi)Comparison
The strings can be compared using relational operators.
>>>msg1=”Good”
>>>msg2=”Good”
>>>msg1==msg2
True

126
Problem Solving and Python Programming GE3151

3.4.1 String slices


A part of a string is called string slices. The process of extracting a sub string from a string
is called slicing. The Slice[n : m] operator extracts substring from the strings. A segment of a string
is called a slice.
a=”HELLO”
print a[0:4] – HELL
print a[ :3] – HEL
print a[0: ]- HELLO

3.4.2 Immutability
Python strings are “immutable” as they cannot be changed after they are created.
Therefore [ ] operator cannot be used on the left side of an assignment.

Operations Example Output

element assignment a="PYTHON" TypeError: 'str' object does not


a[0]='x' support element assignment
New strings can be created a=”Python” PythonProgram
from the old c=a+”Program”
print c

3.4.3 String built in functions and methods (or) String Functions


A method is a function that “belongs to” an object.
Syntax :
To access the method
stringname.method()
Example:
a=”happy birthday”
here, a is the string name.

127
Problem Solving and Python Programming GE3151

Sl.No Syntax Example Description


1 a. capitalize() >>> a. capitalize() capitalize only the first letter in
' Happy birthday’ a string
2 a. upper() >>> a. upper() change string to upper case
'HAPPY BIRTHDAY’
3 a. lower() >>> a. lower() change string to lower case
' happy birthday’
4 a.title() >>> a.title() change string to title case i.e.
' Happy Birthday ' first characters of all the words
are capitalized.

5 a.swapcase() >>>a.swapcase() change lowercase characters to


'HAPPY BIRTHDAY' uppercase and vice versa
6 a.split() >>> a.split() returns a list of words
['happy', 'birthday'] separated by space
7 a.count(substring) >>> a.count('happy') returns the number of
1 occurences of substring
8 a.replace(old,new) >>>a.replace('happy', replace all old substrings
'wishyou happy') with new substrings
'wishyou happy
birthday'

9 a.isupper() >>> a.isupper() checks whether all the case


False based characters (letters) of
the string are uppercase.
10 a.islower() >>> a.islower() checks whether all the
True casebased
characters (letters) of
the string are lowercase.

128
Problem Solving and Python Programming GE3151

11 a.isalpha() >>> a.isalpha() checks whether the string


False consists of alphabetic
characters only.

12 a.isalnum() >>> a.isalnum() checks whether the string


False consists of alphanumeric
characters.
13 a.isdigit() >>> a.isdigit() checks whether the string
False consists of digits only.

14 a.isspace() >>> a.isspace() checks whether the string


False consists of whitespace only.
15 a.istitle() >>> a.istitle() checks whether string is title
False cased.
16 a.startswith(substrin >>> a.startswith("h") checks whether string starts
g) True with substring
17 a.endswith(substrin >>>a.endswith("y") checks whether the string ends
g) True with the substring
18 len(a) >>>len(a) Return the length of the string
>>>14
19 min(a) >>>min(a) Return the minimum
>>>’ ‘ character in the string
20 max(a) max(a) Return the maximum
>>>’y’ character in the string

3.4.4 String modules


A module is a file containing Python definitions, functions, statements.
Standard library of Python is extended as modules.
To use these modules in a program, programmer needs to import the module.
Once we import a module, we can reference or use to any of its functions or variables
129
Problem Solving and Python Programming GE3151

in our code.
There is large number of standard modules also available in python.
Standard modules can be imported the same way as we import our user-defined
modules.
Syntax:
import module_name
Example Program:
import string
print(string.punctuation)
print(string.digits)
print(string.printable)
print(string.capwords("happy birthday"))
print(string.hexdigits)
print(string.octdigits)

Output:

!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
0123456789
0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJ
KLMNOPQRSTUVWXYZ!"#$%&'()*+,-
/:;<=>?@[\]^_`{|}~
Happy Birthday
0123456789abcdefABCDEF
01234567

3.4.5 List as array


Array:
Array is a collection of similar elements. Elements in the array can be accessed by index.
Index starts with 0. Array can be handled in Python by module named array. To create array have
to import array module in the program.
Syntax:
130
Problem Solving and Python Programming GE3151

import array
Syntax to create array:
arrayname = modulename.functionname(‘datatype’,[elements])
Example:
a=array.array(‘i’,[1,2,3,4])
Here,
a- array name
array- module name
i- integer datatype

Convert list into array:


fromlist() function is used to append list to array. Here the list is act like a array.
Syntax:
arrayname.fromlist(listname)
Example Program: Program to convert list into array
import array
sum=0
l=[6,7,8,9,5]
a=array.array('i',[])
a.fromlist(l)
for i in a:
sum=sum+i
print(sum)
Output
35
Methods in array:
a=[2,3,4,5]
Sl.No Syntax Example Description
1 array(data type,value list) array(‘i’,[2,3,4,5]) This function is used to create an
array with data type and value list

131
Problem Solving and Python Programming GE3151

specified in its arguments.


2 append() >>>a.append(6) This method is used to add end of
[2,3,4,5,6] the array.
3 insert(index,element) >>>a.insert(2,10) This method is used to add the
[2,3,10,5,6] value at the position specified in
its argument.
4 pop(index) >>>a.pop(1) This function removes the
[2,10,5,6] element at the position
mentioned in its argument, and
returns it.
5 index(element) >>>a.index(2) This function returns the index of
0 value
6 reverse() >>>a.reverse() This function reverses the
[6,5,10,2] array.
7 count() a.count() This is used to count number of
4 elements in an array

3.5 ILLUSTRATIVE PROGRAMS


3.5.1 Square root using Newton’s method
def newtonsqrt(n):
root=n/2
for i in range(10):
root=(root+n/root)/2
print(root)
n=eval(input("enter number to find Sqrt: "))
newtonsqrt(n)
Output:
enter number to find Sqrt: 9
3.0

132
Problem Solving and Python Programming GE3151

3.5.2 GCD of two numbers


def gcd(a,b):
if(b==0):
return a
else:
return gcd(b,a%b)
a=input(“Enter number1:”)
b=input(“Enter number2:”)
g=gcd(a,b)
print(“gcd is”,g)
Output:
Enter a number1:8
Enter a number2:24
gcd is 8
3.5.3 Exponent of a number
def power(base,exp):
if(exp==1):
return(base)
else:
return(base*power(base,exp-1))
base=int(input("Enter base: "))
exp=int(input("Enter exponential value:"))
result=power(base,exp)
print("The exponent is:",result)
Output:
Enter base: 2
Enter exponential value:3
The exponent is: 8
3.5.4 Sum of array elements
a=[2,3,4,5,6,7,8]

133
Problem Solving and Python Programming GE3151

sum=0
for i in a:
sum=sum+i
print("The total is",sum)

Output:
The total is 35
3.5.5 Linear search
mylist=[11,23,38,40,52,63,78,98,29,45]
print(mylist)
x = int(input("Enter number to search: "))
found=False
for i in range(len(mylist)):
if(mylist[i] == x):
found=True
print ("Element found at position:",i+1)
break
if(found==False):
print "Element not found"
Output:

[11, 23, 38, 40, 52, 63, 78, 98, 29, 45]
Enter number to search: 78
(‘Element found at position:’ 7)
[11, 23, 38, 40, 52, 63, 78, 98, 29, 45]
Enter number to search: 2
Element not found
3.5.6 .Binary search
def bsearch(list,x):
first = 0
last= len(list)-1
134
Problem Solving and Python Programming GE3151

while (first<=last):
midpoint= (first+ last)//2
if x==list[midpoint]:
return midpoint
elif(x<list[midpoint]):
last=midpoint-1
else:
first= midpoint+1
return -1
list=[10,20,30,40,50]
print("Original list is:",list)
x=input("Enter the element to be searched:")
pos=bsearch(list,x)
if(pos!=-1):
print “Element found at the position:”,pos
else:
print “Element not found”
Output:
Original list is:[10,20,30,40,50]
Enter the element to be searched:30
Element found on position:2
Original list is:[10,20,30,40,50]
Enter the element to be searched:60
Element not found

135
Problem Solving and Python Programming GE3151

PART- A (2 Marks with Answers)


1. Define Boolean expression with example.
A boolean expression is an expression that is either true or false. The values true and
false are called Boolean values.
Example:
>>> 5 == 6
False
True and False are special values that belongs to the type bool; they are not strings.
2. What are the different types of operators?

Arithmetic Operator (+, -, *, /, %, **, // )


Relational operator ( == , !=, < >, < , > , <=, >=)
Assignment Operator ( =, += , *= , - =, /=, %= ,**= )
Logical Operator (AND, OR, NOT)
Membership Operator (in, not in)
Bitwise Operator (& (and), | (or) , ^ (binary Xor), ~(binary 1’s complement) ,
<< (binary left shift), >> (binary right shift))
Identity Operator(is, is not)
3. Explain modulus operator with example.
The modulus operator works on integers and yields the remainder when the first operand
is divided by the second. In Python, the modulus operator is a percent sign (%). The syntax is same
as for other operators:
Example:
>>> remainder = 7 % 3
>>> print remainder
1
So 7 divided by 3 is 2 with 1 left over.
4. Explain relational operators.
The == operator is one of the relational operators; the others are:
X! = y # x is not equal to y
x > y # x is greater than y
136
Problem Solving and Python Programming GE3151

x < y # x is less than y


x >= y # x is greater than or equal to y
x <= y # x is less than or equal to y
5. Explain Logical operators
There are three logical operators: and, or, and not. For example, x > 0 and x < 10 is true
only if x is greater than 0 and less than 10. n%2 == 0 or n%3 == 0 is true if either of the conditions
is true, that is, if the number is divisible by 2 or 3. Finally, the not operator negates a Boolean
expression, so not(x > y) is true if x > y is false, that is, if x is less than or equal to y. Non-zero
number is said to be true in Boolean expressions.
6. What is conditional execution?

The ability to check the condition and change the behavior of the program accordingly is
called conditional execution.
If statement:
The syntax of if statement is:
Syntax:
if
statement:
Example:
if x > 0:
print 'x is positive'
The boolean expression after ‘if’ is called the condition. If it is true, then the indented statement
gets executed. If not, nothing happens.

7. What is alternative execution?


A second form of if statement is alternative execution, that is, if …else, where there are two
possibilities and the condition determines which one to execute.
Example:
if x%2 == 0:
print 'x is even'
else:

137
Problem Solving and Python Programming GE3151

print 'x is odd'


8. What are chained conditionals?
Sometimes there are more than two possibilities and we need more than two branches.
One way to express a computation like that is a chained conditional.
Example:
if x < y:
print 'x is less than y'
elif x > y:
print 'x is greater than y'
else:
print 'x and y are equal'
9. Explain ‘for loop’ with example.
The general form of a for statement is
Syntax:
for loop variable in sequence:
Body of for statements
Example:
x=4
for i in range(0, x):
print i
10. What is a break statement?
When a break statement is encountered inside a loop, the loop is immediately terminated and the
program control resumes at the next statement following the loop.
Example:
while True:
line = raw_input('>')
if line == 'done':
break
print line
print 'Done!'

138
Problem Solving and Python Programming GE3151

11. What is a continue statement?


The continue statement works somewhat like a break statement. Instead of forcing
termination, it forces the next iteration of the loop to take place, skipping any code in between.
Example:
for num in range(2,10):
if num%2==0;
print “Found an even number”, num
continue
print “Found a number”, num
12. Compare return value and composition.
Return value:
Return gives back or replies to the caller of the function. The return statement causes our
function to exit and hand over back a value to its caller.
Example:
def area(radius):
temp = math.pi * radius**2
return temp
Composition:
Calling one function from another is called composition.
Example:
def circle_area(xc, yc, xp, yp):
radius = distance(xc, yc, xp, yp)
result = area(radius)
return result
13. What is recursion?
The process in which a function calls itself directly or indirectly is called recursion and
the corresponding function is called as recursive function.

Example:
def factorial(n):
if n == 1:
139
Problem Solving and Python Programming GE3151

return 1
else:
return n * factorial(n-1)
14. Explain global and local scope.
The scope of a variable refers to the places that we can see or access a variable. If we define
a variable on the top of the script or module, the variable is called global variable. The variables
that are defined inside a class or function is called local variable.
Example:
def my_local():
a=10
print(“This is local variable”)
Example:
a=10
def my_global():
print(“This is global variable”)
15. Compare string and string slices.
A string is a sequence of character.
Example:
fruit = ‘banana’
String slices:
A segment of a string is called string slice, selecting a slice is similar to selecting a
character.
Example:
>>> s =' Pythonprogram'
>>> print s[0:5]
pytho
>>> print s[6:12]
progra

140
Problem Solving and Python Programming GE3151

16. Define string immutability.


Python strings are immutable. ‘a’ is not a string. It is a variable with string value. We
can’t mutate the string but can change what value of the variable to a new string.

Example:
a = “foo”
b=a
a=a+a
print a
print b

Output:
foofoo
foo
It is observed that ‘b’ hasn’t changed even though ‘a’ has changed.
17. Mention a few string functions.
s.captilize() – Capitalizes first character of string
s.count(sub) – Count number of occurrences of sub in string
s.lower() – converts a string to lower case
s.split() – returns a list of words in string
18. What are string methods?
A method is similar to a function—it takes arguments and returns a value—but the syntax
is different. For example, the method upper takes a string and returns a new string with all
uppercase letters. Instead of the function syntax upper(word), it uses the method syntax
word.upper()
>>> word = 'lion'
>>> new_word = word.upper()
>>> print new_word
LION

141
Problem Solving and Python Programming GE3151

19. Explain about string module.


The string module contains number of useful constants and classes, as well as some
deprecated legacy functions that are also available as methods on strings.
20. What is the purpose of pass statement?
Using a pass statement is an explicit way of telling the interpreter to do nothing.
Example:
def bar():
pass
If the function bar() is called, it does absolutely nothing
21 .What is the use of str.upper() and str.lower() functions in string?
The functions str.upper() and str.lower() will return a string with all the letters of original
string converted to upper or lower case letters.
22 .Explain string comparison with an example.
The comparison operator works on string to check if two strings are equal.
>>>word=‘python program‘
>>>if word==‘pythonprogram‘
print( ‘Both are Equal‘)
Output:
Both are Equal
23. How to split strings and what function is used to perform that operation?
The str.split() method is used to split strings up.
Example:
>>>book=‘Problem Solving and Python Programming‘

>>>print(book.split()) [‗Problem‘, ‗Solving‘, ‗and‘, ‗Python‘, ‗Programing‘]


24. What is len function and explain how it is used on strings with an example.
The len function, when applied to a string, returns the number or character in a string.
Example:
>>>book=‘Problem Solving and Python Programming‘
>>>len(book)
>>> 38
142
Problem Solving and Python Programming GE3151

25. Write a program to accept two number,multiply them and print the result.
(JANUARY 2018)
print(“Enter two numbers:”)
val1=int(input())
val2=int(input())
prod=val1*val2
print(“product is:”,prod,”\n”)
26. Write a python program to accept two numbers, find the greatest and print the result.
(JANUARY 2018)
print(“Enter two numbers:”)
num1=input()
num2=input()
number1=int(num1)
number2=int(num2)
if number1>number2:
Largest=number1
else:
Largest=number2
print(“largest number is:”,largest)
27. Present the flow of execution for a while statement. (JANUARY 2019)
While loop statement in Python is used to repeatedly executes set of statement as long as a
given condition is true. In while loop, test expression is checked first. The body of the loop is
entered only if the test expression is True.
Syntax:
while(condition):
body of while statements
28. Define recursion with example. (JANUARY 2019)
Recursion is a programming technique that has a recursive function that calls itself again
and again until the condition is reached.

143
Problem Solving and Python Programming GE3151

29. Do loop statements have else clause? When will it be executed? (JANUARY 2020)

Yes. Loop’s else part runs if no break occurs and the condition is false

30. Write a program to display a set of strings using range () function. (JANUARY 2020)

st=" hai welcome to cse" x=' '


for s in range(len(st)):
x=x+st[s]
print(x)

144
Problem Solving and Python Programming GE3151

PART-B (Possible Questions)


1. Explain the syntax and flow chart of the following loop statements
a. for loop
b. while loop
2. Explain recursive function. How do recursive function works? Explain with a help of program
3. Create a program to reverse a string without using recursion
4. Illustrate the concept of local and global variables
5. Discuss the methods to manipulate the arrays in python
6. Create a python program to find the given year is leap or not
7. Investigate on mutability and immutability in python
8. Illustrate the flow chart and syntax of if-elif-else statements
9. Explain the types of function arguments in python
10. Explain break and continue statement with the help of for loop in an example.
11. Write a program for binary search using Arrays
12. Define methods in a string with an example program using at least five methods.
13. What is the use of pass statement, illustrate with an example.
14. How to access characters of a string?
15.i.Appraise with an example nested if and elif header in python (JANUARY 2018)
ii.Explain with an example while loop,break statement and continue statement in python
16.i.Write a python program to find the factorial of a given number without recursion and with
Recursion. (JANUARY 2018)
ii.Write a python program to generate first ‘N’ fibonacci numbers.
17. a) List the three types of conditional statements and explain them (16)
b) i)Python strings are immutable, Justify with an example (8)
ii)Write a python code to perform binary search. Trace it with an example of your choice.
(8) (JANUARY 2019)
18. i)If you are given three sticks, you may or may not be able to arrange them in a triangle. For
example, if one of the sticks is 12 inches long and the other two are one inch long, you will not be
able to get the short sticks to meet in the middle. For any three length, there is a simple test to

145
Problem Solving and Python Programming GE3151

see if it is possible to form a triangle: If any of three lengths is greater than the sum of the other
two, then you cannot form a triangle. Otherwise ,you can.
i) Write a function named is – triangle that takes three integers as arguments, and that prints
either “yes” or “no”, depending on whether you can or cannot form a triangle from sticks with the
given lengths. (4)
ii) Write a function that prompts the user to input three stick lengths, converts them to integers,
and uses is – triangle to check whether sticks with the given lengths can form a triangle
(4).
iii) Write a python program to generate all permutations of a given string using built-in
functions. (8) (JANUARY 2020)
19.i)Compare list and array with example.Can list be considered as an array?justify (6)
ii)Write a python function are Anagram1() to check whether two strings are anagram of each
other or not using built-in functionand are Anagram2() to check the anagram without using built-
in function. (10) (JANUARY 2020)

146
Problem Solving and Python Programming GE3151

PART C (Possible Questions)

1. Write a python program to design simple calculator performing arithmetic functions like
addition, subtraction, multiplication and division with the input given by user.
2. Create a program for linear search using Arrays
3. Illustrate a program to find GCD of m and n.
4. How to find the square root of a number using newton’s method
5. Write a python program to sum an array of numbers
6. Write a python program for student mark system.
7. Write a python program greatest of three numbers.

147
Problem Solving and Python Programming GE3151

CHAPTER 4

LISTS, TUPLES, DICTIONARIES

Lists: list operations, list slices, list methods, list loop, mutability, aliasing, cloning lists, list
parameters; Tuples: tuple assignment, tuple as return value; Dictionaries: operations and methods;
advanced list processing - list comprehension; Illustrative programs: selection sort, insertion sort,
mergesort, histogram.

151
Problem Solving and Python Programming GE3151

152
Problem Solving and Python Programming GE3151

LISTS, TUPLES, DICTIONARIES

4.1 LIST
List contain elements of various data types, the list is enclosed by square brackets where
elements are separated by commas. The values in a list are called elements or items. A list within
another list is called nested list.
 List values can be accessed using slice operator ([] or [:])
 list[0] represents beginning of list
 list[-1] represents ending of list
Syntax:
listname=[value1,value2,…value n]
Example :
>>>mylist = [10,10.5, ‘programming’]
Example program for creating lists:
list1 = [‘Rama’, ‘Delhi’, 2018]
list2 = [10, 20, 30, 40, 50]
list3 = []
list4 = [‘Prema’, 2018, 99.8, [‘Mumbai’, ‘India’]]
print list1
print list2, list3
print list4
Output:
[‘Rama’, ‘Delhi’, 2018]
[10, 20, 30, 40, 50] [ ]
[‘Prema’, 2018, 99.8, [‘Mumbai’, ‘India’]]
Creating list:
i) The simplest way to create a list is enclose the elements in square brackets([])
nlist =[10,20,30,40]
slist =[“Hai”, “Python”]
ii) A list that contains no element is called an empty list. It can be created with empty brackets [].
elist = []
153
Problem Solving and Python Programming GE3151

iii) A list within another list is called a nested list.


nlist =[“phyton”,2.5,[50,100,10,55]]
Accessing list elements:
The indices of list’s elements are numbered from 0 from the left end and numbered from
-1 from the right end. To access the element(s) of a list, subscript operator [ ] (also known as slicing
operator) is used. Index within [ ] indicates the position of the particular element in the list and it
must be an integer expression.
Indexing:
Just like strings, we can access elements on a list with the index. The various types are
i) Negative indexing
The index of -1 refers to the last item, -2 to the second to the last item and so on.
Example Program:
>>>birds[“parrot”,”Dove”,”duck”,”cuckoo”]
>>>birds[-1]
cuckoo
>>> birds[-4]
parrot
ii) Nested indexing:
A list within another list is called as nested list.
Example Program:
>>>nlist = [“Python”,8.5,[5,1,3,4,5.5]]
>>>nlist[0]
Python
>>>nlist[0][3]
h

154
Problem Solving and Python Programming GE3151

4.1.1 List operations(List operators)


List provides a set of operations. They are
i) Concatenation
ii) Repetition
iii) Indexing
iv) Membership
i) Concatenation
The list can be concatenated by using ‘+’ operator.
Example:
>>>a = [1,2,3]
>>>b =[4,5,6]
>>>c =a+b
>>>c
[1,2,3,4,5,6]
ii) Repetition
The list can be repeated by using * operator.
Example:
>>>a =[1,2,3]
>>>a*2
[1,2,3, 1,2,3]
>>>[1]*5
[1,1,1,1,1]
iii) Indexing
The list elements can be accessed by using index operator ([]).
Example:
>>>a =[1,2,3]
>>>a[0]
1
>>>a[1]
2
>>>a[2]
155
Problem Solving and Python Programming GE3151

3
>>>a[-1]
3

156
Problem Solving and Python Programming GE3151

iv) Membership
There are 2 membership operators in python programming.
i) in - Returns true if value is in list, returns false if value is not in list.
ii) not in - Returns true if value is not in list, returns false if value is in list.
Example:
>>>a= [1,2,3]
>>>1 in a
True
>>>4 in a
False
>>>3 not in a
False
4.1.2 List slices
A segment of list is called as list slice. The list elements can be accessed using the slice
operator ([]). Slice operator [n:m] returns a part of list from nth element to mth element , including
first and excluding last.
If the first index is omitted, the slice starts at the beginning of the string. If the second index
is omitted, the slice goes to the end of the string. If the first index is greater than or equal to the
second, the slice is an empty string. If both indices are omitted, the slice is a given string itself.
Syntax:
listname [start: finish -1]
Example:
>>>mylist=[‘Python’,10,10.5,’program’]
>>>mylist[0]
‘Python’
>>>mylist[1]
10
>>>mylist[2]
10.5

157
Problem Solving and Python Programming GE3151

>>>mylist[3]
‘program’
>>>mylist[0:3]
[‘Python’,10,10.5]
>>>mylist[1:3]
[10, 10.5]
>>>mylist[:3]
[‘Python’,10,10.5]
>>>mylist[:]
[‘Python’,10,10.5,’program’]
>>>mylist[1:]
[10,10.5,’program’]
mylist
python 10 10.5 program
0 1 2 3
mylist[0] -> element in 0th position.
mylist[-1] -> element in ending of list
mylist[0:3] -> Starting from 0th position to 2nd position
mylist[1:] -> ending position is not given , so 1st position to ending of list
mylist[:] -> beginning to ending of list.
4.1.3 List methods
Python provides a set of list methods. They are
i) append()
ii) extend()
iii) sort()
iv) reverse()
v) pop()
vi) clear()
vii) index()
viii) count()

158
Problem Solving and Python Programming GE3151

ix) insert()
x) remove()
xi) copy()
i) append()
Adds element to the end of specified list and does not return any value.
>>>a =[1,2,3]
>>>a.append(4)
>>>a
[1,2,3,4]
ii) extend()
This method add all elements of list to another list.
>>>a= [1,2,3]
>>>b=[4,5,6]
>>>a.extend(b)
>>>a
[1,2,3,4,5,6]
iii) sort()
This method sorts elements in list.
>>>a= [3,1,2]
>>>a.sort()
>>>a
[1,2,3]
iv) reverse()
This method reverse the elements in a list.
>>>a =[1,2,3]
>>>a.reverse()
>>>a
[3,2,1]

159
Problem Solving and Python Programming GE3151

v) pop()
This method removes and returns an element at the given index. If the index is not given,
it removes and returns the last element on the list.
Example:
list=[“eng”,”chem”,”python”,”maths”]
>>>list.pop(2)
python
>>>list
[“eng”,”chem”,”maths”]
>>>list.pop()
[“eng”,”chem,’python”]
vi) clear()
This method clear elements in a list.
>>>a= [1,2,3]
>>>a.clear()
>>>print(a)
[]
vii) index()
This method returns index of given element. If the element is not in the list it returns
error.
>>>a= [1,2,3]
>>>a.index(2)
1
viii) count()

It counts how many times the elements occur in the list.


>>>a= [1,2,3,2,2,1,3]
>>>a.count(3)
2
Syntax:

160
Problem Solving and Python Programming GE3151

listname.count(value)

161
Problem Solving and Python Programming GE3151

ix) insert()
It inserts an element on a desired position of a list.
Syntax:
listname.insert(index,element)
>>>a=[1,2,3]
>>>a.insert(1,4)
>>>a
[1,4,2,3]
x) remove()
It removes the specified element from the list.
>>>a=[1,2,3]
>>>a.remove(2)
>>>print(a)
[1,3]
xi) copy()

It copies one list to another list.


>>>a =[1,2,3]
>>>b=a.copy()
>>>b
[1,2,3]
Syntax:

listname.copy()
List functions:
i) len()
ii) max()
iii) min()
iv) cmp()
v) sum()
vi) sorted()
160
Problem Solving and Python Programming GE3151

i) len() : Returns the number of elements in a list.

161
Problem Solving and Python Programming GE3151

>>>a= [1,2,3,4]
>>>len(a)
4
ii) max(): Returns maximum value from the list .
>>>a= [1,2,3,4]
>>>max(a)
4
iii) min(): Returns minimum value from list.
>>>a= [1,2,3,4]
>>>min(a)
1
iv) cmp(): Compares the elements of lists.
>>>list1 = [123, 'xyz']
>>>list2 = [456, 'abc']
>>>print cmp(list1, list2)
-1
>>>print cmp(list2, list1)
1
>>>list3 = list2 + [786];
>>>print cmp(list2, list3)
-1
v) sum(): It returns the sum of all elements in a list.
>>>a= [5,10,15,5,4]
>>>sum(a)
39
vi) sorted(): Returns the sorted list of elements in ascending order.
>>>a= [4,3,2,1]
>>>sorted(a)
[1,2,3,4]

162
Problem Solving and Python Programming GE3151

4.1.4 List loop [Traversing a loop]


The most common way to traverse elements of a list is using for loop. The looping in a
list is done by for loop. There are two types of for looping
i) for-sequence (for-in-loop)
ii) for-range()
i) for-sequence
for loop is used to read elements of list.
Example:
>>>for i in [2,3,5,6,9]
print (i)
Output:
2
3
5
6
9
ii) for-range
To update elements of list, we need to specify the range.
Example Program1:
>>>for i in range(0,4):
data[i]=[0]*3
>>>data
[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0]
4.1.5 List mutability
The list is a mutable data structure, that means its elements can be replaced, inserted and
removed. A slice operator on the left side of an assignment operation can update single or multiple
elements of a list. New elements can be added to the list using append() method. Also mutability
is the ability of data to be changed without entirely recreating it.
Example:
>>>for i in range(0,4)

163
Problem Solving and Python Programming GE3151

data[i]=[0]*3
>>>data
[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0]
>>>data[1][1]
0
>>>data[2][2]
0
>>>data[1][1]
8
>>>data[2][2]
7
>>>data[1][1]
8
>>>data[2][2]
7
>>>data
[0,0,0],[0,8,0],[0,0,0],[0,0,0],[0,0,0]
4.1.6 List aliasing
List aliasing is defined as circumstance where two (or) more variables refer to the same object.
Example:
>>>a=[1,2,3]
>>>b=a
>>>b is a
True
>>>b is not a
False
In this example, a is assigned to b then both variables refers to same objects.
a
[1,2,3]
b

164
Problem Solving and Python Programming GE3151

Here, the same list has two different names (‘a’ and ‘b’).so it is aliased.
If the aliased object is mutable, modifications done in one object affect the other object also.
Aliasing with mutable object:
Lists are mutable (changeable)
Example:
>>>a=[1,2,3]
` >>>b=a
>>>a
[1,2,3]
>>>b
[1,2,3]
>>>a[0]=10
>>>a
[10,2,3]
>>>b
[10,2,3]
4.1.7 Cloning list
Assignment statements in Python do not copy objects. They simply create bindings between
two objects. For mutable sequences (like lists), a copy of an existing object may be required so
that one object can be changed without affecting another. In lists, cloning operation can be used to
create a copy of an existing list so that changes made in one copy of list will not affect another.
The copy contains the same elements as the original. This can be done using
i) list() function
ii) copy() function
iii) copy.deepcopy() function

i) list() function
built-in list() function can be used for cloning lists with the following syntax
Syntax:
newlistname= list(oldlistname)

165
Problem Solving and Python Programming GE3151

Example:
>>>a= [1,2,3]
>>>b= list(a)
>>>a
[1,2,3]
>>>b
[1,2,3]
>>>a[0]=4
>>>a
[4,2,3]
>>>b
[1,2,3]
ii) copy() function
copy.copy() is little slower than list() since it has to determine data type of old list first.
Syntax:
newlistname= copy.copy(oldlistname)
Example:
>>>import copy
>>>a= [1,2,3]
>>>b= copy.copy(a)
>>>a
[1,2,3]
>>>b
[1,2,3]
iii) copy.deepcopy() function
copy.deepcopy() is the slowest and memory-consuming method.
Syntax :
newlistname = copy.deepcopy(Oldlistname)
Example Program1:
import copy

166
Problem Solving and Python Programming GE3151

oldlist = [10, 20, 30, 40, 70]


newlist = copy.deepcopy(oldlist) # Returns a deep copy of oldlist
print(oldlist)
print(newlist)
Output:
[10, 20, 30, 40, 70]
[10, 20, 30, 40, 70]
4.1.9 List parameters
A list can be passed as a parameter to a function. This parameter is passed by reference.
Changes made in list inside function will affect list even after returning function.
Example Program1: To circulate values of n variable .
def circulate(1,n):
newlist= l[[n:]+ l[n:]
return newlist
list= [1,2,3,4,5]
program(“original list:”, list)
mylist= circulate(list,1)
print(“list circulated clockwise by 1:”, mylist)
mylist= circulate(list, 2)
print(“List circulated clockwise by 2:”, mylist)
mylist= circulate(list, 3)
print(“List circulated clockwise by 3:”, mylist)
mylist= circulated(list, 4)
print(“List circulated clockwise by 4:”, mylist)
Output:
Original list: [1,2,3,4,5]
list circulated clockwise by1:[2,3,4,5,1]
list circulated clockwise by 2:[3,4,5,1,2]
list circulated clockwise by 3:[4,5,1,2,3]
list circulated clockwise by 4:[5,1,2,3,4]

167
Problem Solving and Python Programming GE3151

Here list passed as parameter to function (circulate), this list is circulated based on value the value.
4.1.10 Deleting list elements
To remove a list element, del operator can be used if an element to be deleted is known.
In the following code, the element ‘Chennai’ is deleted by mentioning its index in the del operator.
Example Program:
stulist = [‘Rama’, ‘Chennai’, 2018, ‘CSE’, 92.7]
print ‘Initial list is : ‘, stulist
del stulist[1]
print ‘Now the list is : ‘, stulist
Output:
Initial list is : [‘Rama’, ‘Chennai’, 2018, ‘CSE’, 92.7]
Now the list is : [‘Rama’, 2018, ‘CSE’, 92.7]
pop() and remove() methods can also be used to delete list elements.
4.2 TUPLES
Tuple is a collection sequence of values of different types. Unlike lists, tuple values are
indexed by integers. The important difference is that tuples are immutable. Tuples are created
using parenthesis (). The important points to be noted are
i) The values in tuples can be any type and they are indexed by integers
ii) A type is a comma-seperated list of values.
Example:
>>>t=’a’,’b’,’c’,’d’,’e’
Creation of tuples:
i) Create a tuple with a single element.
>>>t1= ‘a’
>>>type(t1)
<class ‘tuple’>
>>>t2=(‘a’)
>>>type(t2)

168
Problem Solving and Python Programming GE3151

<class ‘str’>
ii) A tuple can be created using the built-in function tuple. It can create an empty tuple
with no argument.
>>>t= tuple()
>>>t
()
iii) A tuple built-in- functions can be used to create a tuple with sequence of arguments.
>>>t= tuple(‘computer’)
>>>t
(‘c’,’o’,’m’,’p’,’u’,’t’,’e’,’r’)
Operators on tuple:
i) Bracket operator
ii) Slice operator
iii) Relational operator
i) Bracket operator
Bracket operator indexes an element.
>>>t= (‘c’,’o’,’m’,’p’)
>>>t[0]
‘c’
>>>t[3]
‘p’
ii) Slice operator
Slice operator selects a range of elements.
>>>t[0:3]
(‘c’,’o’,’m’)
iii) Relational operator
The relational operators work with tuples and other sequences.
Python starts by comparing the first element from each sequence.
If they are equal, it goes on to the next elements and so on, until it finds elements that
differ.

169
Problem Solving and Python Programming GE3151

Subsequent elements are not considered.


Example:
>>>(5,8,2)<(5,10,6)
True
>>>(3,2,500000)<(3,8,5)
True
4.2.1 Tuple assignment
Python has a very powerful tuple assignment feature that allows a tuple of variables on
the left of an assignment to be assigned values from a tuple on the right of the assignment.
Example 1:
>>>a,b= 5,10
>>>a
5
>>>b
10
Example 2:
>>>a,b= minmax(‘abcd’)
>>>a
‘a’
>>>b
‘d’
The requirement is that the number of variables on the left must match with the number of
elements in the tuple.
>>>a,b= 1,2,3
valueError: too man values to un pack
>>>[x,y] = [3,4]
>>>x
3
>>>y
4

170
Problem Solving and Python Programming GE3151

The right side can be any kind of sequence (string, list or tuple).
Example:
To split an email address into a username and a domain consider the following
>>>addr=’[email protected]
>>>uname,domain= addr.split(‘@’)
Here split is a keyword, the return value from split is a list with two elements and the first
element is assigned to username, the second to domain
>>>uname
‘effie’
>>>domain
‘python.org’
4.2.2 Tuples as return values
A function can return only one value, but if the value is a tuple, it can return multiple values.
The built-in function divmod takes two arguments and returns a tuple of two values, the quotient
and the remainder. Here the type of returning a values are
i) It can store the result as a tuple.
>>>t= divmod(13,4)
>>>t
(3,1)
ii) To store the elements separately, use tuple assignment.
>>>Q,R= divmod(13,4)
>>>Q
3
>>>R
1
iii) A function can return a tuple. The built-in function def minmax(t) is used to find the
largest and smallest elements of a sequence and can return a tuple of two values.
def minmax(t):
return min(t),max(t)

170
Problem Solving and Python Programming GE3151

max and min are built-in functions that find the largest and smallest elements of the
sequence.
minmax computes both the largest and smallest elements and returns a tuple of two
values.
Example Program:
>>>def minmax(t):
return min(t), max(t)
>>>minmax([6,3,7,12])
(3,12)
>>>minmax(‘abcd’)
(‘a’,’d’)
4.2.3 Accessing values
To access the tuple elements slicing (bracket operator [ ]) operator along with index or
indices is used.
Example Program:
t1 = (‘C’, ‘C++’, ‘python’, 1999, 2018);
t2 = (1, 2, 3, 4, 5, 6, 7 );
t3= (‘a’, ‘b’, ‘c’, ‘d’, ‘e’)
print “tup1[0]: “, tup1[0]
print “tup1[1]: “, tup1[1]
print “tup2[1:5]: “, tup2[1:5]
print “tup2[1:]: “, tup2[1:]
print t[0]
Output:
tup1[0]: C
tup1[1]: C++
tup2[1:5]: [2, 3, 4, 5, 6, 7]
a

171
Problem Solving and Python Programming GE3151

4.2.4 Delete tuple elements


It is impossible to delete a single element in the tuple. There is, of course, nothing wrong
with putting together another tuple with the undesired elements discarded. To delete an entire tuple,
the keyword del is used.
Example Program:
t1 = (‘C’, ‘C++’, ‘python’, 1999, 2018);
print t1
del t1
print “After deleting : “
print t1
Output:
(‘C’, ‘C++’, ‘python’, 1999, 2018)
After deleting:
Traceback (most recent call last):
File “main.py”, line 5, in
print t1
NameError: name ‘t1’ is not defined
4.2.5 Updating tuples
Tuples are immutable means that the tuple values cannot be updated or changed. However,
the portions of existing tuples are added with a new tuple to create another tuple as the following
example demonstrates. Consider the following tuple,
t3= (‘a’, ‘b’, ‘c’, ‘d’, ‘e’)
No elements can be modified. If you try to modify, you will get an error.
t3[1]= ‘B’
TypeError: ‘tuple’ object does not support item assignment
Instead of modifying an element in the tuple sequence, it is obvious to simply replace one tuple
with another:
t3 = (‘A’) + t3 [1:]
print t

172
Problem Solving and Python Programming GE3151

Output:
(‘A’, ‘b’, ‘c’, ‘d’, ‘e’)
Here, the first element ‘a’ is replaced with ‘A’. A new tuple is created with the value ‘A’ is
combined with tuple t3 having index from 1 to the last element. The tuple value t3[0]=’a’ is
replaced by ‘A’.
4.2.6 Built-in functions with tuple
The built-in functions with tuples are given below.
i) all(): Return True if all elements of the tuple are true (or if the tuple is empty).
ii) any():Return True if any element of the tuple is true. If the tuple is empty, return False.
iii) enumerate():Return an enumerate object. It contains the index and value of all the items of
tuple as pairs.
iv) len():Return the length (the number of items) in the tuple.
v) max():Return the largest item in the tuple.
vi) min():Return the smallest item in the tuple
vii) sorted():Take elements in the tuple and return a new sorted list (does not sort the tuple
itself).
viii) sum():Return the sum of all elements in the tuple.
4.2.7 Comparing tuples
With relational operators it is possible to work with tuples and other sequences. To compare
two elements, Python starts by comparing the first element from each sequence. If the elements
are equal, it goes on to the next elements, and so on, until it finds an element that is different,
subsequent elements are not considered (even if they are really big)
>>> (0, 1, 2) < (0, 3, 4)
True
4.3 Dictionaries
Dictionary is a collection that shows values along with key,the sequence of such key and
value pair is separated by commas, these pairs are sometimes called entries or items,all the entries
are enclosed by {}.A colon seperates key and its values.
 Dictionaries in Python are implemented using hash table. It is an array whose indexes
are obtained using a hash function on the keys.

173
Problem Solving and Python Programming GE3151

Dictionary is a mutable list.


A hash function takes a key value and returns hash value, an integer. This hash value is
used in the dictionary to store and lookup key-value pairs. So keys in dictionary must be hashable.
Example1:
>>>d={1:apple’,2:’ball’}
>>>d
{1:apple’,2:’ball’}
>>>d[1]
apple
>>>d[2]
Ball
Example2:
>>>d={‘name’,:’ABCD’,’phoneno’,:04652}
>>>d[name]
ABCD
>>>d[phone no]
04652
Example3:
>>>for key , val in d.items():
print (val:key)
name: ABCD
phoneno: 04652
The following code is a simple example which creates an empty dictionary.
mydict = {}
print mydict
Output:
{}
4.3.1 Dictionary –Operations and Methods.
The following dictionary operations and methods are used in python programming.

174
Problem Solving and Python Programming GE3151

i) dict()
ii) dict(s)
iii) len()
iv) max()
v) min()
vi) all()
vii) sorted()
viii) any()
ix) pop()
x) copy()
xi) key()
xii) values()
xiii) update()
xiv) clear()
i) dict() : It creates a new, empty dictionary.
>>>cse=dict()
>>>cse
{}
ii) dict(s): It creates a new dictionary with key-value.
>>>cse=dict(s)
iii) len(): It counts the number of key value pairs.
>>>cse={‘name’:’ABC’,’age’:20}
>>>len(cse)
2
iv) max(): It returns the maximum key in dictionary.
>>>max(xse)
2
v) min(): It returns the minimum key in dictionary.
>>>min(cse)
1

175
Problem Solving and Python Programming GE3151

vi) all(): It returns true if all keys are true.


>>>all(cse)
True
vii) sorted(): It sort keys in order.
>>>sorted(cse)
[age’,’name’]
viii) any(): It returns true if any key is true
>>>any(cse)
True
ix) pop(): It removes particular item from dictionary.
>>>cse.pop(age)
>>>cse
{‘name’:’ABC’}
x) dict.copy(): It copies dictionary into new dictionary.
>>>cse={‘name’:’ABC’,’age’:’20’}
xi) dict.key(): It returns keys in dictionary
>>>dict.key(cse)
‘name’,’age’
xii) dict.values(): It returns values in dictionary.
>>>dict.values(cse)
‘ABC’,20
xiii) dict.update(): It adds dictionary key-value pairs to dictionary.
>>>dict.update(cse,”address”:”xyz”)
>>>cse
{‘name:’’ABC’,’age’:220,”address’:”xyz}
xiv) dict.clear(): It clears dictionary.
>>>dict.clear(cse)
>>>cse
{}

176
Problem Solving and Python Programming GE3151

4.3.2 Access, update, and add elements in dictionary


Key can be used either inside square brackets or with the get() method. The difference
while using get() is that it returns none instead of KeyError, if the key is not found. Dictionary is
mutable. So we can add new items or change the value of existing items. If the key is present, its
value gets updated, else a new key: value pair is added to dictionary.
4.3.3 Delete or remove elements from a dictionary
A particular item in a dictionary can be removed by using the method pop(). This method
removes an item with the provided key and returns the value. The method, popitem()can be used
to remove and return an arbitrary item (key, value) from the dictionary. All the items can be
removed at once using the clear () method.
4.3.4 Sorting a dictionary
The items in dictionary can be sorted using sorted () function. In the following example,
fromkeys() function is used to create a dictionary from sequence of values. The value 10 is assigned
for all keys. Each item is accessed iteratively using for loop that iterate though each key in a
dictionary.
Example Program:
marks={}.fromkeys([‘Math’,’English’,’Science’],10)
print marks
for item in marks.items():
print item
print list(sorted(marks.keys()))
Output:
{‘Maths’: 10, ‘Science’: 10, ‘English’: 10}
(‘Maths’, 10)
(‘Science’, 10)
(‘English’, 10)
[‘English’, ‘Maths’, ‘Science’]
4.3.5 Reverse lookup
Lookup is the process of finding the corresponding value for the given key from
dictionary. It’s easy to find the value given a key to a Python dictionary.

177
Problem Solving and Python Programming GE3151

value=dict[key]
Whereas, reverse lookup is the process of finding the key for a given value. There is no direct
method to handle reverse lookup. The following function takes a value and returns the first key
that map to that value.
Example Program:
def getvalue(dic,value):
for name in dic:
if dic[name] == value:
return name
raise ValueError
squares={1:1,2:4,3:9,4:16,5:25}
print getvalue(squares,4)
Output:
2
4.3.6 Inverting a dictionary
A dictionary can be inverted with list values. For example, if you were given a dictionary
that maps from child to parent, you might want to invert it; that is, create a dictionary that maps
from parent to children. Since there might be several children with the same parent each value in
the inverted dictionary should be a list of children.
Example Program:
def invertdict(d):
newdict = {}
for k, v in d.iteritems():
newdict.setdefault(v, []).append(k)
return newdict
d = { ‘child1’: ‘A1’,
‘child2’: ‘A1’,
‘child3’: ‘parent2’,
‘child4’: ‘parent2’,
}

178
Problem Solving and Python Programming GE3151

print invertdict(d)
Output:
{‘parent2’: [‘child3’, ‘child4’], ‘A1’: [‘child1’, ‘child2’]}
4.4 ADVANCED LIST PROCESSING
.The list comprehension is the advanced list processing is given below.
4.4.1 List comprehensions
List comprehension is an elegant and concise way to create new list from existing list in
python. List comprehension process is described by series of keywords.
Syntax:
[expression for item in list if conditional]

This is equivalent to:


for item in list:
if conditional:
expression
new_list = [expression(i) for i in oldlist if filter(i)]

newlist is the resultant list. expression (i) is based on the variable used for each element in the
old list. If needed filter can be applied using if statement.
A list comprehension consists of the following parts:
i) An input sequence.
ii) Variable representing members of the input sequence.
iii) An optional predicate expression.
iv) An Output expression producing elements of the output list from members of the
input sequence that satisfy the predicate.
Example Program1:
>>>a=[11,22,33,44]
>>>b=[x*2 for x in a]
>>>b
[22,44,66,88]

179
Problem Solving and Python Programming GE3151

Example Program2:
>>>names=[‘alice’,’bob’,’charly’]
>>>b=[ x.upper() for x in names]
[‘ALICE’,’BOB,’CHARLY]
>>>c=[x.capitalize() for x in names]
>>>c
[‘Alice’,’Bob’,’Charly’]
Example Program3:
>>>vowels=(‘a’,’e’,’i’,’o,’u’)
>>>t=’hello’
>>>[c for c in t if c in vowels]
[‘e’,’o’]
Example Program4:
>>>a=[1,2,3,4]
>>>[x**2 for x in a]
[1,4,9,16]
Example Program5:
>>>a= [10,5,0,-5,-10]
>>>[x for x in a if x>0]
[10,5]
>>>[x for x in a if x<0]
[-5,-10]

4.5 ILLUSTRATIVE PROGRAMS


4.5.1 Insertion sort
def insertionsort(a):
for index in range(1,len(a)):
currentvalue=a[i]
position=i
while position>0 and a[position-1]>currentvalue:

180
Problem Solving and Python Programming GE3151

a[position]=a[position-1]
position=position-1
a[position]=currentvalue
list=[50,60,40,30,20,70]
print( “Original list is:”,list)
insertionsort(list)
print(”List after insert:”,a)
Output:
Original list is: =[50,60,40,30,20,70]
List after insert:[20,30.40,50,60,70]

4.5.2 Selection sort


def selectionSort(alist):
for i in range(len(alist)-1,0,-1):
pos=0
for location in range(1,i+1):
if alist[location]>alist[pos]:
pos= location
temp = alist[i]
alist[i] = alist[pos]
alist[pos] = temp
alist = [54,26,93,17,77,31,44,55,20]
selectionSort(alist)
print(alist)
Output:
[17, 20, 26, 31, 44, 54, 55, 77, 93]
4.5.3 Merge sort
def mergesort(a):
if len(a)>1:
mid=len(a)//2

181
Problem Solving and Python Programming GE3151

left=a[:mid]
right=a[mid:]
mergesort(left)
mergesort(right)
i=0
j=0
k=0
while i<len(left) and j<len(right):
if left[i]<right[j]:
a[k]=left[i]
i=i+1
else:
a[k]=right[j]
j=j+1
k=k+1
while i<len(left):
a[k]=left[i]
i=i+1
k=k+1
while j<len(right):
a[k]=right[j]
j=j+1
k=k+1
list=[50,60,40,20,70,100]
print ("Original list is:" ,list)
mergesort(list)
print ("Sorted list is:",list)

Output:
Original list is: [50, 60, 40, 20, 70, 100]

182
Problem Solving and Python Programming GE3151

Sorted list is: [20, 40, 50, 60, 70, 100]


4.5.4 Histogram
def histogram(items):
for n in items:
output=’’
times=n
while (times>0):
output+=’*’
times=times-1
print(output)
histogram([2,3,4,3,2])
Output:
**
***
****
***
**

183
Problem Solving and Python Programming GE3151

PART A (2 Marks with Answers)


1. What is a list? How list differs from tuple? (JANUARY 2018)
A list is an ordered set of values, where each value is identified by an index. The values
that make up a list are called its elements. Lists are similar to strings, which are ordered sets of
characters, except that the elements of a list can have any type.
The syntax for expressing literals of type list is similar to that used for tuples, the difference
is that we use square brackets rather than parenthesis. Lists are mutable, tuples are immutable.
2. How to slice a list in python? (JANUARY 2018)
The values stored in a list can be accessed using slicing operator with indices starting at
0 in the beginning of the list and ending with -1.
Syntax:
listname[start:finish-1]
3. What are the string operators?
String contains the slicing operator and the slicing with step size parameter is used to
obtain the sub set of a string. It also contain concatenation ‘+’,’in’ and repetition ‘*’ operators.
4. Mention any 5 list methods.
i) sort()
ii) pop()
iii) index()
iv) insert
v) remove()
vi)append()
vii)extend ()
5. State the difference between lists and dictionary.
List is a mutable type meaning that it can be modified whereas dictionary is immutable.
Dictionary is not ordered and it requires that the keys are hashable whereas list can store a
sequence of objects in a certain order.

184
Problem Solving and Python Programming GE3151

6. What is List mutability in Python? Give an example.


Python represents all its data as objects. Some of these objects like lists and dictionaries
are mutable, i.e., their content can be changed without changing their identity. Other objects like
integers, floats, strings and tuples are objects that cannot be changed.
Example:
>>> numbers = [17, 123]
>>> numbers[1] = 5
>>> print numbers [17, 5]
7. What is aliasing in list? Give an example.
Aliasing is a circumstance where two or more variables refer to the same object.
Example: If a refers to an object and we assign b = a, then both variables refer to the same
object.
>>> a = [1, 2, 3]
>>> b = a
>>> b is a True
8. Define cloning in list.
In order to modify a list and also keep a copy of the original, it is required to make a copy
of the list itself, not just the reference. This process is called cloning.
9. Explain List parameters with an example.
Passing a list as an argument actually passes a reference to the list, not a copy of the list.
For example, the function head takes a list as an argument and returns the first element.
def head(list):
return list[0]
10. Write a program in Python to delete first element from a list.
def deleteHead(list):
del list[0]
Exmple:
>>> numbers = [7, 2, 3]
>>> deleteHead(numbers)
>>> print numbers [2, 3]

185
Problem Solving and Python Programming GE3151

11. How will you change the elements of Python list?


The elements of Python list can be replaced, inserted and removed (List is a mutable data
structure). A slice operator on the left side of an assignment operation can update single or multiple
elements of a list. New elements can be added to the list using append() method.
12. What is the benefit of using tuple assignment in Python?
It is often useful to swap the values of two variables. With conventional assignments a
temporary variable would be used. For example, to swap a and b:
>>> temp = a
>>> a = b
>>> b = temp
Using tuple assignment we can easily swap
>>> a, b = b, a
13. How to create copy of a list?
In lists, cloning operation can be used to create a copy of an existing list so that changes
made in one copy of list will not affect another. The copy contains the same elements as the
original.
14. Define dictionary with an example.
A dictionary is an associative array. Any key of the dictionary is mapped to a value. The
values of a dictionary can be any Python data type. So dictionaries are unordered key-value pairs.
Example:
>>> eng2sp = {} # empty dictionary
>>> eng2sp[’one’] = ’one’
>>> eng2sp[’two’] = ’two’
15. How to return tuples as values?
A function can only return one value, but if the value is a tuple, the effect is the same as
returning multiple values. For example, if we want to divide two integers and compute the quotient
and remainder, it is inefficient to compute x/y and then x%y. It is better to compute them both at
the same time.
>>> t = divmod(7, 3)

186
Problem Solving and Python Programming GE3151

>>> print t (2, 1)


16. How do you remove duplicates from a list?
Steps:
(i) sort the list.
(ii) scan the list from the end.
(iii) while scanning from right-to-left, delete all the duplicate elements from the list
17. Define dictionary methods with an example.
A method is similar to a function, it takes arguments and returns a value but the syntax is
different. For example, the keys method takes a dictionary and returns a list of the keys that appear,
but instead of the function syntax keys(eng2sp), method syntax eng2sp.keys() is used.
>>> eng2sp.keys() [’one’, ’three’, ’two’]
18. Define List Comprehension.
It provides a compact way of mapping a list into another list by applying a function to
each of the elements of the list.
19. Write a Python program to swap two variables.
x = 50
y = 100
print('The value of x after swapping: ',x)
temp = x
x=y
y = temp
print('The value of y after swapping: ',y)
20. How many kinds of sequences are supported by Python?
Python supports 7 sequence types. They are str, list, tuple, unicode, bytearray, xrange, and
buffer.
21. Solve
a)[1] * 4 and
b) [1, 2, 5] * 3.
>>> [01] * 4 [1, 1, 1, 1]
>>> [1, 2, 5] * 3 [1, 2, 5, 1, 2, 5, 1, 2, 5]

187
Problem Solving and Python Programming GE3151

22. Let list = [’a’, ’b’, ’c’, ’d’, ’e’, ’f’].


Find a) list[1:3] b) t[:4]
>>> list = [’a’, ’b’, ’c’, ’d’, ’e’, ’h’]
>>> list[1:3] [’b’, ’c’]
>>> list[:4] [’a’, ’b’, ’c’, ’d’]
23. Write a program in Python returns a list that contains all but the first element of the
given list.
def tail(list):
return list[1:]
Here’s how tail is used:
>>> numbers = [1, 2, 3]
>>> rest = tail(numbers)
>>> print rest [2, 3]
24. List two dictionary operations.
i) Del -removes key-value pairs from a dictionary.
ii) Len -returns the number of key-value pairs.

25. Compare lookup and reverse lookup.


Lookup is the process of finding the corresponding value for the given key from dictionary.
It's easy to find the value given a key to a python dictionary. value=dict[key] Whereas, reverse
lookup is the process of finding the key for a given value.

26. Write the syntax for list comprehension.


The basic syntax is [ expression for item in list if conditional]

27. Define key- value pairs.


The elements of a dictionary appear in a comma-separated list. Each entry contains an
index and a value separated by a colon. In a dictionary, the indices are called keys, so the elements
are called key-value pairs.

188
Problem Solving and Python Programming GE3151

28. Relate Strings and Lists. (JANUARY 2019)


• String is a sequence of characters and a List is a sequence of values, but a list of
characters is not same as string.
• To convert from a string to a list of characters list can be used.
>>>S=’Python’
>>>T=list(S)
>>>print T
[‘P’,’y’,’t’,’h’,’o’,’n’]

29. Give a function that can take a value and return the first key mapping to that value in a
dictionary. (JANUARY 2019)

def reverse_lookup(d,v):
for k in d:
if d[k]==v:
return k
raise Value Error
30. How will you update list items? Give one example. (JANUARY 2020)
List will be updated using index value.
Example:
>>>a=[1,2,3]
>>>a[0]=10
>>> print(a)
[10,2,3]
31. Can function return tuples? If yes give example. (JANUARY 2020)
Yes function return tuples.
Example:
def add(a,b)
return(a+b)
add(3,2)

189
Problem Solving and Python Programming GE3151

PART B (Possible Questions)


1. Explain the different ways to create a list with suitable examples.
2. How are elements of a list reversed? Explain.
3. What is list? How will you create list? Explain with neat program.
4. Define dictionary. Explain the various operation s of dictionary with an example.
5. What do you mean by tuple? How will you create a truple? Explain.
6. Explain the following
i) Aliasing
ii) Cloning a list
7. How is an empty list and list with six integers, ie 30,35,40,90,95 and 100 created?
8. List and clarify the operators supporting lists.
9. Explain the supporting inbuilt functions used to create lists.
10. Write a program to pass a list to a function and return it in the reverse order.
11. i)What is a dictionary in python? Give example. (4) (JANUARY 2018)
ii) Appraise the operations for dynamically manipulating dictionaries. (12)
12. i)Write a python program to perform linear search on a list.(8) (JANUARY 2018)
ii) Write a python program to store n numbers in a list and sort the list using selection sort. (8)
13.i)Discuss the different options to traverse a list. (8)
ii)Demonstrate the working of +,* and slice operators in python .(8) (JANUARY 2019)
14. i)Compare and contrast tuples and list in python. (4)
ii)Write a script in python to sort n number using selection sort.(12) (JANUARY 2019)
15. i)Define Dictionary in Python. Do the following operations on dictionaries.(10)
i) Initialize two dictionaries and create a new dictionary with key value pairs.
ii) Compare the two dictionaries with master key and print missing keys.
iii)Find keys that are in first and not in second dictionary.
iv) Find same keys in two dictionaries.
v) Merge two dictionaries and create a new dictionary using a single expression.
ii)What is list comprehension in python? Explain with example. (6) (JANUARY 2020)
16.i)What is tuple in python? How does it differ from list?(8)
ii)Write a python program t sort n numbers using mergesort.(8) (JANUARY 2020)

190
Problem Solving and Python Programming GE3151

PART C (Possible Questions)


1 .Write a Python program to duplicate all the elements in a list.
2. Write Python program for the following.
a. Merge sort
b. Selection sort
3. Write a Python program for palindrome using functions and list.
4. Create a list of six elements. Pass the list to a function and compute the average of six
numbers.
5. Write a Python program to create a list to store the names of colors and return size of list.
6. Write a Python program to put even and odd elements in a list into two different lists.
7. Write a Python program to remove the duplicate items from a list.
8. Write a Python program to multiply two matrices.
9. Write a Python program to count the frequency of words appearing in a string using a
dictionary.
10. Write a Python program to add and remove a key-value pair to the dictionary.

191
Problem Solving and Python Programming GE3151

Additional Programs

1. Positive or negative number


n=eval(input("enter a number:"))
if(n>=0):
print("positive number")
else:
print("negative number")
Output:
enter a number:88
positive number
2. Leap year or not
y=eval(input("enter a yaer:"))
if(y%4==0):
print("leap year")
else:
print("not leap year")
Output:
enter a year:2004
leap year
3. Greatest of three numbers
a=eval(input(“enter the value of a:”))
b=eval(input(“enter the value of b:”))
c=eval(input(“enter the value of c:”))
if(a>b):
if(a>c):

print(“The greatest number is”,a)


else:
print(“The greatest number is”,c)
else:

148
Problem Solving and Python Programming GE3151

if(b>c):

149
Problem Solving and Python Programming GE3151

print(“The greatest number is”,b)

else:
print(“The greatest number is”,c)

Output

enter the value of a: 9


enter the value of b: 1
enter the value of c: 8
The greatest number is 9
4. Student mark system
mark=eval(input("enter your mark:"))
if(mark>=90):
print("grade:S")
elif(mark>=80):
print("grade:A")
elif(mark>=70):
print("grade:B")
elif(mark>=50):
print("grade:C")
else:
print("fail")
Output:
enter your mark:78
grade:B
5. Sum of n numbers
n=eval(input("Enter the value of n:"))
i=1
sum=0
while(i<=n):
sum=sum+i
150
Problem Solving and Python Programming GE3151

i=i+1

151
Problem Solving and Python Programming GE3151

print(sum)
output
Enter the value of n :
10
55
6. Print no’s divisible by 5 not by 10
n=eval(input("enter a"))
for i in range(1,n,1):
if(i%5==0 and i%10!=0):
print(i)
Output:
enter a:30
5
15
25

150
Problem Solving and Python Programming GE3151

Additional Programs
1. Python program to find the largest number in a list.
a=[]
n=int(input("Enter the number :"))
for i in range(1,n+1):
b=int(input("Enter element:"))
a.append(b)
a.sort()
print("Largest element is:",a[n-1])
Output:
Enter the number :3
Enter element:33
Enter element:569
Enter element:73
Largest element is: 569
2. Python program to put even and odd elements in a list into two different lists.
a=[]
n=int(input("Enter number of elements:"))
for i in range(1,n+1):
b=int(input("Enter element:"))
a.append(b)
even=[]
odd=[]
for j in a:
if(j%2==0):
even.append(j)
else:
odd.append(j)
print("The even list",even)
print("The odd list",odd)

192
Problem Solving and Python Programming GE3151

Output:
Enter number of elements:5
Enter element:69
Enter element:45
Enter element:46
Enter element:28
Enter element:457
The even list [46, 28]
The odd list [69, 45, 457]
3. Python program to remove the duplicate items from a list.
a=[]
n= int(input("Enter the number of elements in list:"))
for x in range(0,n):
element=int(input("Enter element" + str(x+1) + ":"))
a.append(element)
b = set()
unique = []
for x in a:
if x not in b:
unique.append(x)
b.add(x)
print("Non-duplicate items:")
print(unique)
Output:
Enter the number of elements in list:5
Enter element1:100
Enter element2:100
Enter element3:220
Enter element4:220
Enter element5:220

193
Problem Solving and Python Programming GE3151

Non-duplicate items:
[100, 220]
4. Python program to add a key-value pair to the dictionary.
key=int(input("Enter the key (int) to be added:"))

value=int(input("Enter the value for the key to be added:"))

d={}

d.update({key:value})

print("Updated dictionary is:")

print(d)

Output:
Enter the key (int) to be added:12
Enter the value for the key to be added:34
Updated dictionary is:
{12: 34}
5. Python program to concatenate two dictionaries in to one.
d1={'A':1,'B':2}

d2={'D':3}

d1.update(d2)

print("Concatenated dictionary is:")

print(d1)

Output:
Case 1:
Concatenated dictionary is:
{'A': 1, 'D': 3, 'B': 2}
6. Python program to check if a given key exists in a dictionary or not.
d={'A':1,'B':2,'C':3}

key=raw_input("Enter key to check:")

194
Problem Solving and Python Programming GE3151

if key in d.keys():

print("Key is present and value of the key is:")

print(d[key])

else:

print("Key isn't present!")

Output:
Enter key to check: A
Key is present and value of the key is:
1
7. Python program to sum all the items in a dictionary.
d={'A':100,'B':540,'C':239}

print("Total sum of values in the dictionary:")

print(sum(d.values()))

Output:
Total sum of values in the dictionary:
879
8. Python program to multiply all the items in a dictionary.
d={'A':100,'B':100,'C':239}

tot=1

for i in d:

tot=tot*d[i]

print(tot)

Output:
2390000
9. Python program to remove the given key from a dictionary.
d = {'a':1,'b':2,'c':3,'d':4}
print("Initial dictionary")

195
Problem Solving and Python Programming GE3151

print(d)
key=raw_input("Enter the key to delete(a-d):")
if key in d:
del d[key]
else:
print("Key not found!")
exit(0)
print("Updated dictionary")
print(d)
Output:
Initial dictionary
{'a': 1, 'c': 3, 'b': 2, 'd': 4}
Enter the key to delete(a-d):c
Updated dictionary
{'a': 1, 'b': 2, 'd': 4}
10. Python program to count the frequency of words appearing in a string using a
dictionary.
test_string=raw_input("Enter string:")
l=[]
l=test_string.split()
wordfreq=[l.count(p) for p in l]
print(dict(zip(l,wordfreq)))
Output:
Enter string: hello world program world test
{'test': 1, 'world': 2, 'program': 1, 'hello': 1}

196
Problem Solving and Python Programming GE3151

CHAPTER 5

FILES, MODULES, PACKAGES

Files and exception: text files, reading and writing files, format operator; command line arguments,
errors and exceptions, handling exceptions, modules, packages; Illustrative programs: word count,
copy file.

197
Problem Solving and Python Programming GE3151

198
Problem Solving and Python Programming GE3151

FILES, MODULES, PACKAGES


5.1 FILES AND EXCEPTION
Files:
File is a named location on disk to store the related information. A collection of data or
information that has a name is called the file name. All information stored in a computer must be
in a file.
Types of files:
i) Data files
ii) Text files
iii) Program files
iv) Directory files
5.1.1 Text files
Text file is a sequence of characters stored on a permanent medium like hard drive, flash
memory (or) CD-ROM. In addition to printable characters, the text file contains non printing
characters. So a text file contain letters (a-z/A-Z), numbers (0-9), special symbols ($,#),non
printing characters(\n,\t,\b) etc. Text file should be saved with the extension .txt.
5.1.2 File operations
In Python, a file operation takes place in the following order.
i) Opening the file
ii) Reading and writing (perform operation)
iii) Closing the file
i) Opening the file
When the user wants to read or write to a file, user needs to open it first. Python has a
built-in function open () to open a file.
Syntax:
fileobject=open(“filename”, ”access mode”)
The parameters are explained below:
filename The filename argument is a string value that contains the name of the file to access.

access mode The access mode denotes the mode in which the file has to be opened (read,

199
Problem Solving and Python Programming GE3151

write, append, etc).


Example:
>>>f=open(“test.txt”,”w”)
File opening modes:
There are various modes while opening a file. They are,
Modes Description
Opens a file for reading only. The file pointer is placed at the beginning of
r
the file.
Opens a file for reading only in binary format. The file pointer is placed at
rb
the beginning of the file. This is the default mode.
Opens a file for both reading and writing. The file pointer placed at the
r+
beginning of the file.
Opens a file for both reading and writing in binary format. The file pointer
rb+
placed at the beginning of the file.
Opens a file for writing only. Overwrites the file if the file exists. If the
w
file does not exist, creates a new file for writing.
Opens a file for writing only in binary format. Overwrites the file if the
wb
file exists. If the file does not exist, creates a new file for writing.
Opens a file for both writing and reading. Overwrites the existing file if
w+ the file exists. If the file does not exist, creates a new file for reading and
writing.
Opens a file for both writing and reading in binary format. Overwrites the
wb+ existing file if the file exists. If the file does not exist, creates a new file
for reading and writing.
Opens a file for appending. The file pointer is at the end of the file if the
a file exists. If the file does not exist, it creates a new file for writing.

Opens a file for appending in binary format. The file pointer is at the end
ab
of the file if the file exists. If the file does not exist, it creates a new file

200
Problem Solving and Python Programming GE3151

for writing.
Opens a file for both appending and reading. The file pointer is at the end
a+ of the file if the file exists. If the file does not exist, it creates a new file
for reading and writing.
Opens a file for both appending and reading in binary format. The file
ab+ pointer is at the end of the file if the file exists. If the file does not exist, it
creates a new file for reading and writing.

The file object attributes:

Attribute Description
Returns true if the file is closed, otherwise
file.closed
false.
Returns the file access mode with which file
file.mode
was opened.
file.name Returns name of the file.
ii) Reading and writing files
Python provides read () and write () methods to read and write files through file object
respectively.
Reading files:
The read() method read the file contents, from opened file. To read the content of file, the
file must be opened in read mode (r).There are 4 methods for reading files.
i ) Reading a file using read(size) method
ii) Reading a file using for loop
iii) Reading a file using readline() method
iv) Reading a file using readlines() method
The file test.txt contains
problem solving and python programming.
Introduction to python
i) Reading a file using read(size) method
201
Problem Solving and Python Programming GE3151

The read(size) method is used to read in size number of data.If the size parameter is not
specified, it reads and returns up to the end of file.
Syntax:
fileobject . read([size])
Example:
f=open(“test.txt”, “r+”)
S=f.read(15);
print(“Read string is:”,S)
f.close()
Output:
Read string is: problem solving
ii) Reading a file using for loop
A file can be read using for loop. This method is efficient and fast.
Syntax:
for loopvariable in fileobject:
print(loopvariable)
Example Program:
f=open(“test.txt”, “r+”)
for i in f:
print(i)
f.close()
Output:
Problem solving and python programming
Introduction to python
iii) Reading a file using readline() method
The readline() method is used to read individual line of a file. It reads a file till the
newline(\n) character is reached (or) end of file is reached.
Syntax:
fileobject . readline()
Example Program:

202
Problem Solving and Python Programming GE3151

f=open(“test.txt”, “r+”)
f.readline()
f.close()
Output:
Problem solving and python programming
iv) Reading a file using readlines() method
The readlines() method is used to read all the lines of file at a time.
Syntax:
fileobject.readlines()
Example Program:
f=open(“test.txt”, “r+”)
f.readlines()
f.close()
Output:
Problem solving and python programming
Introduction to python
Writing files:
The write() method is used to write the contents into the file. To write the file contents,
the file must be opened into following mode.
w-writing mode
a-appending mode
x-exclusive creation
The ‘w’ mode will overwrite into the file if already exists. So all previous data’s are erased.
Syntax:
fileobject . write(string)
Example Program:
f=open(“test.txt”, “r+”)
f.write(“Welcome to python”)
f.close()
iii) Closing the file

203
Problem Solving and Python Programming GE3151

The function close() of a file object flushes if there is any unwritten information and closes
the file object when there is no more writing can be done. Python closes a file automatically when
the reference object of a file is reassigned with another file. The syntax of close () function is given
below.
Syntax:
fileobject.close()
Example Program:
f1=open(“test.txt”,”w”)
print(“Name of file is:”,f1.name)
print(“closed or not:”,f1.closed)
print(“opening mode is:”,f1.mode)
f1.close()
Output:
Name of file is:test.txt
closed or not:False
opening mode is:w
5.1.3 Format Operator
write() function takes the argument as a string . To put other values in a file, it must be
converted to strings. It is done by 2 methods:
i) str() method is used to convert other values into string.
Example Program:
>>>x=52
>>>f.write(str(x))
52
ii) Format operator is an % operator that converts other values into string.
with integers, % is considered as modulus operator
with strings,% is considered as format operator

Example Program:
>>>x=15

204
Problem Solving and Python Programming GE3151

>>>”%d”%x
15
%d is formatted as decimal integer.
Format sequence in string:
Format sequence can appear anywhere in the string
Example Program:
>>>computers=10
>>>’I have bought %d computers’, %computers
Output:
I have bought 10 computers
More than one format sequence:
If there is more than one format sequence, second argument must be tuple.
Example Program:
>>>”In %d years, I have bought %g%s”.%(2,3.0,’computers’)
In 2 years, I have bought 3.0 computers
In the above program:
%d is formatted to integer
%g is formatted to floating point number
%s is formatted to string.
Number of elements in tuple and number of format sequences must be same.
5.2 COMMAND LINE ARGUMENTS
Command line arguments are what we type at the command line prompt along with the
script name while we try to execute our script other languages.
Command line argument in python can be processed by using two modules.
i) sys module
ii) argparse module
i) sys module
Sys module is used to access the command line arguments through sys.argv. The sys
module is used for two purposes.
i) sys.argv is a list in Python, which contains the command line arguments passed to the script.

205
Problem Solving and Python Programming GE3151

ii) len(sys.argv) is used to count the number of arguments


There are three steps followed in sys module
i) Import the sys module
ii) We can use sys.argv for getting the list of command line arguments.
iii) Use len(sys.argv) for getting length of command line arguments.
Example Program:
import sys
print ‘No. of arguments:’, len(sys.argv)
print ‘Argument List:’,str(sys.argv)
Run the above script as follows:
$ python test.py arg1 arg2 arg3
Output:
Number of arguments: 4
Argument List: [‘test.py’, ‘arg1’,’arg2’,’arg3’]
ii) argparse module
argparse module is used to access command line arguments. It includes tools for building
command line arguments. There are three steps followed in arg parse module.
i) Import argparse module
ii) Use ArgumentParser for parsing command line arguments
iii) Use parseargs() method to parse command line arguments.
Example Program:
Import argparse
Parser=argparse.ArgumentParser()
Parser.parseargs()
Output:
>>>python cmdline.py –h
Usage:cmdline.py[-h]
Optional arguments
-h,--help show message

206
Problem Solving and Python Programming GE3151

5.3 ERRORS AND EXCEPTIONS


5.3.1 Errors
Errors or mirrors in a program are often referred to as bugs. Error is mistakes in the
program, which are created by fault of the programmer.
Debugging:
Debugging is the process of finding and eliminating errors.

Errors

Syntax error Runtime error Logical error

Missing Division Access Using


Mis Using operator
spelling of colon by zero not
wrong precedence
keyword ,comma defined
variable wrong

Fig: 5.1: Types of errors


Types of errors:
i) Syntax errors
ii) Runtime errors
iii) Logical error
i) Syntax errors
Syntax error occurs when the program is not following the proper structure (syntax).
If syntax errors occur then python display error message and exit without continuing execution
process.

207
Problem Solving and Python Programming GE3151

Some of syntax errors are:


Misspelling keyword
Incorrect indentation
Missing of colon, comma
Leaving a keyword
Putting a keyboard in wrong place
Here are some examples of syntax errors in Python:
a=5
b=20
if a<b
print ‘a is greater’
Error Message:
File “main.py”, line 3
if a<b
^
ii) Runtime errors
Runtime errors occur during execution of program. It is also known as dynamic errors.
Some of runtime errors are:
Division by Zero
Access not defined identifier
Access not defined file
Example:
>>>b= [1,2,3,4]
>>>a
Runtime Error:’a’ is not defined
>>>a=5
>>>b=10
>>>a/b
Runtime Error:’Division by Zero’

208
Problem Solving and Python Programming GE3151

iii) Logical errors


Logical error occurs due to mistake in program’s logic. Here program runs without any
error messages, but produces an incorrect result. These errors are difficult to fix. Here are some
logical errors are:
 Using the wrong variable name
 Indenting a block to the wrong level
Using integer division instead of floating-point division
Using wrong operator precedence
 Making a mistake in a Boolean expression
Off-by-one and other numerical errors
Example:Addition of two numbers
>>>x=10
>>>y=20
>>>z=x-y #Logic error
>>>print z
-10
Here, parentheses are missing. So we get wrong result.
5.3.2 Exceptions
An exception is an error that occurs during execution of a program. It is also called as run
time error. Some examples of Python runtime errors:
division by zero
performing an operation on incompatible types
using an identifier which has not been defined
accessing a list element, dictionary value or object attribute which doesn’t exist
trying to access a file which doesn’t exist
An example for run time error is as follows:
print (10/0)
Error Message:
Traceback (most recent call last):
File “main.py”, line 1, in <module>

209
Problem Solving and Python Programming GE3151

print (10/0)
ZeroDivisionError: integer division or modulo by zero
Exceptions come in different types, and the type is printed as part of the message: the type
in the example is ZeroDivisionError which occurs due to division by 0. The string printed as the
exception type is the name of the built-in exception that occurred. Exception refers to unexpected
condition in a program. The unusual conditions could be faults, causing an error which in turn
causes the program to fail. The error handling mechanism is referred to as exception handling.
Many programming languages like C++, PHP, Java, Python, and many others have built-in support
for exception handling.
Python has many built-in exceptions which forces your program to output an error when
something in it goes wrong. When these exceptions occur, it stops the current process and passes
the control to corresponding exception handler. If not handled, our program will crash.
Some of the standard exceptions available in Python are listed below.
Exception Name Description
Exception Base class for all exceptions
ArithmeticError Base class for all errors that occur for numeric
calculation.
OverflowError Raised when a calculation exceeds maximum limit for
a numeric type.
FloatingPointError Raised when a floating point calculation fails.
ZeroDivisionError Raised when division or modulo by zero takes place
for all numeric types.
AssertionError Raised in case of failure of the Assert statement
EOFError Raised when there is no input from either the
raw_input() or input() function and the end of file is
reached.
ImportError Raised when an import statement fails.
IndexError Raised when an index is not found in a sequence
KeyError Raised when the specified key is not found in the
dictionary.
210
Problem Solving and Python Programming GE3151

NameError Raised when an identifier is not found in the local or


global namespace
IOError Raised when an input/ output operation fails, such as
the print statement or the open() function when trying
to open a file that does not exist.
SyntaxError Raised when there is an error in Python syntax
SystemExit Raised when Python interpreter is quit by using the
sys.exit() function. If not handled in the code, causes
the interpreter to exit
TypeError Raised when an operation or function is attempted that
is invalid for the specified data type
ValueError Raised when the built-in function for a data type has
the valid type of arguments, but the arguments have
invalid values specified.
RuntimeError Raised when a generated error does not fall into any
category

5.4 HANDLING EXCEPTIONS


The simplest way to handle exceptions is with a “try-except” block. Exceptions that are
caught in try blocks are handled in except blocks. If an error is encountered, a try block code
execution is stopped and control transferred down to except block.

Try Raise Except

Exception Raise the Catch if exception


occurs
may occur Exception

Fig 5.2: Exception Handling

211
Problem Solving and Python Programming GE3151

Syntax:
try:
statements
----------------

-----------------

Except exception1:

If exception1 occurs execute it.

Except exception2:

If exception2 occurs execute it.

The try statement works as follows.


i) First, the try block (the statement(s) between the try and except keywords) is
executed.

ii) If no exception occurs, the except block is skipped and execution of the try statement
is finished.

iii) If an exception1 occurs rest of try block is skipped, except block1 gets executed.
iv) If an exception2 occurs rest of try block is skipped, except block2 gets executed.
A simple example to handle divide by zero error is as follows.
(x,y) = (5,0)
try:
z = x/y
except ZeroDivisionError:
print “divide by zero”
Output:
divide by zero
A try statement may have more than one except clause, to specify handlers for different
exceptions. If an exception occurs, Python will check each except clause from the top down to see
if the exception type matches. If none of the except clauses match, the exception will be considered
unhandled, and your program will crash.

212
Problem Solving and Python Programming GE3151

Syntax:
try:
# statements
break
except ErrorName1:
# handler code
except ErrorName2:
# handler code
A simple example to handle multiple exceptions is as follows.
try:
dividend = int(input(“Please enter the dividend: “))
divisor = int(input(“Please enter the divisor: “))
print(“%d / %d = %f” % (dividend, divisor, dividend/divisor))
except ValueError:
print(“The divisor and dividend have to be numbers!”)
except ZeroDivisionError:
print(“The dividend may not be zero!”)
Output (successful):
Please enter the dividend: 12
Please enter the divisor: 2
12 / 2 = 6.000000
Output (unsuccessful-divide by zero error):
Please enter the dividend: 100
Please enter the divisor: 0
The dividend may not be zero!

Output (unsuccessful-value error):


Please enter the dividend: ‘e’
The divisor and dividend have to be numbers!
An except clause may name multiple exceptions as a parenthesized tuple, for example:

213
Problem Solving and Python Programming GE3151

... except (RuntimeError, TypeError, NameError):


...#handlercode
Example:
try:
dividend = int(input(“Please enter the dividend: “))
divisor = int(input(“Please enter the divisor: “))
print(“%d / %d = %f” % (dividend, divisor, dividend/divisor))
except(ValueError, ZeroDivisionError):
print(“Oops, something went wrong!”)
Output:
Please enter the dividend: 110
Please enter the divisor: 0
Oops, something went wrong!
To catch all types of exceptions using single except clause, simply mention except
keyword without specifying error name. It is shown in following example.
try:
dividend = int(input(“Please enter the dividend: “))
divisor = int(input(“Please enter the divisor: “))
print(“%d / %d = %f” % (dividend, divisor, dividend/divisor))
except:
print(“Oops, something went wrong!”)
5.4.1 Raising exceptions
The raise statement initiates a new exception. It allows the programmer to force a specified
exception to occur. The raise statement does two things: it creates an exception object, and
immediately leaves the expected program execution sequence to search the enclosing try
statements for a matching except clause. It is commonly used for raising user defined exceptions.
Syntax of two forms of the raise statement are:
raise ExceptionClass(value)
raise Exception

214
Problem Solving and Python Programming GE3151

Example:
try:
raise NameError
except NameError:
print(‘Error’)
Output:
Error
raise without any arguments is a special use of python syntax. It means get the exception
and re-raise it. The process is called as re-raise. If no expressions are present, raise re-raises the
last exception that was active in the current scope.
Example:
try:
raise NameError
except NameError:
print(‘Error’)
raise
Output:

Error
Traceback (most recent call last):
File “main.py”, line 2, in <module>
raise NameError(‘Hi’)
NameError: Hi
In the example, raise statement inside except clause allows you to re-raise the exception
NameError.
5.4.2 The else and finally statements
Two clauses that can be added optionally to try-except block are else and finally. else
will be executed only if the try clause doesn’t raise an exception.
try:
age = int(input(“Please enter your age: “))
except ValueError:
215
Problem Solving and Python Programming GE3151

print(“Value error occured”)

else:
print(“I see that you are %d years old.” % age)
Output:
Please enter your age:10
I see that you are 10 years old.
Please enter your age:’a’
Value error occured
5.4.3 User-defined exceptions
Python allows the user to create their custom exceptions by creating a new class. This
exception class has to be derived, either directly or indirectly, from Exception class.
# define Python user-defined exceptions
class Error(Exception):
“””Base class for other exceptions”””
pass # null operation
class PosError(Error):
“””Raised when the input value is positive”””
pass
class NegError(Error):
“””Raised when the input value is negative”””
Pass

5. 5 MODULES
Module is a file containing Python definitions and statements. Modules are imported from
other modules using the import command.
i) When module gets imported, Python interpreter searches for module.
ii) If module is found, it is imported.
iii) If module is not found, “module not found” will be displayed.

216
Problem Solving and Python Programming GE3151

Modules

Built-in module User defined modules

random math date time

Fig 5.3: Types of modules


5.5.1 Built-in modules
Built-in modules are predefined modules, which is already in python standard library.
Python have the following built-in modules.
i) random
This module generates random numbers. If we want random integer, we use randint function.
Example:
>>>import random
>>>print random . randint(0,5)
1 (or)2 (or) 3 (or)4 (or)5
ii) math
This module is used for mathematical calculations. If we want to calculate square root, we use
the function sqrt.
Example:
>>>import math
>>>math . sqrt(16)
4

217
Problem Solving and Python Programming GE3151

>>>math . factorial(4)
24
iii) datetime
This module is used to calculate date and time.
Example:
>>>import datetime
>>>datetime . time()
9:15:20
>>>datetime . date()
21.06.2018
5.5.2 User Defined modules
To create module,write one or more functions in file, then save it with .py extentions.
i) Create a file
def add(a,b):
c=a+b
return c
ii) Save it as sum.py
iii) Import module
>>>import sum
>>>print sum.add(10,20)
5.6 PACKAGES
When we have a large number of Python modules, they can be organized into packages
such that similar modules are placed in one package and different modules are placed in different
packages. A package is a tree like hierarchical file directory structure that consists of modules,
sub-packages, sub-sub packages, and so on. In another words, it is a collection of modules. When
a package is imported, Python explores in list of directories on sys.path for the package
subdirectory.
Example:
Assume we are creating a package named Animals with some sub packages as shown in
following.

218
Problem Solving and Python Programming GE3151

Animals

(Package)

_init_.py Mammals Birds

(Module) (Sub-Package) (Sub-Package)

_init_.py _init_.py

(Module) (Module)

create.py create.py

(Module) (Module)

print.py display.py

(Module) (Module)

Fig 5.3: Organization of packages and modules


Steps to create a Python package:
i) Create a directory and name it with a package name.
ii) Keep subdirectories (sub packages) and modules in it.
iii) Create init .py file in the directory
This init .py file can be left empty but we generally place the initialization code with import
statements to import resources from a newly created package. This file is necessary since Python
will know that this directory is a Python package directory other than an ordinary directory.
Method 1:
Consider, we import the display.py module in the above example. It is accomplished by
the following statement.

219
Problem Solving and Python Programming GE3151

Syntax:
import Animals.Birds.display
Now if this display.py module contains a function named displayByName(), we must use
the following statement with full name to reference it.
Syntax:
Animals.Birds.display.displayByName()
Method 2:
On another way, we can import display.py module alone as follows:
Syntax:
from Animals.Birds import display
Then, we can call displayByName() function simply as shown in the following statement:
Syntax:
display.displayByName()
5.7 ILLUSTRATIVE PROGRAMS
5.7.1 Word count
This Program counts the number of words present in a given file.
try:
InFile=open(“test.txt”,’r’)
except IOError:
print “Error:File Not Found”
else:
data=inFile.read()
words=data.split()
print(words)
print “Total number of words are:”,len(words)
Output:
test.txt

I am enjoying python program


[‘I’, ‘am’, ‘enjoying’,’python’,’program’]
Total number of words are:5
220
Problem Solving and Python Programming GE3151

5.7.2 Copy files


To copy files in Python, you have to import copy file from shutil library. The copyfile()
function copies the content of source file into destination file.
Example Program:
from shutil import copyfile
sourcefile=input(“Enter the source file name:”)
destfile=input(“Enter the destination file name:”)
copyfile(sourcefile,destfile)
print(“File copied successfully!)
c=open(destfile,’r’)
print(c.read())
c.close()
Output:
f1.txt
Hello Python
Enter the source file name: f1.txt
Enter the destination file name: f2.txt
File copied successfully!
Hello Python

221
Problem Solving and Python Programming GE3151

PART A (2 Marks with Answers)

1. Define file.
File is the named location on the system which stores data, information or commands for later
access. It stores the information permanently.
2. Define Text File.
Text files are the types of files that store information in the form of readable and printable
characters. They are the persistent storage.
3. What are the basic file operations in python?
Opening a file
Writing to a file.
Reading from a file
Closing a file.
4. What are the different types of files?
i) Data files
ii) Text files
iii) Program files
iv) Directory files
5. Write the syntax for opening and closing a file.
Opening a file: fileobject.open(“filename”,mode)
Closing a file: fileobject.close()
6. Write a python program that writes “Hello world” into a file.
f =open("ex88.txt",'w')
f.write("hello world")
f.close()
7. Write a python program that counts the number of words in a file.
f=open("test.txt","r")
content =f.readline(20)
words =content.split()
print(words)
8. What are the two arguments taken by the open() function?
222
Problem Solving and Python Programming GE3151

The open function takes two arguments: name of the file and the mode of operation.
Example:
f = open("test.txt","w")
9. What is a file object?
A file object allows us to use, access and manipulate all the user accessible files. It
maintains the state about the file it has opened.

10. What is the difference between readline() and readlines() method.


The readline() method reads a single line from a file.
fileobject.readline()
The readlines() method reads all the lines written in a file at a time.
fileobject.readlines()
11. How will you write files?
The write() method is used to write the contents into the file. To write the file contents,
the file must be opened into following mode.
w-writing mode
-appending mode
x-exclusive creation
Syntax:
fileobject . write(string)
12. What is meant by format operator(%)?
Format operator % is used to convert the other values into string.
Example program:
>>>x=15
>>>”%d”%x
15
%d is formatted as decimal integer.
13. Define Command line arguments.
Command line arguments are what we type at the command line prompt along with the
script name while we try to execute our scripts.Command line argument in python can be
processed by using two modules.
223
Problem Solving and Python Programming GE3151

i) sys module
ii) argparse module
14. What is an exception?
Whenever a runtime error occurs, it creates an exception. The program stops execution
and prints an error message.
For example, dividing by zero creates an exception:
print 55/0
ZeroDivisionError: integer division or modulo
15. Define an error. What are its types?
Errors are mistakes in the program, which are created by fault of the programmer. They
are often referred to as bugs.
Types of errors:
iv) Syntax errors
v) Runtime errors
vi) Logical error
16. Define Debugging.
Debugging is the process of finding and eliminating errors.
17. Define Runtime errors.
Runtime errors occur during execution of program. It is also known as dynamic errors.
Some of runtime errors are:
Division by Zero
Access not defined identifier
Access not defined file
18. What are the error messages that are displayed for the following exceptions?
Accessing a non-existent list item
Accessing a key that isn’t in the dictionary
Trying to open a non-existent file
IndexError: list index out of range
KeyError: what
IOError: [Errno 2] No such file or directory: 'filename'

224
Problem Solving and Python Programming GE3151

19. How do you handle the exception inside a program when you try to open a non-existent
file?
filename = raw_input('Enter a file name: ')
try:
f = open (filename, "r")
except IOError:
print 'There is no file named', filename
20. How does try and execute work?
The try statement executes the statements in the first block. If no exception occurs, then
except statement is ignored. If an exception of type IOError occurs, it executes the statements in
the except branch and then continues.
21. What is the function of raise statement? What are its two arguments?
The raise statement is used to raise an exception when the program detects an error. It takes
two arguments: the exception type and specific information about the error.
22. What are modules?
A module is simply a file that defines one or more related functions grouped together. To
reuse the functions of a given module, we need to import the module.
Syntax: import <modulename>
23. What is a package?
Packages are namespaces that contain multiple packages and modules themselves. They are
simply directories.
Syntax: from <mypackage> import <modulename>
24. What is the special file that each package in Python must contain?
Each package in Python must contain a special file called init .py.
25. Write a python program to count number of lines, words and characters in a text file.
def wordCount():
cl=0
cw=0
cc=0
f=open("ex88.txt","r")

225
Problem Solving and Python Programming GE3151

for line in f:
words=line.split()
cl +=1
cw +=len(words)
cc +=len(line)
print('No. of lines:',cl)
print('No. of words:',cw)
print('No. of characters:',cc)
f.close()
26. Write a python script to display the current date and time. ( JANUARY 2018)
>>>import datetime
>>>datetime.time()
9:15:20
>>>datetime.date()
19/5/2018
27. Write a note on modular design. (JANUARY 2018)
A module is simply a file that defines one or more related functions grouped together. To
reuse the functions of a given module, we need to import the module.
Syntax: import <modulename>

28. What is module? Give example. (JANUARY 2019)


Module is a file containing Python definitions and statements. Modules are imported
from other modules using the import command.
Syntax: import <modulename>
Eg. import math
29. Find the syntax error in the code given: (JANUARY 2019)
While True print(‘Hello world’)
Syntax Error: Invalid Syntax
The error is detected at the function print(), since a colon(:) is missing before it.
30. How to use command line arguments in python? (JANUARY 2020)
By using the following system argument
226
Problem Solving and Python Programming GE3151

• Sys.argv
• argparse
• getopt
31. Write methods to rename and delete files. (JANUARY 2020)
Delete - remove()
Rename – rename()

227
Problem Solving and Python Programming GE3151

PART B (Possible Questions)

1. Explain in detail about Text files.


2. Write a Python program to illustrate the use of command-line arguments.
3. How file is opened and closed?
4. Explain the basic operations in manipulating file.
5. How other values are converted into strings? Or Explain in detail about format operator.
6. How exceptions are handled? Explain in detail.
7. Explain in detail about error and Exceptions.
8. Tabulate the different modes of opening a file and explain the same. (16) (JANUARY 2018)
9. i)Appraise the use of try block and except block in python with syntax (6) (JANUARY 2018)
ii) Explain with an example exceptions with arguments in python. (10)
10.i)Explain the commands used to read and write into a file with examples.(8)
ii)Discuss about the use of format operator in file processing.(8) (JANUARY 2019)
11. Describe how exceptions are handled in python with necessary examples.(16)
(JANUARY 2019)
12.i)What are Exceptions? Explain the method to handle them with example.(8)
ii) Write a python program to count the number of words in a text file.(8) (JANUARY 2020)
13.i)How to merge multiple files into a new file using python.
ii)What are modules in python? How will you import them? Explain the concept by
creating and importing a module. (JANUARY 2020)

228
Problem Solving and Python Programming GE3151

PART C (Possible Questions)

1. Write a function that copies a file reading and writing up to 50 characters at a time.
2. Write a Python program to handle multiple exceptions.
3. Write a python program to count number of lines, words and characters in a text file.
4. Write a program to illustrate multiple modules.
5. Write a Python program to append the contents of one file to another file.
6. Write a Python program to count the occurrences of a word in a text file.
7. Write a Python program to count the number of blank spaces in a text file.

229
Problem Solving and Python Programming GE3151

Additional Programs

1. Python program to read the contents of a file.


a=str(input("Enter the name of the file with .txt extension:"))
file2=open(a,'r')
line=file2.readline()
while(line!=""):
print(line)
line=file2.readline()
file2.close()
Output:
Contents of file:
Hello world
Output:
Enter the name of the file with .txt extension: data1.txt
2. Python program to count the number of words in a text file.
fname = input("Enter file name: ")
numwords = 0
with open(fname, 'r') as f:
for line in f:
words = line.split()
numwords += len(words)
print("Number of words:")
print(numwords)
Output:
Contents of file:
Hello world
Output:
Enter file name: data1.txt
Number of words: 2

230
Problem Solving and Python Programming GE3151

3. Python program to count the occurrences of a word in a text file.


fname = input("Enter file name: ")
word=input("Enter word to be searched:")
k=0
with open(fname, 'r') as f:
for line in f:
words = line.split()
for i in words:
if(i==word):
k=k+1
print("Occurrences of the word:")
print(k)
Output:
Contents of file:
hello world hello
hello
Output:
Enter file name: test.txt
Enter word to be searched:hello
Occurrences of the word:3
4. Python program to append the contents of one file to another file.
name1 = input("Enter file to be read from: ")
name2 = input("Enter file to be appended to: ")
fin = open(name1, "r")
data2 = fin.read()
fin.close()
fout = open(name2, "a")
fout.write(data2)
fout.close()
Output:

231
Problem Solving and Python Programming GE3151

Output:
Enter file to be read from: test.txt
Enter file to be appended to: test1.txt
Contents of file test.txt:
Appending!!
Contents of file test1.txt (before appending):
Original
Contents of file test1.txt (after appending):
Original Appending!!
5. Python program to count the number of blank spaces in a text file.
fname = input("Enter file name: ")
k=0
with open(fname, 'r') as f:
for line in f:
words = line.split()
for i in words:
for letter in i:
if(letter.isspace):
k=k+1
print("Occurrences of blank spaces:")
print(k)
Contents of file:
he l l o world hello
Output:
Output:
Enter file name: read.txt
Occurrences of blank spaces:5
6. Python program to read a file and capitalize the first letter of every word in the file.
fname = input("Enter file name: ")
with open(fname, 'r') as f:

232
Problem Solving and Python Programming GE3151

for line in f:
l=line.title()
print(l)
Output:
Contents of file:
hello world
hello
Output:
Enter file name: read.txt
Hello World
Hello
7. Python program to read the contents of a file in reverse order.
filename=input("Enter file name: ")
for line in reversed(list(open(filename))):
print(line.rstrip())
Output:
Contents of file:
hello world
hello
Output:
Enter file name: read.txt
hello
hello word

233
Problem Solving and Python Programming GE3151

234
Problem Solving and Python Programming GE3151

ANNA UNIVERSITY
MODEL
QUESTION PAPERS

235
Problem Solving and Python Programming GE3151

236
Problem Solving and Python Programming GE3151

MODEL QUESTION PAPER –I


(Regulation 2017)
First Semester
Common to All Branches
GE 8151 - PROBLEM SOLVING AND PYTHON PROGRAMMING
Time: 3 Hours Maximum Marks: 100
Answers all Questions
PART – A (10x2=20)
1. Define algorithm.
2. Differentiate pseudo code and flowchart.
3. What is Python?
4. Define keyword? List out any four of the same.
5. Write a program to calculate area and perimeter of circle using function.
6. Is string is mutable or immutable? Justify.
7. Define list and tuples with declarations.
8. Explain various dictionary operations.
9. Explain various modes of file opening.
10. Define exception handling.
PART –B (5 x13=65)
11.a. Explain the basic symbols for constructing a flowchart & discuss about the basic guidelines
for preparing flowchart.(13)
OR
b. i) Write an algorithm to sort a list of numbers in ascending order. (6)
ii) Write a pseudocode to find the sum of the digits of a positive number. (7)
12.a. Briefly discuss about the fundamental of Python.(13)
OR
b. Explain the different types of operators with example. (13)
13.a.i) Explain the type of function arguments in Python.(8)
ii) Write a Python program using function to check given number is odd or even. (5)
OR

237
Problem Solving and Python Programming GE3151

b. Briefly discuss about the types of decision making statements. (13)


14. a.What is Python list? Explain the basic list operations with suitable examples.(13)
OR
b.i) Write a Python program to multiply two matrices.(7)
ii) Write a Python program to concatenate two lists.(6)
15. a. Describe in detail about exception handing with necessary examples.(13)
OR
b. i) Write a program to generate Armstrong numbers between two limits.(9)
ii) Write a program to assess if a file closed or not. (4)
PART – C (1x15=15)
16. a. Create a list of six elements. Pass the list to a function and compute the average of six
numbers. (15)
OR
b. Write a program to illustrate multiple modules. (15)

238
Problem Solving and Python Programming GE3151

MODEL QUESTION PAPER –II


(Regulation 2017)
First Semester
Common to All Branches
GE8151 - PROBLEM SOLVING AND PYTHON PROGRAMMING
Time: 3 Hours Maximum Marks: 100
Answers all Questions
PART – A (10x2=20)
1. Define programming language.
2. What are the limitations of using flowchart?
3. Write an algorithm for computing greatest of three numbers.
4. Define variable? How will you declare a variable?
5. Write a program to swap the contents of two variable with and without using third
variable.
6. Differentiate break and continue.
7. Differentiate list and string.
8. How will you declare used-defined exception?
9. Write a Python script to display current date and time.
10. Explain the syntax for opening a file.
PART –B (5 x13=65)
11.a What is pseudocode? Explain how it can be designed and write the benefits and
limitations.(13)
OR
b. i) Discuss briefly about the simple strategies for developing an algorithm. (13)
12. a. Write a program to perform addition, subtraction, multiplication, integer division, modulo
division, floor division on two values. (13)
OR
b. Define operator. Explain the different types of operators with example. (13)
13. a. Briefly discuss about the looping techniques in Python with suitable examples.(13)

239
Problem Solving and Python Programming GE3151

OR
b. Define recursion. Write a Program for finding factorial of given number. (13)
14. a. Define list. Explain the various techniques to slice the list. (13)
OR
b.i) Define dictionary and its operation in detail.(7)
ii) Explain about the different types of arguments in detail. (6)
15. a .i)Explain in detail about how to read contents from file with example.(6)
ii) Explain in detail about package concepts in python with example. (7)
OR
b. i) Define exception handling? Explain user defined exception handling in detail.(6)
ii) Write a program to count the occurrence of all letters in file. (7)

PART –C (1 x15=15)
16. a. Summarize the difference between algorithm, flowchart and pseudo code.(15)
OR
b. Do the Case study and perform the following operation in tuples i) Maxima ii) minima iii)
sum of two tuples iv) duplicate a tuple v) slicing operator vi) obtaining a list from a tuple
vii) Compare two tuples viii) printing two tuples of different data types.(15)

240
Problem Solving and Python Programming GE3151

MODEL QUESTION PAPER –III


B.E./B.Tech. DEGREE EXAMINATION, January 2018
First Semester
Civil Engineering
GE8151 - PROBLEM SOLVING AND PYTHON PROGRAMMING
(Common to All Branches)
(Regulations 2017)
Time: Three Hours Maximum: 100 Marks

Answer all questions


PART – A (10×2=20 Marks)

1. What is an algorithm?
2. Write a pseudo-code to accept two numbers, add the numbers and print the result.
3. Outline the modes Python interpreter works.
4. State the difference between (I) and (II) operators in Python.
5. Write a Python program to accept two numbers, find the greatest and print the result.
6. What is recursion?
7. What is a list in Python? Give example.
8. Write the syntax for concatenating two lists in Python.
9. What is an exception? Give example.
10. Write the syntax for opening a file in Python for reading only.

PART – B (5×16=80 Marks)

11. a) i) Explain with an example the building blocks of an algorithm. (8)


ii) Draw a flow chart to print the first ‘n’ prime numbers. (8)
(OR)
b) Explain with relevant diagrams and algorithm the Towers of Hanoi problem. (16)
12. a i) Explain with an example the structure of a Python program. (8)
ii) Outline with an example the assignment operators supported in Python. (8)
(OR)
241
Problem Solving and Python Programming GE3151

b) Explain the various data types in Python. (16)


13. a) i) Write a Python program using while loop to print the first n numbers divisible by 5. (8)
ii) Write a Python program to compute the factorial of a given number. (8)
(OR)
b) Write Python program to perform binary search. (16)
14. a) Write code snippets in Python to perform the following :
i) Accessing elements of a tuple. (5)
ii) Modifying elements of a tuple. (5)
iii) Deleting elements of a tuple. (6)
(OR)
b) Write the Python program to sort an integer list using selection sort. (16)
15. a) Describe in detail how exceptions are handled in Python. Give relevant examples. (16)
(OR)
b) Write a Python program to copy the contents of one file to another. (16)

242
Problem Solving and Python Programming GE3151

Question Paper Code: 54009

B.E./B.Tech. DEGREE EXAMINATION, JANUARY 2018


First Semester
Civil Engineering
GE8151 - PROBLEM SOLVING AND PYTHON PROGRAMMING
(Common to All Branches)
(Regulations 2017)
Time: Three Hours Maximum: 100 Marks

Answer all questions


PART – A (10×2=20 Marks)

1. What is an algorithm?
2. Write an algorithm to accept two numbers, compute the sum and print the result.
3. Name the four types of scalar objects Python has.
4. What is a tuple? How literals of type tuple are written? Give example.
5. Write a Python program to accept two numbers, multiply them and print the result.
6. Write a Python program to accept two numbers, find the greatest and print the result.
7. What is a list? How lists differ from tuples?
8. How to slice a list in Python?
9. Write a Python script to display the current date and time.
10. Write a note on modular design.

PART – B (5×16=80 Marks)

11. a) i) Draw a flow chart to accept three distinct numbers, find the greatest and print the result.
(8)
ii) Draw a flow chart to find the sum of the series 1 + 2+ 3+4+5+….+100. (8)
(OR)
b) Outline the Towers of Hanoi problem. Suggest a solution to the Towers of Hanoi problem
with relevant diagrams. (16)
243
Problem Solving and Python Programming GE3151

12. a i) What is a numeric literal? Give examples. (4)


ii) Appraise the arithmetic operators in Python with an example. (12)
(OR)
b)i) Outline the operator precedence of arithmetic operators in Python. (6)
ii) Write a Python program to exchange the value of two variables. (4)
iii) Write a Python program using function to find the sum of first ‘n’ even numbers and .
print the result (6)
13. a) i) Appraise with an example nested if and elif header in Python. (8)
ii) Explain with an example while loop, break statement and continue statement in Python.
(8)
(OR)
b)i) Write Python program to find the factorial of a given number without recursion and with
recursion. (8)
ii) Write a Python program to generate first ‘N’ Fibonacci numbers. (8)
Note : The Fibonacci numbers are 0,1,1,2,3,5,8,13,21,34,….where each number is
the sum of the preceding two.
14. a)i) What is a dictionary in Python? Give example. (4)
ii) Appraise the operations for dynamically manipulating dictionaries. (12)

(OR)
b) i) Write the Python program to perform linear search on a list. (8)
ii) Write a Python program to store ‘n’ numbers in a list and sort the list using
selection sort. (8)
15. a) Tabulate the different modes for opening a file and explain the same. (16)
(OR)
b)i) Appraise the use of try block and except block in Python with syntax. (6)
ii) Explain with an example exceptions with arguments in Python. (10)

244
Problem Solving and Python Programming GE3151

Question Paper Code: 25109

B.E./B.Tech. DEGREE EXAMINATION, Dec/Jan 2019


First Semester
Civil Engineering
GE8151 - PROBLEM SOLVING AND PYTHON PROGRAMMING
(Common to All Branches)
(Regulations 2017)
Time: Three Hours Maximum: 100 Marks

Answer all questions


Part A (10*2=20 Marks)
1. Distinguish between algorithm and program.
2. Write an algorithm to find minimum number in a given list of numbers.
3. What are keywords? Give example.
4. State the reason to divide programs into functions.
5. Present the flow of execution for a while statement.
6. Define recursion with example.
7.Relate Strings and Lists.
8. Give a function that can take a value and return the first key mapping to that value in a
dictionary
9. What is module? Give example.
10. Find the syntax error in the code given:
While True print(‘Hello world’)

PART B (5*16= 80 Marks)


11. a. i) Discuss about the building blocks of algorithms. (8)
ii) Write a recursive algorithm to solve towers of Hanoi problem. (8)
(OR)
b. i) Identify the simple strategies for developing an algorithm. (8)

245
Problem Solving and Python Programming GE3151

ii)Write an algorithm to insert a card into a list of sorted cards. (8)

12. a. i)Sketch the structure of interpreter and compiler. Detail the difference between them.
Explain how python works in interactive mode and script mode with example. (2+2+4)
ii)Summarize the precedence of mathematical operators in python (8)
(OR)
b.i)Explain the syntax and structure of user defined functions in python with examples. Also
discuss about parameter passing in functions. (12)
ii)Write a python function to swap the values of two variables (4)

13. a) List the three types of conditional statements and explain them (16)
(OR)
b. i)Python strings are immutable, Justify with an example (8)
ii)Write a python code to perform binary search. Trace it with an example of your choice.
14. a.i)Discuss the different options to traverse a list (8)
ii)Demonstrate the working of +,* and slice operators in python (8)
(OR)
b.i)Compare and contrast tuples and list in python (4)
ii)Write a script in python to sort n number using selection sort (12)

15. a.i)Explain the commands used to read and write into a file with examples (8)
ii)Discuss about the use of format operator in file processing (8)

(OR)
b) Describe how exceptions are handled in python with necessary examples (16)

246
Problem Solving and Python Programming GE3151

Question Paper Code: 90277

B.E./B.Tech. DEGREE EXAMINATION, NOV/DEC 2019


First Semester
Civil Engineering
GE8151 - PROBLEM SOLVING AND PYTHON PROGRAMMING
(Common to All Branches)
(Regulations 2017)
Time: Three Hours Maximum: 100 Marks

Answer all questions


Part A (10*2=20 Marks)
1. How will you analyze the efficiency of an algorithm.
2. What is the use of Algorithm, Flowchart and Pseudo code in the perspective of problem
solving.
3. Compare interpreter and compiler. What type of translator is used for python?
4. Write a python program to print sum of cubes of the values of n variables.
5. Do Loop statements have else clause? When will it be executed?
6. Write a program to display a set of strings using range() function.
7.How will you update list items? Give an example.
8. Can function return tuples? If yes give example.
9. How to use command line arguments in python?
10. Write method t rename and delete files.
PART B (5*16= 80 Marks)
11.a) i) What is Programming language? What are its types? Explain them in detail with their
advantages and disadvantages(8)
ii) Write a function find_index, which returns the index of a number in the Fibonacci sequence,
if the number is an element of this sequence and return -1 if the number is not contained in it,
call this function using user input and display the result.(8)
OR

247
Problem Solving and Python Programming GE3151

b). i) What is recursive function? What are its advantages and disadvantages? Compare it
with iterative function.(6)
ii) Implement a recursive function in python for the sieve of Eratosthenes. The sieve of
Eratosthenes is a simple algorithm for finding all prime numbers up to a specified integer.
It was created by the ancient Greek mathematician Eratosthenes. The algorithm to find all
prime numbers less than or equal to a given integer n:
1) Create a list of integers from two to n:2,3,4,….n
2) Start with a counter i set to 2. (i.e)the first prime number
3) Starting from i+1,count up by I and remove those numbers from the
list,(i.e)2*I,3*I,4*i….
4) Find the first number of the list following i. This is the next prime number
5)Set I to the number found in the previous step
6) Repeat steps 3 and 4 until I is greater than n.
7) All the numbers, which are still in the list are prime numbers (10)

12. a.i)Write a python program to rotate a list by right n times with and without slicing
techniques(4+4)
ii)Discuss about keyword arguments and default arguments in python with examples(4+4)
OR
b)i)Write a python program print the maximum among ‘n’ randomly generate ‘d’ numbers
by storing them in a list(10)
ii)Evaluate the following expression in python
(i)24//6%3
(ii)float(4+int(2.39)%2)
(iii)2 **2**3 (6)
13.a.i)If you are given three sticks, you may or may not be able to arrange them in a triangle. For
example, if one of the sticks is 12 inches long and the other two are one inch long, you will not be
able to get the short sticks to meet in the middle. For any three length, there is a simple test to see
if it is possible to form a triangle: If any of three lengths is greater than the sum of the other two,
then you cannot form a triangle. Otherwise ,you can.
248
Problem Solving and Python Programming GE3151

i) Write a function named is – triangle that takes three integers as arguments, and that prints
either “yes” or “no”, depending on whether you can or cannot form a triangle from sticks with the
given lengths. (4)
ii) Write a function that prompts the user to input three stick lengths, converts them to integers,
and uses is – triangle to check whether sticks with the given lengths can form a triangle
(4).
iii) Write a python program to generate all permutations of a given string using built-in
functions. (8)
OR
b.i)Compare list and array with example.Can list be considered as an array?justify (6)
ii)Write a python function are Anagram1() to check whether two strings are anagram of each
other or not using built-in functionand are Anagram2() to check the anagram without using built-
in function. (10)
14.a.i) Define Dictionary in Python. Do the following operations on dictionaries.(10)
i) Initialize two dictionaries and create a new dictionary with key value pairs.
ii) Compare the two dictionaries with master key and print missing keys.
iii)Find keys that are in first and not in second dictionary.
iv) Find same keys in two dictionaries.
v) Merge two dictionaries and create a new dictionary using a single expression.
ii)What is list comprehension in python? Explain with example. (6)
OR
b.i)What is tuple in python? How does it differ from list?(8)
ii)Write a python program t sort n numbers using merge sort.(8)
15.a.i)What are Exceptions? Explain the method to handle them with example.(8)
ii) Write a python program to count the number of words in a text file.(8)
b.i)How to merge multiple files into a new file using python.(6)
ii)What are modules in python? How will you import them? Explain the concept by
creating and importing a module. (10)

249
Problem Solving and Python Programming GE3151

REFERENCES
TEXT BOOKS:
1. Allen B. Downey, ``Think Python: How to Think Like a Computer Scientist’’, 2nd edition,
Updated for Python 3, Shroff/O’Reilly Publishers, 2016 (http://greenteapress.com/wp/think-
python/)
2. Guido van Rossum and Fred L. Drake Jr, “An Introduction to Python – Revised and
updated for Python 3.2, Network Theory Ltd., 2011.
REFERENCES:
1. Charles Dierbach, “Introduction to Computer Science using Python: A Computational
Problem-Solving Focus, Wiley India Edition, 2013.
2. John V Guttag, “Introduction to Computation and Programming Using Python’’, Revised
and expanded Edition, MIT Press , 2013
3. Kenneth A. Lambert, “Fundamentals of Python: First Programs”, CENGAGE Learning,
2012.
4. Paul Gries, Jennifer Campbell and Jason Montojo, “Practical Programming: An Introduction
to Computer Science using Python 3”, Second edition, Pragmatic Programmers,LLC,2013.
5. Robert Sedgewick, Kevin Wayne, Robert Dondero, “Introduction to Programming in
Python: An Inter-disciplinary Approach, Pearson India Education Services Pvt. Ltd., 2016.
6. Timothy A. Budd, “Exploring Python”, Mc-Graw Hill Education (India) Private Ltd.,, 2015.

250

You might also like