Introduction To Computing and Problem Solving Using Python (AKUMA)
Introduction To Computing and Problem Solving Using Python (AKUMA)
● Fundamentals of Computers
● Numerical Methods
● Reliability Engineering
A recipient of numerous honors and awards, he has been listed in the Directory of Who’s Who of
Intellectuals and in the Directory of Distinguished Leaders in Education.
INTRODUCTION TO COMPUTING AND PROBLEM
SOLVING USING PYTHON
E Balagurusamy
Chairman
EBG Foundation
Coimbatore
Copyright © 2016 by McGraw Hill Education (India) Private Limited. No part of this publication may be reproduced or distributed in
any form or by any means, electronic, mechanical, photocopying, recording, or otherwise or stored in a database or retrieval system
without the prior written permission of the publishers. The program listings (if any) may be entered, stored and executed in a computer
system, but they may not be reproduced for publication.
Print Edition:
ISBN-13: 978-93-5260-258-2
ISBN-10: 93-5260-258-7
Information contained in this work has been obtained by McGraw Hill Education (India), from sources believed to be reliable. However,
neither McGraw Hill Education (India) nor its authors guarantee the accuracy or completeness of any information published herein,
and neither McGraw Hill Education (India) nor its authors shall be responsible for any errors, omissions, or damages arising out
of use of this information. This work is published with the understanding that McGraw Hill Education (India) and its authors are
supplying information but are not attempting to render engineering or other professional services. If such services are required, the
assistance of an appropriate professional should be sought.
Typeset at The Composers, 260, C.A. Apt., Paschim Vihar, New Delhi 110 063 and printed at
Cover Printer:
Preface ix
Acknowledgements xiii
Chapter 4 Functions 82
4.1 Introduction 82
4.2 Built-in Functions 82
4.3 Composition of Functions 88
4.4 User Defined Functions 89
4.5 Parameters and Arguments 92
4.6 Function Calls 96
4.7 The return Statement 97
4.8 Python Recursive Function 98
4.9 The Anonymous Functions 98
4.10 Writing Python Scripts 100
Always Remember 102
Key Terms 103
Review Exercises 104
Multiple Choice Questions 109
Short Questions 110
Answers to Multiple Choice Questions 111
Contents vii
Developments in the field of digital electronics and the huge amount of data generated during the last
few decades ushered in the second Industrial Revolution which is popularly referred to as the Information
Revolution. Information technology played an ever-increasing role in this new revolution. A sound knowledge
of how computers work, process and analyze data has, therefore, become indispensable for everyone who
seeks employment not only in the area of IT, but also in any other fields. Rightly so, many institutions and
universities in India have introduced a subject covering the fundamentals of computation and problem solving
with Python for their undergraduate students. This book caters to those needs of the undergraduate students.
Web Supplements
The web supplements can be accessed at <http://highered.mheducation.com/sites/9352602587> which
contains the following:
● Solution Manual
● Lecture PPTs covering
1. Important standard library
(a) argparse
(b) csv
(c) math
(d) os
(e) pickle
(f) random
(g) subprocess
2. How to install third party libraries
(a) Using pip
(i) Installing pip under Windows and Linux
(ii) Using pip to install a package
(b) Installing packages from source.
Preface xi
A note of acknowledgement is due to the following reviewers of the book for their valuable suggestions:
Sujith Kumar
Sree Narayana Gurukulam College of Engineering, Kolenchery, Kerala
Jini Raju
Thangal Kunju Musaliar College of Engineering, Kollam, Kerala
Sanjiv Singh
Impetus Technologies, Noida, Uttar Pradesh
Aswathy Ravikumar
Mar Baselios College of Engineering and Technology, Thiruvananthapuram, Kerala
Pawan Kumar
Mphasis, Noida, Uttar Pradesh
A token of special appreciation to Mr. Jayarajan J N (Rajagiri School of Engineering and Technology,
Cochin) for his valuable contribution in development of this book.
Publisher’s Note
Remember to write to us. We look forward to receiving your feedback, comments, and ideas to enhance
the quality of this book. You can reach us at info.india@mheducation.com. Please mention the title and
authors’ name as the subject. In case you spot piracy of this book, please do let us know.
INTRODUCTION TO
1 DIGITAL COMPUTER
1.1 INTRODUCTION
In earlier days, the term “digital computer” was used to refer a person who drew mathematical tables and
solved complex calculations. In less than a human lifetime, computers have changed from massive, expensive
and unreliable calculators to the dependable and versatile machines that are now omnipresent in society.
Computers were once the size of rooms and used to take a day to change the program and now, it is just a
double click away. Computers help the impossible become possible. They have become a necessary tool in
today’s society. Without computers, it is hard to do pretty much anything. Computers process information in
1’s and 0’s (usually referred to as On and Off respectively). This operation identifies instructions in Binary
Code. This is the language understood by the computer to complete a command. By 1953, it was estimated
that there were almost 100 computers in the world.
It is believed that the first computer was invented in Berlin, Germany, in 1936.
● The Z1 was invented in 1936 by Konrad Zuse in Germany. This was a programmable machine that
1944. It was a large calculator. This computer was able to calculate many different types of numbers.
● With the advancement of technology and research, major companies like IBM, Apple, and Intel have
contributed to the explosion of the personal computers as we know today. For example, Apple 1 was
released in 1976 which was having memory of 4 KB expandable to 8 KB. The Macintosh was released
in 1984 which was having memory of 64 KB expandable to 256 KB.
● CSIRAC was the first computer to play digital music in 1949.
● UNIVAC 1 was used by CBS to predict the results of the 1952 presidential elections in USA.
● COBOL (Common Business Oriented Language), one of the oldest programming languages, was
● Single - board computer known as apple -1 was designed by Steve Wozniak some more important
developments and was marketed by his friend Steve Jobs.
● In 1980 IBM introduced its Personal Computers (PC). The first IBM PC was known as IBM Model
window's NT
● In 1994 Sony entred the home gaming market with release of play station console.
A Personal Computer (PC) is a digital computer designed for the usage by one person at a time. PCs
can be classified into desktop computers, workstations and laptop computers. Today, PCs have five major
applications which are as follows:
1. Internet Browser: Internet browser is a software application used to access the Internet. For example,
Internet Explorer, Firefox, Opera, etc., are all Internet browsers.
2. Data Compression Software: Data compression software is used to reduce file size. ZIP is widely used
as the data compression software on personal computers.
3. Windows Media Player: Windows Media Player is used to create music libraries for listening music.
4. Image Editing Software: Image editing software is used to develop good quality pictures. Examples of
such software include Photoshop, Microsoft Publisher and Picasa.
5. Audio Editing Software: Audio editing software is used to edit audio files and also to add audio effects.
Note The first personal computer was Altair 8800. Later IBM introduced IBM PC.
Computers have become an integral part of the society because of the following characteristics they
possess:
● A computer can perform millions of calculations in a second.
● A computer can store billions of bytes of information. For example, the capacity of a terabyte =
2,00,000 songs.
● A computer can work continuously without getting tired.
execution. The information can be stored by using compact disk (CD), floppy, etc.
2. Data or programs are stored into the main memory.
3. Processing of instructions is sequential.
Note A process describes how the processor takes the data or program, decodes it and
finally executes it. The fetch-decode-execute cycle is also known as the Von Neumann
execution cycle.
1. Processor: It is also known as the Central Processing Unit (CPU). The processor is the brain of the
computer. It takes data in the form of input and processes this input using arithmetic or logical operations in
the ALU, thereby transforming it into the output.
2. Memory (Storage): Memory refers to the data storage, permanent or temporary. Computer memory
understands only two bits, 0 and 1. The temporary memory is called RAM and the permanent memory is
called Read Only Memory (ROM).
3. Input/Output: It refers to the communication mechanism. Input and output devices are significant portions
of the computer accessories. Input devices provide data to the computer as input from the external source
while output devices generate information for the user after processing the input.
Storage
TIP
Before buying a computer, one should check the processor speed. To determine the processing
speed of the CPU, the clock speed is checked. The CPU can perform a certain number of
clock cycles per second. The computer’s clock speed is measured in gigahertz (GHz). One
GHz equals to one billion cycles per second. A higher clock speed indicates that the CPU
can execute more operations per second.
Note The very first commercially produced and sold computer in 1951 was UNIVAC.
● Arithmetic Logic Unit (ALU): The ALU performs both arithmetic and logical operations including
addition, subtraction, division and bits manipulation.
● Registers: Registers hold values in the CPU. Each register has a unique name and is capable of
holding a byte or word of data.
● Control Unit: The Control Unit controls the operation of the CPU, the Memory and the input-output
components based on a sequence of instructions in the Memory.
4. External Memory: The External Memory is a physical device used to store programs (set of instructions)
or data temporarily or permanently for use in a computer or some other digital electronic device. It is
classified into two categories which are as follows:
● Primary Memory: The primary memory is also known as main memory. The program is loaded in
the main memory before it can be executed. The information within the Primary Memory can be lost
when power to the computer is turned off. Thus, the Primary Memory is volatile by nature.
● Secondary Memory: The secondary memory is a non-volatile, low-speed memory. The information
within this memory will not be lost even if the computer is turned off due to power failure. Examples
of secondary storage include hard disk, DVD, floppy drive, etc.
5. Bus: In a computer, all the components described above are connected by cables and each cable can only
send one bit at a time. These cables are called bus and are responsible for the movement of data from input
devices to output devices.
Keyboard
ALU
Display
Registers Secondary
Memory
Printer
Storage Output
Devices
Central Processing Unit Bus
(CPU)
Computers have become a huge part of our life nowadays. We use them every day to complete different
tasks. They are basically composed of two main things-the software and the hardware. The software has all
the instructions and information needed for the computer to run. This includes the operating system and the
programs or applications. The hardware consists of all the physical elements that make the computer work.
This includes the CPU, RAM, ROM, Cache etc.
6 Introduction to Computing & Problem Solving using Python
Let us imagine a restaurant. Every day a keeper comes to open the restaurant and makes sure everything is
ready and working well. Here, the keeper and the computer is called read-only memory or ROM which can
be modified. To keep everything running properly in a restaurant we need an administrator, this is the central
processing unit or CPU. It is called a microprocessor in cell phones and it contains the arithmetic logic unit
or ALU and the control unit or CU. The ALU in a computer is the manager who takes care of the numbers
and logical part. The control unit is the head chef who organises the incoming information and gets everyone
task. Let us see a customer making an order. The order acts as the input data. The waiter or data bus then
carries this information to the kitchen, and then goes to the head chef who decides where it should go further.
The kitchen represents the mother board inside, where there is a fridge and you keep everything that is used
frequently for easy access. This is called random access memory or RAM in a computer. Cache will be like
a small recipe book in which the computer keeps the frequently used instructions. There is also a warehouse
for rest of the information stored and this works as a hard disk. We can also get the things delivered through
the back door which acts as an optical disc in the computer. These are called the secondary storage devices.
Let us imagine, we also have a timer in the kitchen. Every time the timer starts, everyone starts preparing
a dish and has to get it done by the time gets over, so this keeps everything synchronised. In a computer, it
is called the internal clock.
We get an order, the buses carry it and it goes through the control unit in the CPU which supervises that
it reaches the right destination. If we need something that has been recently used, we can easily get it from
RAM, and if not, then the computer has to look for it in the secondary storage devices. The data is processed
now, and it is time for the chefs to turn into some delicious food that we can eat. This is the task of the video
card converting data into images. This is how our computer works.
1.3 STORAGE
The term Storage refers to memory that retains computer programs and data. There are basically two
categories of storage: primary and secondary.
2. ROM (Read Only Memory): The Read Only Memory gets its name from the fact that the computer can
only read information from it but cannot write any information on it. A part of the operating system is
stored in ROM. When the computer system is turned on, the CPU executes instructions stored in ROM.
The information stored in ROM cannot be changed and will not be lost even if the computer is turned off.
3. Cache Memory: Cache memory stores the data recently processed by the CPU. The size of cache is very
small and execution is very fast. In order to process an application, processor first searches the cache memory
and then, the RAM.
3. Flash Drive: A flash drive can be inserted into a USB port for data retrieval and data storage. It is small
in size and portable. Nowadays, flash drive comes in many shapes.
4. Memory Card: A memory card is a very small data storage medium. It is portable and can be used in
remote computing devices.
5. Compact Disc: A compact disc is a kind of optical disc used to store digital data. Data can be accessed
faster here compared to the floppy discs, but it is still slower than the hard discs. A compact disc stores the
same data as a floppy disc does.
Note An early method used to store data or information in the computer was the Punch
card. The machine Analytical Engine invented by Charles Babbage had a punched card
system to store and retrieve information.
1.3.3 Register
It contains the address of the memory location where data resides. Register is highly accessible by the CPU.
Speed of the CPU is determined by the number of registers it has.
Memory hierarchy is the arrangement of the storage in a computer. Each level of memory hierarchy is
distinguished by the response time. It is illustrated in Figure 1.10.
Cache
Main Memory
Disk/Virtual Memory
Programming Languages
Machine Assembly
Language Language
TIP
If you want to learn programming languages, first choose a language that you want to
learn. After that, you need to learn the core concepts of that language. Install the software
that is required to compile the program. Now, create your first program.
1.5 TRANSLATORS
A translator is a computer program that can instantly translate between any languages. It converts program
language to machine level language for the debugging and execution of the programs. While the computer
understands only binary code i.e. 1’s and 0’s, it is not easy for humans to read and write in such code. So,
the translators are used to translate a computer program into binary code. There are three types of translator
programs, namely Compiler, Assembler, and Interpreter.
1.5.1 Compiler
A compiler is very important in giving the application a performance boost. The compiler of a language is
a computer program that converts the source code of an application written in the computer programming
language to the target language with its binary form.
The compiler checks for syntax errors in a source code of a program. If no error is found, the program
is declared to be successfully compiled. If the program does not contain any syntax error, the compiler
translates the source code of the program into the machine language of the computer, so that the computer
is able to understand the instructions given to it.
Source files are the program files created by a programmer. They contain information and instructions
written by the programmer, which are checked by the compiler during the process of compilation. These
source files are compiled by a compiler and run with an executable file.
1.5.2 Assembler
To translate the assembly language into machine language, a translator is needed. This translator is also
called an assembler. Each assembly language is unique to the particular computer architecture. In assembly
language, we use some mnemonic such as ‘add’, ‘sub’, ‘mul’ etc. for all the operations.
For example, if we want to add 4 and 3, then in assembly language, we will write Add 4 3 where Add
is a mnemonic and both 4 and 3 are the arguments of the operand. Now, the assembler will map this to the
binary code.
Introduction to Digital Computer 13
1.5.3 Interpreter
Like a compiler, an interpreter also translates high-level language into low-level machine language. An
interpreter reads the statement and first converts it into an intermediate code and executes it, before reading
the next statement. It translates each instruction immediately one by one. This is a rather slow process
because the interpreter has to wait while each instruction is being translated.
The interpreter stops execution at the time of error occurrence and reports it, whereas a compiler reads
the whole program even if it encounters several errors.
1.6.1 Hardware
Hardware are the physical components of the computer system. The hardware components consist of several
parts like input devices, Central Processing Unit (CPU), primary storage, output devices and auxiliary
storage devices.
1. Input Devices: These are the devices such as keyboards that are used to enter the program and data. Mouse
and audio input also fall in the category of input devices.
2. CPU: It processes all the instructions given to the computer and is also used for doing arithmetic
calculations and comparisons, and for controlling the movement of data.
3. Primary Storage: It is the main memory of the computer system. In primary storage, programs and data
are stored temporarily for processing. The data in the primary device is erased when the computer is turned
off.
4. Output Devices: Devices such as monitor or printer are used to get the output.
5. Auxiliary Storage: Programs and data are stored permanently in auxiliary storage. It is also known as
secondary storage and used for both input and output. This storage is very useful as the data remains stored
even when the computer is turned off.
14 Introduction to Computing & Problem Solving using Python
1.6.2 Software
Computer software is a collection of programs used to manage the entire file system of the computer. It is
also necessary for the running of computer hardware. The working of the computer hardware depends on
the computer software. Computer software is classified into two categories, namely, System software and
Application software.
1. System Software: The system software provides interface between the user and the hardware (components
of the computer). It also manages the system resources, enabling the working of all hardware components
(hard disk, RAM, CD drive, etc.) of the computer. Computer hardware resources are managed through this
system software with the help of programs.
These programs fall into following three types:
● Operating System: It provides the interface between the user and computer hardware, managing
all files and folders, and providing ease of access to the database. The operating system makes the
computer perform efficiently.
● System Support Software: It provides all the services of the operating system and system utilities.
For example, disk format program is the system utility made to do the formatting of the storage. Other
services include data encryption and bit lock for locking storage devices.
● System Development Software: It works as a language translator that converts program language to
machine level language for debugging and execution of the programs.
2. Application Software: The application software runs under the system software. It helps the user to solve
problems. It can be further classified into general-purpose software and application-specific software.
● General-Purpose Software: It refers to software meant to be used for more than one application.
For example, Word Processor.
● Application-Specific Software: As the name suggests, it refers to software generally used for
a specific, intended purpose. For example: a general account ledger used by the accountants for
managing accounts.
The examples of application software are as follows:
a) Microsoft Internet Explorer
b) VLC Media Player
c) Adobe Reader X
Note Auxiliary storage is very useful since when the computer is turned off, the data
remains in the secondary storage, ready for the next time we need it.
Operating System
Drives
(C:, D:, E: etc.) Monitor
Keyboard Printers
● The Von Neumann architecture is also known as “stored-program” architecture because in this architecture,
the program data and instruction data are stored in the same memory.
● The basic structure of Von Neumann architecture consists of the memory, the processing unit and the
control unit.
● In the central processing unit (CPU) there is a control unit that manages the process of data or program.
● Input devices are used to give data to the computer as input from the external source.
● Output devices are used to convey the information after processing to the user.
● Primary storage is also known as temporary storage and is used for storing data and programs temporarily.
● Secondary storage is also known as permanent storage. Examples of secondary storage include the hard
drive, DVD and memory card.
● The computer understands only machine language. All instructions are written in 1s and 0s form.
● When a high-level language is translated into machine language, there are two ways to translate it:
compiled or interpreted.
● Hardware is the physical component of the computer system. It consists of several parts including input
devices, CPU, primary storage, output devices and auxiliary storage devices.
● Computer software is used to manage the entire file system of the computer and is necessary for the
running of computer hardware.
● The operating system can allow users to do multitasking, by allowing two or more than two programs to
be run simultaneously on a single operating system.
● The compiler checks for syntax error in a source code of a program.
● The interpreter stops execution when an error occurs and reports it, whereas a compiler reads the whole
program even if it encounters several errors.
✓ ARITHMETIC LOGIC UNIT (ALU): It is useful in arithmetic and logical calculations, such as addi-
tion, subtraction, division and comparisons.
✓ ASSEMBLER: It translates the assembly language to machine language.
✓ BIT: Bit is the smallest storing space in the computer. In a computer, bit represents two states: either
“on” or “off”. It represents two numerical digits “0” and “1”.
✓ BYTE: A group of 8 bits form a byte. A computer’s capacity is measured in terms of bytes.
✓ BROWSER: A browser is a software used to access the Internet. For example, Internet Explorer, Mozilla,
Opera, etc.
✓ CENTRAL PROCESSING UNIT (CPU): It takes data in the form of input and processes the input by
some arithmetic or logical operations using ALU, transforming the data into output.
✓ COMPUTER: A computer is an electronic device that is able to execute programs written in different
languages.
Introduction to Digital Computer 17
✓ COMPILER: A compiler is a software program that converts high-level language into low-level lan-
guage understood by the processor.
✓ INTERPRETER: Just like a compiler, an interpreter also translates high-level language into low-level
machine language. It translates each instruction immediately one by one.
✓ OPERATING SYSTEM: Operating system works as an interface between the hardware and the user.
✓ PROGRAM: A program, written in programming language, is a set of instructions by which computer
comes to know what is to be done.
✓ STORAGE DEVICE: Storage devices are used to store the digital data and programs which can be ac-
cessed by the computer system.
✓ PRIMARY STORAGE: Primary storage is also known as temporary storage. It is used for storing data
and programs temporarily.
✓ SECONDARY STORAGE: Secondary storage is not constantly accessible by a computer system.
When required, secondary storage devices and media can be accessed by plugged or inserting them into
a computer.
✓ SOFTWARE: A software is a collection of programs. Computer software is used to manage the entire
file system of the computer and is also necessary for the running of computer hardware.
✓ HARDWARE: Hardware is the physical component of the computer system.
Short Questions
1. What is a digital computer? What are the components of digital computer?
2. What are the characteristics of Von Neumann architecture?
3. What is the difference between primary storage and secondary storage?
4. Explain the terms hardware and software.
5. What do you mean by programming languages? What is the difference between machine language,
assembly language and high-level language?
6. What is compiler? How is compiler different from interpreter?
7. What is assembler? What are the differences between compiler and assembler?
8. What is the difference between RAM and ROM?
9. What is an operating system?
20 Introduction to Computing & Problem Solving using Python
not fulfilled. If your goal was to achieve 100% growth but you end up attaining only 70%, this implies that
you have not met the actual standard.
While solving a problem it is acceptable to skip a few steps if these steps are not really important. On
the basis of this key dimension, a problem can be categorised as ignorable, recoverable and irrecoverable.
Note The very first step of writing a program is to understand the problem. In order to
understand the problem, it must be thoroughly analysed.
2.2 ALGORITHMS
In computer science and mathematics, an algorithm is a set of instructions used for solving problems in a
step-by-step manner. This step-by-step explanation of doing something is known as an algorithm.
Problem Solving Strategies 23
TIP
If an algorithm is correctly written, there are very low chances of generating a bad program.
24 Introduction to Computing & Problem Solving using Python
Figure 2.1
2. Input/Output: Every time you take an input from a user and return an output to the user, an input/
output symbol is used in the flow chart. The symbol that is used for both input/output-related actions is a
parallelogram as shown in Fig. 2.2.
Figure 2.2
3. Process: If you are running a processing instruction, you need to use a rectangular box in the flow chart.
This rectangular box, as shown in Fig. 2.3, is used for processing needs.
Figure 2.3
Problem Solving Strategies 25
4. Decision Symbol: In a flow chart, a decision symbol, as shown in Fig. 2.4, is used for answering questions
in the form of either true/false or yes/no. Please note that each answer can lead you to a different path in
the flow chart. A ‘yes’ to a question can take you to one path and a ‘No’ to the same question can generate
a completely new path.
Figure 2.4
5. Flow Lines: Flow lines depict the direction of a flow in a flow chart. There are four types of flow lines.
Flow lines, as shown in Fig. 2.5, can depict a left, right, top or bottom direction.
Figure 2.5
6. Connector: As the name suggests, a connector connects. It connects different steps in a flow chart that are
on different pages and gives a sense of continuation. Generally, it is used in extremely complex flow charts
and it is denoted by a small circle as shown in Fig. 2.6.
Figure 2.6
TIP
To draw a correct flow chart, it is imperative to know the function of each flow chart
symbol.
26 Introduction to Computing & Problem Solving using Python
Start
Yes Is it No
raining?
Stop
Figure 2.7
Start
Is the
No
statement
true?
Yes
Statement will be repeated
Stop
Figure 2.8
Problem Solving Strategies 27
Start
Perform step 1
Perform step 2
Perform step 3
Stop
Figure 2.9
Start
No
Stay at home
Stop
Figure 2.10
● Also, only one flow line should enter a decision symbol. However, two or three flow lines can leave
the same decision symbol. For example, in Fig. 2.10, decision after the question ‘do you have more
than 100 rupees?’ led to two flow lines, each representing a ‘yes’ and a ‘no’, respectively.
● Only one flow line, as shown in Fig. 2.10, is used in conjunction with a terminal symbol.
● It is important to ensure that a flow chart has a logical start and end. A flow chart can have only one
start terminal. However, it can sometimes lead to more than one terminal symbols.
● It is also important to stop a flow chart at a logical conclusion.
Start
Sum = 0, count = 0
Read n
Sum = sum + n
count = count + 1
Is count Yes
< 4?
No
Write sum
Stop
Figure 2.11
30 Introduction to Computing & Problem Solving using Python
Start
Read 5, 6
Mul = 5 * 6
Write mul
Stop
Figure 2.12
Start
Read p, q, r
Yes No
Is p > q?
No No
Is p > r? Is q > r?
Yes Yes
Write p Write r Write q
Stop
Figure 2.13
Problem Solving Strategies 31
Start
Count = 0
Write
Symbol
Count = count + 1
Is count Yes
< 7?
No
Stop
Figure 2.14
Start
Write
www.gmail.com
Write Email Id
and password Error in log in
Email Id and
password you No
entered is
correct?
Yes
Stop
Figure 2.15
32 Introduction to Computing & Problem Solving using Python
Start
Read P, Q
Area = P * Q
Write Area
Stop
Figure 2.16
Start
Sum = 0
c=1
Sum = Sum + c
c=c+1
Is No
c > 50?
Yes
Write sum
Stop
Figure 2.17
Problem Solving Strategies 33
● To analyse a problem, first identify whether the problem is decomposable or not, i.e., it can/cannot be
decomposed into sub-problems.
● A problem can be defined as a gap between the actual and desired conditions.
● The process of developing a solution consists of development of a structure chart, a pseudo code and a
flow chart.
● A structure chart shows a logical breakdown of a program into different steps. Each step has separate
modules that are related to different modules.
● A pseudo code is used to state an algorithm in an English-like syntax.
● An algorithm is a set of instructions used for solving a problem in a step-by-step manner.
● A flow chart is a graphical representation of the logical flow of data.
● A flow chart gives a sequential order of steps that must be followed while designing the whole program.
● A flow chart uses the standard graphical symbols to narrate the sequential processes of a specific module.
● The basic symbols that are used to draw a simple flow chart are as follows:
1. Terminal symbol
2. Process
3. Input/output
4. Decision
5. Flow lines
6. Connector
Short Questions
1. Differentiate between an algorithm and a program?
2. Define a flow chart and list its uses.
3. What are the rules to draw a flow chart?
4. Write an algorithm to make tea.
5. Differentiate between an algorithm and a flow chart?
6. Draw a flow chart to find whether a given number is odd or even.
7. Draw a flow chart to calculate the average of three numbers.
8. What do you mean by problem analysis?
9. What are the methodologies to solve a problem?
10. Briefly describe the basic symbols used to draw a flow chart.
11. Write an algorithm and draw a flow chart to change the temperature from Celsius to Fahrenheit.
12. Write an algorithm to find the area of a circle.
3.1 INTRODUCTION
In the previous chapters, we learnt how programming languages and flow charts work. In this chapter, we
will learn about the basics of Python, including the declaration of variables and the different data types.
We will also learn about the different types of operators supported by Python and the execution of control
statements in this language.
Python is a high-level, interpreted, general-purpose, dynamic programming language. Python was
conceived in the late 1980s and its usage began from December 1989. It is a widely used programming
language. Python possesses a property of code termed reusability. The syntax of Python programs can
express concepts in fewer lines as compared to programs in C, C++ and JAVA.
Python can be used in multiple programming styles, including Object-Oriented, Functional programming
Procedural Programming and Imperative styles. It also supports automatic memory management and has
a large standard library and innumerous set of third party libraries. Python can be used on almost every
operating system because its interpreter is available for many operating systems.
Python is free and open-source software. Open-source software is a kind of computer software in which
the source code of the software is made public, i.e., the copyright holder gives rights to everyone to read,
change and distribute the code for any purpose. It generally has a community-based development.
● Python can be used as a scripting language, as a language for implementing web applications, etc.
● Extending Python with C or C++ can help in the performance of intensive tasks where speed of
● It supports many control statements such as if, if-else, if-elif-else, while, iterative
for, etc.
● It allows for easier programming with the use of functions, classes, modules and packages.
Note Python 2.7.x version of python interpreter is being discussed throughout this book.
Install Python 2.7.x for better results. Many Examples listed in this book may or may not
work under Python 3.x.
Figure 3.1
Now, choose the directory where you want to install Python and click Next> as shown in Fig. 3.2. It is
best to use the default given location.
Figure 3.2
Introduction to Python 39
You will then be asked to select the package. Click Next> as shown in Fig. 3.3.
Figure 3.3
Please note that installation takes some time to complete as indicated in Fig. 3.4.
Figure 3.4
40 Introduction to Computing & Problem Solving using Python
Once the installation process is complete, click on Finish to exit the installer (Fig. 3.5).
Figure 3.5
Python is now installed in your computer’s directory. You need to run Python by following the given steps:
1. Click START button.
2. Go to All Programs.
3. Search for Python 2.7 folder.
4. Click Python (Command line).
This will start the Python Command line.
Once Python starts, you will see the interpreter startup message, indicating version and platform. You
will also be given the python interpreter prompt, i.e., “>>>” which is also known as python chevron
prompt. The “>>>”indicates that Python interpreter is waiting for an expression or command. The interactive
environment where we are interacting with the Python interpreter is called the console or command shell as
shown in Fig. 3.6.
Figure 3.6
Introduction to Python 41
Now, try to interact with the interpreter by entering a simple expression, 8 + 9, on the console. After
entering the expression, press the Enter key to get the result.
>>> 8+9
17 # Output
>>>
The given example shows how Python can also work as a simple calculator.
Now, type the following text at the Python prompts and press Enter.
>>> print “Hello, Python!”
This produces the following result:
Hello, Python! # Output
Now, let us try some more examples.
>>> Hello
After writing Hello, when you hit the Enter key, an error message will be displayed. This is because
Python does not have any Hello command and its interpreter is unable to identify the command.
>>> Hello
Traceback (most recent call last): # Output
File “<pyshell#0>”, line 1, in <module>
Hello
NameError: name ‘hello’ is not defined
However, if you want to display a message on the console, you will need to keep your message within
quotes. This tells the interpreter that the text entered is not a command. Therefore, the interpreter simply
echoes the text.
>>> ‘Hello’
‘Hello’ # Output
Note The print statement is used to display output to the screen. Those of you who are
familiar with C know that the printf() function produces screen output. Many shell script
languages use the echo command for program output.
TIP
The print statement, paired with the string format operator (%), behaves even more like
C’s printf() function.
3.4 COMMENTS
Just like other programming languages, Python allows you to add comments in the code. Comments are used
by the programmer to explain the piece of code to others as well as to himself in a simple language. Every
programming language makes use of some special character for commenting, so does Python.
Python uses the hash character (#) for comments. Putting # before a text ensures that the text will not
be parsed by the interpreter. Comments do not affect the programming part and the Python interpreter does
not display any error message for comments. Comments show up as it is in the programming. It is a good
practice to use comments for program documentation in your program so that it becomes easier for other
programmers to maintain or enhance the program when required.
Now, take a look at some examples of comments used in Python.
Commenting without the use of Hash mark (#)
>>> 8+9 addition
SyntaxError: invalid syntax # Output
>>>
In the above example, ‘addition’ is written without the Hash mark. As a result, the interpreter accepts the
word ‘addition’ as part of programming. Since ‘addition’ is not a command in Python, an error message is
displayed.
Commenting using Hash mark (#)
>>> 8+9 #addition
17 # Output
>>>
Now, in this example, ‘addition’ is written with a Hash mark. Hence, the interpreter understands it as a
comment and does not display any error message.
TABLE 3.1 Examples of Valid and Invalid Names for Creating Identifiers
Examples of Identifiers
Valid Invalid
MyName My Name (Space is not allowed)
My_Name 3dfig (cannot start with a digit)
Your_Name Your#Name (Only alphabetic character, Underscore ( _ ) and numeric are allowed
3.7 VARIABLES
3.7.1 Declaring a Variable
A variable holds a value that may change. The process of writing the variable name is called Declaring the
variable. In Python, variables do not need to be declared explicitly in order to reserve memory spaces as in
other programming languages like C, Java, etc. When we initialize the variable in Python, Python Interpreter
automatically does the declaration process.
The equal sign (=) is known as Assignment operator. An expression is any value, text or arithmetic
expression, whereas variable is the name of the variable. The value of the expression will be stored in
the variable.
Let us now look at an example of initialising a variable:
>>>year=2016
>>> name=’Albert’
The two given statements reserve two memory spaces with variable names year and name.2016 and
Albert, are stored respectively, in these memory spaces as shown in Fig. 3.7.
44 Introduction to Computing & Problem Solving using Python
Memory
Year name
2016 Albert
Figure 3.7
TIP
Whenever you want to display the value of the variables, simply type these variable names
on console.
Note You can also assign one variable value into another variable. Assign the value of
name1 variable into name2 variable.
Let us now look at an example of assigning one variable value into another:
>>> name1=’Albert’
>>> name2=name1
>>> name2
‘Albert’ # Output
>>>
Whenever two values are successively assigned to a variable, the interpreter will forget the previous value
assigned to it and store the latest value in the variable memory space.
>>> year=2016
>>> year=2017
>>> year
2017 # Output
>>>
In the given example, we first assigned 2016 to the variable year and then assigned 2017 to the same
variable. The interpreter will forget the value 2016 and will display 2017 as the value of year.
We can also assign different types of values to the same variable. For example, we can assign a text value
where there previously was a numeric value. Even in such a case however, only the last assigned value
remains.
Let us now look at an example of assigning different types of values to the same variable:
Introduction to Python 45
>>> amount=50
>>> amount
50 # Output
>>> amount=’Fifty’
>>> amount
‘Fifty’ # Output
>>>
3.8.1 Numeric
Numeric data can be broadly divided into integers and real numbers (i.e., fractional numbers). Integers can
themselves be positive or negative. Unlike many other programming languages, Python does not have any
upper bound on the size of integers. The real numbers or fractional numbers are called floating point numbers
in programming languages. Such floating point numbers contain a decimal and a fractional part.
Let us now look at an example that has an integer as well as a real number:
>>> num1=2 # integer number
>>>num2=2.5 # real number (float)
>>>num1
2 # Output
>>>num2
2.5 # Output
>>>
Note In all the earlier versions of Python 3, slash (/) operator worked differently. When
both numerator and denominator are integers, then the result will be an integer. The slash
operator removes the fraction part.
Let us look at an example of the division operator in all the earlier versions of Python 3:
>>> 5/2
2 # Output
>>>
46 Introduction to Computing & Problem Solving using Python
The result becomes a floating number when either the numerator or the denominator is a floating number.
When both the numerator and the denominator are floating numbers, the result is again a floating number.
Let us look at an example of the division operator in all the earlier versions of Python 3:
>>> 5.0/2
2.5 # Output
>>>
This operator has been modified in Python 3 and in all the versions after Python 3. The division operator
provides accurate results even when both the numerator and the denominator are integers.
Here is an example of the division operator that is used in all the versions after Python 3:
>>> 5/2
2.5 # Output
>>>
3.8.2 String
Besides numbers, strings are another important data type. Single quotes or double quotes are used to represent
strings. A string in Python can be a series or a sequence of alphabets, numerals and special characters. Similar
to C, the first character of a string has an index 0.
There are many operations that can be performed on a string. There are several operators such as slice
operator ([]) and [:]), concatenation operator (+), repetition operator (*), etc. Slicing is used to take out a
subset of the string, concatenation is used to combine two or more than two strings and repetition is used to
repeat the same string several times.
Here is an example of string data:
>>> sample_string =”Hello” # store string value
>>> sample_string # display string value
‘Hello’ # Output
>>> sample_string + “World” # use of + operator
‘HelloWorld’ # Output
>>> sample_string * 3 # use of * operator
‘HelloHelloHello’ # Output
Python also provides slice operators ([] and [:]) to extract substring from the string. In Python, the
indexing of the characters starts from 0; therefore, the index value of the first character is 0.
Syntax
>>> sample_string[start : end <:step>] #step is optional
Introduction to Python 47
Example
>>>sample_string=”Hello”
>>>sample_string[1] # display 1st index element.
‘e’ # Output
>>>sample_string[0:2] # display 0 to 1st index elements
‘He’ # Output
Example
>>> sample_string = "HelloWorld"
>>> sample_string[1:8:2] # display all the alternate charactors be-
tween index 1 to 8. ie, 1,3,5,7
'elWr' # Output
3.8.3 List
List is the most used data type in Python. A list can contain the same type of items. Alternatively, a list
can also contain different types of items. A list is an ordered and indexable sequence. To declare a list in
Python, we need to separate the items using commas and enclose them within square brackets([]). The list
is somewhat similar to the array in C language. However, an array can contain only the same type of items
while a list can contain different types of items.
Similar to the string data type, the list also has plus (+), asterisk (*) and slicing [:] operators for
concatenation, repetition and sub-list, respectively.
Let us look at an example of the List data type:
>>>first=[1,”two”,3.0,”four”] # 1st list
>>>second=[“five”, 6] # 2nd list
>>>first # display 1st list
[1, ‘two’, 3.0, ‘four’] # Output
>>>first+second # concatenate 1st and 2nd list
[1, ‘two’, 3.0, ‘four’, ‘five’, 6]# Output
>>>second * 3 # repeat 2nd list
[‘five’, 6, ‘five’, 6, ‘five’, 6] # Output
>>>first[0:2] # display sublist
[1, ‘two’] # Output
>>>
3.8.4 Tuple
Similar to a list, a tuple is also used to store sequence of items. Like a list, a tuple consists of items separated
by commas. However, tuples are enclosed within parentheses rather than within square brackets.
Let us look at an example of the tuple data type:
>>>third=(7, “eight”,9, 10.0)
>>>third
(7, ‘eight’, 9, 10.0) # Output
48 Introduction to Computing & Problem Solving using Python
parentheses ().
● Lists are mutable whereas Tuples are immutable. Tuples are read only lists. Once the items are stored,
TIP
The items cannot be modified in a tuple but the same is not the case with a list.
3.8.5 Dictionary
It is the same as the hash table type. The order of elements in a dictionary is undefined. But, we can iterate
over the following:
1. The keys
2. The values
3. The items (key-value pairs) in a dictionary
A Python dictionary is an unordered collection of key-value pairs. When we have the large amount of
data, the dictionary data type is used. Keys and values can be of any type in a dictionary. Items in dictionary
are enclosed in the curly-braces{} and separated by the comma (,). A colon (:) is used to separate key from
value. A key inside the square bracket [] is used for accessing the dictionary items.
Example of dictionary:
>>> dict1 = {1:"first line", "second":2} # declare dictionary
>>> dict1[3] = "third line" # add new item
>>> dict1 # display dictionary
{1: 'first line', 'second': 2, 3: 'third line'} #Output
>>> dict1.keys() # display dictionary keys
[1, 'second', 3] # Output
>>> dict1.values() # display dictionary values
['first line', 2, 'third line'] # Output
3.8.6 Boolean
In a programming language, mostly data is stored in the form of alphanumeric but sometimes we need to
store the data in the form of ‘Yes’ or ‘No’. In terms of programming language, Yes is similar to True and
No is similar to False.
This True and False data is known as Boolean Data and the data types which stores this Boolean data are
known as Boolean Data Types.
Introduction to Python 49
Example
>>> a = True
>>> type(a)
<type ‘bool’>
>>> x = False
>>> type(x)
<type ‘bool’>
3.8.7 Sets
The lists and dictionaries in Python are known as sequence or order collection of data. However, in Python
we also have one data type which is an unordered collection of data known as Set. A Set does not contain
any duplicate values or elements.
Union, Intersection, Difference and Symmetric Difference are some operations which are performed on
sets.
Union: Union operation performed on two sets returns all the elements from both the sets. It is performed
by using & operator.
Intersection: Intersection operation performed on two sets returns all the element which are common or in
both the sets. It is performed by using | operator.
Difference: Difference operation performed on two sets set1 and set2 returns the elements which are present
on set1 but not in set2. It is performed by using – operator.
Symmetric Difference: Symmetric Difference operation performed on two sets returns the element which
are present in either set1 or set2 but not in both. It is performed by using ^ operator.
Example
# Defining sets
>>> set1 = set([1, 2, 4, 1, 2, 8, 5, 4])
>>> set2 = set([1, 9, 3, 2, 5])
type() Function
type() function in Python programming language is a built-in function which returns the datatype of any
arbitrary object. The object is passed as an argument to the type() function. Type() function can take anything
as an argument and returns its datatype, such as integers, strings, dictionaries, lists, classes, modules, tuples,
functions, etc.
Example
>>> x = 10
>>> type(x)
<type ‘int’> #Output
>>> type(‘hello’)
<type ‘str’> #Output
>>> import os
>>> type (os)
<type ‘module’> #Output
>>> li = [1,2,3]
>>> type(li)
<type ‘list’> #Output
Introduction to Python 51
3.9 OPERATORS
Operators are constructs used to modify the values of operands. Consider the following expression:
3 + 4 = 7
In the above expression, 3 and 4 are the operands whereas + is operator.
Based on functionality, operators are categories into following seven types:
1. Arithmetic operator
2. Comparison operator
3. Assignment operator
4. Logical operator
5. Bitwise operator
6. Membership operator
7. Identity operator
Example
>>> x = 10
>>> y = 12
>>> z = 0
>>> z = x + y
>>> print z
22 #Ouput
>>> z = x - y
>>> print z
-2 #Ouput
>>> z = x * y
>>> print z
120 #Ouput
>>> z = x / y
>>> print z
0 #Ouput
>>> z = x % y
>>> print z
10 #Ouput
>>> z = x ** y
>>> print z
1000000000000 #Ouput
>>> z = x // y
>>> print z
0 #Ouput
Example
>>> x = 10
>>> y = 12
>>> z = 0
>>> if (x == y):
print “x is equal to y”
else:
print “x is not equal to y”
>>> if (x != y):
print “x is not equal to y”
else:
print “x is equal to y”
Example
>>> x = 10
>>> y = 12
>>> y += x
>>> print y
22 #Output
>>> y *= x
>>> print y
220 #Output
>>> y /= x
>>> print y
22 #Output
Introduction to Python 55
>>> y %= x
>>> print y
2 #Output
>>> y **= x
>>> print y
1024 #Output
>>> y //= x
>>> print y
102 #Output
Example
>>> x = 10 # 10 = 0000 1010
>>> y = 12 # 12 = 0000 1100
>>> z = 0
# Bitwise AND
>>> z = x & y
>>> print z
8 # 8 = 0000 1000
# Bitwise OR
56 Introduction to Computing & Problem Solving using Python
>>> z = x | y
>>> print z
14 # 14 = 0000 1110
# Bitwise XOR
>>> z = x ^ y
>>> print z
6 # 6 = 0000 0110
# Bitwise inverse
>>> z = ~x
>>> print z
-11 # -11 = 1111 0101
# Left shift
>>> z = x << 2
>>> print z
40 # 40 = 0010 1000
# Right shift
>>> z = x >> 2
>>> print z
2 # 2 = 0000 0010
Example
>>> x = True
>>> y = False
False #Output
>>> print (x or y)
True #Output
Example
>>> x = 10
>>> y = 12
>>> list = [21, 13, 10, 17]
>>> if (x in list):
print “x is present in the list”
else:
print “x is not present in the list”
Example
>>> x = 12
>>> y = 12
>>> if ( x is y):
print “x is same as y”
else:
print “x is not same as y”
x is same as y #Output
>>> y = 10
When the given expression is evaluated left to right, the final answer becomes 3. However, if the above
expression is evaluated right to left, the final answer becomes 11. This shows that changing the sequence
in which the operators are evaluated in the given expression also changes the solution. Therefore, in order
to remove this problem, a level of precedence is associated with the operators. Precedence is the condition
that specifies the importance of each operator relative to the others.
Table 3.9 to display operator precedence from lower precedence to higher:
Introduction to Python 59
It may happen that an expression has two operators having same precedence. In that case, we use
Associativity to evaluate the expression. Associativity is nothing but the direction in which we evaluate the
operators if they have same precedence.
3.9.9 Associativity
In Table 3.9 (precedence of operators) we can see that many operators are having the same precedence.
Hence, associativity decides the order in which the operators with same precedence are executed.
There are two types of associativity. One is left-to-right and other is right-to-left. In left-to-right
associativity, the operator of same precedence are executed from the left side first and in right-to-left
associativity, the operator of same precedence are executed from the right side first. Most of the operators
in Python have left-to-right associativity. Examples for left-to-right associative operators are multiplication,
floor division, etc and ** operator is right-to-left associative.
Example
>>> 3 * 4 // 6
2 #Output
>>> 3 * (4 // 6)
0 #Output
>>> 3 ** 4 ** 2 # 3^16
43046721 #Output
>>> (3 ** 4) ** 2 # 81^2
6561 #Output
Note The order in which operators are evaluated can be controlled using parentheses, as
illustrated in the example. Parentheses have the highest precedence.
60 Introduction to Computing & Problem Solving using Python
Note When two operators have the same precedence, then operators are evaluated from
left to right direction.
Let us now look at an example of a mathematical expression with operators having the same precedence:
10 * 5 / 5
In the above expression, the multiplication operator is evaluated before the division operator is evaluated.
Based on the number of operands, operators are classified into following two types:
1. Unary Operator
2. Binary Operator
Unary Operator
Unary operators are operators with only one operand. These operators are basically used to provide sign to
the operand.
The format of the unary operator is:
Operator operand
Some unary operators are as follows:
● +
● -
● ~
Example
>>> x = 12
>>> +x
12 #Output
>>> -x
-12 #Output
>>> ~x
-13 #Output
Note The invert(~) operator returns the bit-wise inversion of long integer arguments.
The bit-wise inversion of y can be computed as –(y+1). Hence, in the above example, we
get the ~(12) as -13.
Binary Operator
Binary operators are operators with two operands that are manipulated to get the result. They are also used
to compare numeric values and string values.
The format of binary operator is:
Operand1 Operator Operand2
Some binary operators are as follows:
**, *, /, %, +, -, <<,>>, &, | ,^,<,>,<= ,>=, == ,!= ,<>
We saw many examples of binary operators in the section above.
Introduction to Python 61
● Comparison Operator
● Assignment Operator
● Logical Operator
● Bitwise Operator
● Membership Operator
● Identity operator
3.10.2 Expression
An expression is a combination of variables, operators, values and a reserve keyword.
Whenever you type an expression in the command line, the interpreter evaluates it and produces the
result.
Example
>>> 1+1
2 # Output
62 Introduction to Computing & Problem Solving using Python
Evaluation of Expression
The evaluation of an expression produces a value. In an assignment statement, an expression is always there
on the right side.
Let us look at an example of an expression:
>>> 2+3
5 # Output
>>>program=”Hello Python”
>>>program
‘Hello Python’ # Output
>>>print program
Hello Python # Output
Note In the given example, we assigned a value “Hello Python” to the variable program.
Now, when we type only program, we get the output ‘Hello Python.’ This is the term we
typed when we assigned a value to the variable. When we use a print statement with
program it gives the value of the variable, i.e., the value after removing quotes.
3.11.1 Concatenation
The concatenation operation is done with the + operator in Python. Concatenation means joining the strings
by linking the last end of the first string with the first end of the second string and so on. Two separate strings
transform into one single string after concatenation.
Let us look at an example of concatenation:
>>>test=”Test string”
>>> “Hello” + test
‘HelloTest string’ # Output
>>>
Introduction to Python 63
3.11.2 Repetition
The repetition operation is performed on the strings in order to repeat the string several times. It is done
with * operator.
Let us look at an example of repetition:
>>> ‘Spam’*3
SpamSpamSpam # Output
>>>
3.11.4 Slicing
In Python, you can extract a substring by using a colon inside the square bracket [:]. The resultant substring
is a part of the long string.
>>>test=”Test string”
>>>test[1:7]# substring between index 1 to 7 (excludes 7)
‘est st’ # Output
>>>test[:3] # substring from index 0 to 3(excludes 3)
‘Tes’ # Output
>>>test[2:] # substring from index 2 to last
‘st string’ # Output
>>>
Python also provides various in-built commands or methods for string operation (Table 3.10). These
methods are used to convert the lower case letter to upper case, to determine the length of string, etc.
Example
>>> s = “Hello Python” #Defining a string
>>> print s.lower()
hello python #Converts the string in lower case
>>> print s.upper()
HELLO PYTHON #Converts the string in upper case
>>> print s.find(“l”)
2 #returns the index of first ‘l’
>>> print s.replace(“l”,”p”)
Heppo Python #Replace each “l” to “p”
>>> print s.count(“o”)
2 #count the number of “o”
>>> print len(s)
12 #Length of the string
>>> s = “Hello”
>>> print s.isalpha()
True #String contains only alphabets
>>> print s.isdigit()
False #String doesn’t contain digits
Note We can see in the following example that bool is the name of the class representing
Python’s Boolean expressions.
>>>type(True)
<type ‘bool’>
>>>type(False)
<type ‘bool’>
Syntax
>>>for x in y :
Block 1
else: # Optional
Block 2 # excuted only when the loop exits normally
In the above section, we have seen the syntax of for loop. The for loop is used to iterate over a
sequence. Here, x is used to iterate over y and when the loop exits normally then the else part of the for
loop executes otherwise not.
Example
>>>for letter in ‘Python’ :
print ‘Current Letter :’, letter
Output:
Current Letter : P
Current Letter : y
Current Letter : t
Current Letter : h
Current Letter : o
Current Letter : n
Example
>>> subjects = [“Maths”, “English”, “Physics”, “Chemistry”, “Computer”]
>>> for x in subjects:
print(x)
66 Introduction to Computing & Problem Solving using Python
Maths #Output
English
Physics
Chemistry
Computer
Example
>>> for x in range(7):
print(x)
else:
print(‘Else Part’)
0
1
2
3
4
5
6
Else Part
In the above example, we have printed the value from 0 to 6 by using the for loop and an else part
having a print statement is also been used. In this case, the for loop is ended normally then the
else part also executed but when the loop stops because of break statement then the else part
doesn’t execute.
range() Function
The range() function is a built-in function in Python that helps us to iterate over a sequence of numbers.
It produces an iterator that follows arithmetic progression.
Example
>>> range(8)
[0, 1, 2, 3, 4, 5, 6, 7]
range(8) provides a sequence of numbers 0-7. That is to say, range(n) generates a sequence of numbers
that starts with 0 and ends with (n-1).
range() function can also be passed with two arguments: begin and end.
Example
>>> range(3,9)
[3, 4, 5, 6, 7, 8]
Introduction to Python 67
We provided the begin index with 3 and the end index with 9. Hence, the range function generates a
sequence iterator of numbers that starts from 3 and ends at 8.
Till now, we have seen that all the numbers in the sequence have a difference of 1. We can also change
this difference if we want to. For this purpose, we have to use another parameter, step, along with begin
and end.
Example
>>> range(3,40, 5)
[3, 8, 13, 18, 23, 28, 33, 38]
This range() function gives us a sequence that starts from 3 and ends at 38; every number in the list has
a difference of 5.
Example
>>> subjects = [‘maths’, ‘physics’, ‘chemistry’, ‘computer’]
In the above example, a list subjects is defined which has 4 elements or items in it. Now, it is required
to print all the elements in list subjects one by one with the for loop and taking help of range()
function. Now, we initialized a for loop in next statement which will iterate over the sequence of number
given by the range() function. In our example, we have used range(len(subjects)) which means
range(4) that is because the length of the list subjects is 4 which is computed by the function len.
Syntax
>>> while condition :
block
else: #Optional
statement
68 Introduction to Computing & Problem Solving using Python
Here, condition is a statement by which interpreter decides when to halt the loop and block is the
piece of code that we want to repeat.
Example
Write a while statement that prints integers from zero to 5.
>>> count = 0
>>> while count < 6:
print count
count += 1
0 # Output
1
2
3
4
5
Example
# Print first five even numbers.
>>> count = 2
>>> while True:
print count
count = count + 2
if count >= 12:
break # breaks the loop
2 # Output
4
6
8
10
Example
# Print first four even numbers.
>>> for i in range(1,10):
Introduction to Python 69
if i % 2 != 0:
continue # if condition becomes true, it skips the print
part
print i
2 # Output
4
6
8
Note If the break statement in a for loop is executed then the else part of that for loop
is skipped.
Note The break and continue statements are often useful in a while statement. The
break statement exits from the loop. The continue statement causes execution to
immediately continue at the start of the loop.
Example
>>>var = 100
if (var ==100) : print “Value of expression is 100”
Output:
Value of expression is 100
An else statement can be combined with an if statement. It contains the block of code that executes
if the conditional expression in the if statement resolves to 0 or FALSE value. It is an optional statement.
Please note there can be at the most one else statement following if.
Syntax
>>>if expression :
statement1
else :
statement2
70 Introduction to Computing & Problem Solving using Python
We can check multiple expressions for TRUE with the help of elif statement and execute a block of code
written just below the elif statement whose condition is TRUE.
Similar to else, the elif statement is optional. However, there can be more than one elif statement
following an if.
Syntax
>>>if expression1 :
statement1
elif expression2 :
statement2
elif expression3 :
statement3
else expression4 :
statement4
TIP
The Boolean expression after the if statement is called the condition. If the condition is
true, then the intended statement is executed. If the condition is not true, the statement is
not executed.
Note The set of intended statements that follow a conditional statement or a loop
statement is called block. Indentation can be done by 'tabs' or 'spaces'. Using 4 spaces for
indentation of a block is standard. A statement block inside a compound statement is called
the body of the statement.
The intended statements that follow the conditional statements are called block. The first
unintended statement marks the end of the block. A statement block inside the compound
statement is called the body of the statement.
There are no bounds on the number of statements that can appear in the body of an if statement, but there
has to be at least one statement. Occasionally, it is useful to have a body with no statements. In that case,
you can use the pass statement, which does nothing.
>>>if True : # This is always true
pass # so this is always executed, but it does nothing
Syntax
The syntax of a while loop in Python programming language is as follows:
>>> while expression :
statement(s)
else: # Optional
statement # executes only when while condition becomes false
Here, statement(s) may be a single statement or a block of statements. The condition may be any
expression, and whenever the expression resembles a non-zero value, it will be treated as TRUE, otherwise
it will be treated as FALSE. The loop iterates while the condition is TRUE.
72 Introduction to Computing & Problem Solving using Python
Unlike other programming languages, while loop in Python makes use of an optional else clause which
is executed when the condition of while statement fails.
When the condition becomes false, program control passes to the line immediately following the loop.
Flow Diagram
Figure 3.8 represents a flow diagram.
while expression:
statements(s)
condition
Example
>>>count = 0
while (count < 9) :
print ‘The count is :’, count
count = count + 1
Output:
The count is : 0
The count is : 1
The count is : 2
The count is : 3
The count is : 4
The count is : 5
The count is : 6
The count is : 7
The count is : 8
The block here, consisting of the print and increment statements, is executed repeatedly until count is no
longer less than 9. With each iteration, the current value of the index count is displayed and then increased
by 1.
Introduction to Python 73
Note If there is a continue statement inside a while loop or a for loop then also the else
part of that loop is executed.
Example
>>> name = input(“What is your Name?”)
>>> print (“Hello “ + name + “!”)
>>> type(name)
<type ‘str’>
>>> type(age)
74 Introduction to Computing & Problem Solving using Python
<type ‘int’>
>>> type(hobbies)
<type ‘list’>
Example
# No casting
>>> age = raw_input(“What is Your Age? “)
What is Your Age? 46
>>> type(age)
<type ‘str’> #Input is stored as string
● Python is a high-level general-purpose programming language. The code written in Python is automatically
compiled to byte code and executed.
● The print statement is used to display the output screen.
● In Python, the Hash character (#) is used for commenting. Codes or texts that come after the hash character
are not considered as a part of the program.
● In Python, an identifier (name) must begin with a letter or underscore and can include any number of
letters, digits, or underscore.
● Writing the name of a variable is called declaring a variable whereas assigning a value to a variable is
called initialising a variable.
● Python supports six data types which are as follows:
1. Numeric
2. String
3. List
4. Tuple
5. Dictionary
6. Boolean
● The main differences between lists and tuples are that lists are enclosed in brackets ([]) and their elements
and size can be changed, while tuples are enclosed in parentheses(()) and cannot be updated. Tuples can
be thought of as read-only lists.
● The items cannot be modified in tuple, but can be modified in the list.
● A Python dictionary works on the basis of key-value pairs. Key used in dictionary can be an integer value
or a string value.
● On the basis of functionality, operators in Python are categorised into following seven types:
1. Arithmetic operator
2. Comparison operator
3. Assignment operator
4. Logical operator
5. Bitwise operator
6. Membership operator
7. Identity operator
● A statement is a unit of code that the Python interpreter can execute.
● An expression is a combination of variables, operators, values and reserve keyword.
● A string is a combination of characters (alphabets, digits and symbols). A string value is always enclosed
within double or single quotes.
● The concatenation operation is done with the + operator. Concatenation means joining the strings together
by linking them end to end.
● The repetition operation is performed on the strings in order to repeat the string several times.
● In Python, you can extract substring by using the colon inside the square bracket [:]. The resultant
substring is a part of the long string.
76 Introduction to Computing & Problem Solving using Python
● In Python, for statement iterates over the items in a sequence (a list or a string) in the order in which
they appear in the sequence.
● Syntax for while statement in Python is:
>>> while condition :
Block
✓ COMMENT: The part of the program not executed by the interpreter. It is used by other persons to
understand the program thoroughly.
✓ CONCATENATION: The process of joining strings end-to-end.
✓ DICTIONARY: A mapping of keys to their corresponding values.
✓ FLOATING POINT: A type of numeral that has a fractional part.
✓ HIGH-LEVEL LANGUAGE: A programming language such as Python that is designed to be easy for
humans to read and write.
✓ INDEX: An integer value that represents an element in a sequence.
✓ INTEGER: A type of numeral that represents whole numbers including negative numbers.
✓ INTERACTIVE MODE: A way of using Python language where we type command and expressions.
✓ INTERPRET: To execute a program in a high-level language by executing it one line at a time.
✓ ITEM: An element or a value in a series.
✓ ITERATION: The repetition of a set of statements or a piece of code.
✓ KEYWORD: A word that is reserved in a programming language for a specific purpose. We cannot use
keywords such as if and else as variable names.
✓ OPERAND: The value on which an operator operates.
✓ SLICE: A subset or a part of a string.
PROGRAMS
1. Write a Program to find the square root of a number.
Solution.
>>> x = int(input(‘Enter an integer number: ‘))
>>> sqrt_x = x ** 0.5
>>> print (sqrt_x)
6. Write a program to check the largest among the given three numbers.
Solution.
>>> x = int(input(“Enter the first number: “))
Enter the first number: 14
>>> y = int(input(“Enter the second number: “))
78 Introduction to Computing & Problem Solving using Python
7. Write a Python program to check if the input year is a leap year or not.
Solution.
# Python program to check if the input year is a leap year or not
Output:
Enter a year: 2016
2016 is leap year
Output:
Enter a year: 1985
1985 not leap year
Output:
Enter the value for n (where n>2)? 10
Fibonacci sequence:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34,
>>> count = 0
>>> while count < 3:
print(“Inside the while loop”)
print (count)
counter = count + 1
else:
print(“Inside the else statement”)
Output:
Inside the while loop
0
Inside the while loop
1
Inside the while loop
2
Inside the else
10. Write a Python program to print the prime numbers for a user provided range.
Solution.
# Python program to print the prime numbers for a user provided range
# input range is provided from the user
>>> low = int(input(“Enter Lower range: “))
80 Introduction to Computing & Problem Solving using Python
8. Which of the following is used to find the first index of search string?
a. .find(“string”) b. .search(“string”)
c. (“string”).find d. (“string”).search
9. Which of the following is used to access single character of string?
a. [:] b. ()
c. [.] d. []
10. What is the order of precedence in Python?
i. Addition ii. Multiplication
iii. Division iv. Subtraction
v. Exponential vi. Parenthesis
a. ii, i, iii, iv, vi, v b. vi, v, iii, ii, i, iv
c. vi, v, ii, i, iii, iv d. ii, vi, iii, i, iv, v
11. Which of the following will be printed?
x =4.5
y =2
print x//y
a. 2.0 b. 2.25
c. .25 d. 0.5
12. What gets printed?
Nums=set([1,1,2,3,3,3,4])
Print len(nums)
a. 2 b. 4
c. 5 d. 7
Short Questions
1. What is Python? What is Python good for?
2. How can we distinguish between tuples and lists?
3. How can a string be converted to a number?
4. What are comments in Python?
5. What will be the output of the given code?
list = [‘p’, ‘r’, ‘s’, ‘t’,]
print list[8:]
6. Briefly describe the data types in Python.
7. What will be the output of the code str + “Python” if str = ‘Programming!’?
8. What will be the output of the code test*5 if test = (000, ‘computer’)?
9. Describe operators in Python.
10. How will you create a dictionary in Python?
11. How will you convert a string to an integer in Python?
12. What are the uses of //, **, *= operators in Python?
4.1 INTRODUCTION
Functions are self-contained programs that perform some particular tasks. Once a function is created by the
programmer for a specific task, this function can be called anytime to perform that task.
Suppose, we want to perform a task several times, in such a scenario, rather than writing code for that
particular task repeatedly, we create a function for that task and call it when we want to perform the task.
Each function is given a name, using which we call it. A function may or may not return a value.
There are many built-in functions provided by Python such as dir(), len(), abs(), etc. Users can
also build their own functions, which are called user-defined functions.
There are many advantages of using functions:
a) They reduce duplication of code in a program.
b) They break the large complex problems into small parts.
c) They help in improving the clarity of code (i.e., make the code easy to understand).
d) A piece of code can be reused as many times as we want with the help of functions.
Example
>>>int(5.5)
5 # Output
>>>int(‘Python’)
Traceback (most recent call last): # Output
File “<pyshell#21>”, line 1, in <module>
int(‘Python’)
ValueError: invalid literal for int() with base 10: ‘Python’
>>>int(‘5’)
5 # Output
In the above examples, you can see that in the first case, we took a floating-point number 5.5 that was
converted to an integer number 5 by the int function. In the second case, we took a string that was not a
number and applied int function to it, but got an error. This means that a string that is not a number cannot
be converted to an integer. However, in the third case, we took a number in string form and converted it to
an integer 5 using int function.
Similarly, we have a function float, which can convert integers and string into floating-point numbers.
Example
>>>float(45)
45.0 # Output
>>> float (‘5’)
5.0 # Output
Finally, Python has a str function that converts the types into strings.
Example
>>>str(67)
‘67’ # Output
>>>print(‘Python version’ + 2.7)
TypeError: cannot concatenate ‘str’ and ‘float’ objects # Output
>>>print(‘Python version’ + str(2.7))
Python version2.7 # Output
In the example given above, you can see that when we try to concatenate a string and a float object, the
interpreter gives an error saying, “cannot concatenate ‘str’ and ‘float’ objects.” Hence, we
convert the float object, i.e., 2.7 to a string using the str function and then successfully concatenate it with
another string.
Type coercion is a process through which the Python interpreter automatically converts a value of one
type into a value of another type according to the requirement.
Example
Suppose we want to calculate an elapsed fraction of an hour. The expression minutes/60 does integer
arithmetic and gives result, even 59 minutes past hour.
One solution is that we convert the minutes to a floating-point number using type conversion and
do floating-point division:
>>>minute=59
>>>float(minute)/60
0.98333333333 # Output
Alternatively, we can take advantage of type coercion process in Python. For the mathematical
operators, if either operand is a float, the other is automatically converted to float:
>>>minute=59
>>>minute/60.0
0.98333333333 # Output
Hence, in the example given above, we make the denominator a float number. The Python interpreter
automatically converts the numerator into float and does the calculation.
Note that when a float number is converted to integer, the tractional part is truncated.
Python provides us a Math module that contains most of the familiar and important mathematical
functions. A module is a file that contains some predefined Python codes. A module can define functions,
classes and variables. It is a collection of related functions grouped together.
Before using a module in Python, we have to import it.
For example, to import the math module, we use:
>>> import math
This statement creates an object of module named math. Now, if we try to print this object, the interpreter
will give some information about it:
>>>print math
<module ‘math’ (built-in)>
There are many predefined functions and variables that reside under the module object. To access these
functions, we have to write the name of the module followed by a dot (.) (this dot is also known as a period)
followed by the function name.
Example
>>>decibel = 10 * math.log10(18.0)
>>>angle = 2.5
>>>height = math.sin(angle)
In the given example, we use two math module functions, log and sin. In the first statement, the variable
decibel is set to the log of 18 base 10. If you want to perform log 18.0 with base e, then simply
write log(18.0).
The third statement calculates the sine of the variable angle. Sin and other trigonometric functions
(i.e., cos, tan, cosec, etc.) take the value of angles in radians as arguments. In order to convert degrees
to radians, we divide the value in degree by 360 and multiply by 2*pi.
Example
Find the cos of 45degrees.
>>>degree = 45
>>>angle = degree * 2 * math.pi/360.0
>>>math.cos(angle)
0.7071067811865476 # Output
In the given example, we use a math.pi function in order to get the variable pi from the math module.
Examples
Getting current date and time:
>>> import time;
>>>
>>> localtime = time.localtime(time.time())
>>> print “Local current time : “, localtime
#Output
Local current time : time.struct_time(tm_year=2016, tm_mon=5, tm_mday=31,
tm_hour=19, tm_min=21, tm_sec=50, tm_wday=1, tm_yday=152, tm_isdst=0)
This example gives us the current time and date. This function returns a time-tuple with nine items.
If we want, we can change the format in which the time and date is given.
Here, we make use of the asctime() function to get a readable format of date and time.
Getting calendar for a month:
Python provides us a calendar module through which we can use yearly and monthly calendars
>>> c = calendar.month(2015,10)
>>> print “Calender for October, 2015: \n”, c
In the examples discussed above, localtime(), asctime() and month() are built-in functions
contained in the modules time and calendar.
Functions 87
Example
>>> import math
>>> list = dir(math)
>>> print list
#Output
[‘__doc__’, ‘__name__’, ‘__package__’, ‘acos’, ‘acosh’, ‘asin’, ‘asinh’,
‘atan’, ‘atan2’, ‘atanh’, ‘ceil’, ‘copysign’, ‘cos’, ‘cosh’, ‘degrees’,
‘e’, ‘erf’, ‘erfc’, ‘exp’, ‘expm1’, ‘fabs’, ‘factorial’, ‘floor’, ‘fmod’,
‘frexp’, ‘fsum’, ‘gamma’, ‘hypot’, ‘isinf’, ‘isnan’, ‘ldexp’, ‘lgamma’,
‘log’, ‘log10’, ‘log1p’, ‘modf’, ‘pi’, ‘pow’, ‘radians’, ‘sin’, ‘sinh’,
‘sqrt’, ‘tan’, ‘tanh’, ‘trunc’]
In the given example, we give the math module as an argument to the dir() function and it gives the
list of all the functions, modules and variables present in the math module.
Note The module that is passed in the dir() function must be imported first.
Example
# import math module
>>> import math
>>> help(math.sin) #give detailed info about sin function in math module
Help on built-in function sin in module math:
sin(...)
sin(x)
Return the sine of x (measured in radians).
>>> help(math.cos) #give detailed info about cos function in math module
Help on built-in function cos in module math:
cos(...)
cos(x)
Return the cosine of x (measured in radians).
88 Introduction to Computing & Problem Solving using Python
where, f and g are functions. This means the return value of function g is passed into the function f as
parameters/arguments.
Just as with the mathematical functions, Python functions can also be composed. We can use any kind of
expression including arithmetic operators as an argument to a function.
Example
>>> x = math.sin(angle + math.pi/4)
In the given example, we have used an expression angle + math.pi/4 as an argument to the function
math.sin. First, the value of the innermost expression is computed, and then the resulting value is used as
the argument for the function math.sin.
Similarly, we can also take a function as an argument to another function.
Example
>>> x = math.exp(math.log(10.0))
Here, the value of the function math.log(10.0)is calculated first and then used as the argument for
the function math.exp.
2. Write a program to print the calendar for the month of March, 1991.
Ans.
>>> import calendar
>>> c = calendar.month(1991, 3)
>>> print c
March 1991
Functions 89
Mo Tu We Th Fr Sa Su
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
Syntax
def functionname(parameters):
“function_docstring”
statement(s)
return [expression]
In any type of programming language, a docstring is a string literal which is used to document a specific
part of the code. It is used just like the comments in the programming language. It does not affect the program
execution but it is considered to be a good practice to use docstrings.
Example
>>>def print_lines():
... print “Hello Python!!”
... print “Welcome to Python Programming!!”
90 Introduction to Computing & Problem Solving using Python
The function definition is always preceded by the keyword def. In the given example, print_lines is
the name of the function.
The rules for defining a function name are same as those for variable names: alphabets, numerals and
some special characters are allowed. The name of the function cannot start with a number. No keyword can
be used as the name of the function. Giving the same name to a variable and a function should be avoided.
The parentheses after the function name contain the parameters or arguments. They are optional.
The first line in the definition of function is known as header and the rest is abbreviated as body. The
header line will always end with a colon. All the statements meant to execute at the time of function calling
are defined in the body part only. We can define any number of statements in the body of the function
definition but they have to be ordered from the left margin.
When we type a function definition in interactive mode (command line), the ellipses (...) are
automatically displayed by the interpreter in the next line to tell us that the definition is not complete yet
Figure 4.1
Example
>>>defprint_lines():
... print “Hello Python!!”
... print “Welcome to Python Programming!!”
...
Functions 91
When we define a function, Python interpreter also creates a variable with the same name.
>>> print print_lines
<functionprint_lines at 0x0294D970>
>>>type (print_line)
<type ‘function’>
As you can see above, the type of print_lines is ‘function’ and value is a function object.
In the previous sections, we have seen the calling of the built in function. The calling of the user-defined
functions happens in a similar way.
>>> print print_lines()
Hello Python!! # Output
Welcome to Python Programming!! # Output
Example
>>>defnew_print():
print_lines()
print_lines()
>>>new_print()
Output:
Hello Python!!
Welcome to Python Programming!!
Hello Python!!
Welcome to Python Programming!!
In the given example, we created a new function new_print() and inside the body of this function,
we called the print_lines() function twice. Now, when we call new_print(), the print_lines()
function is executed twice. This is how we call a function within another function.
Hence, we can call a function repeatedly when we want to do so and can also call the function from
another function. In the example given above, we call print_lines()twice inside new_print() in order
to repeatedly call print_lines().
Now, we combine the code fragments from the above section into a single program:
>>> def print_lines():
print “Hello Python!!”
print “Welcome to Python Programming!!”
>>> def new_print():
print_lines()
print_lines()
>>> new_print()
Hello Python!! # Output
Welcome to Python Programming!!
Hello Python!!
Welcome to Python Programming!!
92 Introduction to Computing & Problem Solving using Python
As you can see, this whole program has two function definitions: print_lines()and new_print().
When a function definition is executed, a function object is created. The statements residing inside a function
get executed only when the function is called. Outputs are generated only by the function calls and not by
the function definitions.
Example
>>>defprint_lines(line):
... print line
... print line
In this function we have defined a variable line which is a parameter. Now, when the function is called,
it prints the value of the parameter line twice.
>>>print_lines(‘Hello’)
Hello # Output
Hello # Output
>>>print_lines(17)
17 # Output
17 # Output
>>>print_lines(math.pi)
3.14159265359 # Output
3.14159265359 # Output
We can see that this function works with any type of value that can be displayed.
There can be four types of formal arguments using which a function can be called which are as follows:
2. Keyword arguments
3. Default arguments
4. Variable-length arguments
1. Required arguments When we assign the parameters to a function at the time of function definition, at
the time of calling, the arguments should be passed to a function in correct positional order; furthermore,
the number of arguments should match the defined number of parameters.
Functions 93
Example
>>>defprint_lines(str)
... print str
... return;
We have defined one parameter str to the function print_lines. Hence, at the time of calling, we have
to pass exactly one argument to the function, otherwise it will produce an error.
# function calling here
>>>print_lines();
Traceback (most recent call last): # Output
File “<pyshell#18>”, line 1, in <module>
print_lines()
TypeError: print_lines() takes exactly 1 argument (0 given)
There is an error because we did not pass any argument to the function print_lines, while according
to the function definition, the function print_lines must take exactly one argument.
2. Keyword arguments In keyword arguments, the caller recognises the arguments by the parameter’s
names. This type of argument can also be skipped or can also be out of order.
Example 1
>>>defprint_lines():
... print str
... return
...
Example 2
# Function Definition
>>>defprint_info(name, age):
... print “Name: “, name
... print “Age: “, age
... return
...
# function calling
>>>print_info(age=15, name=’john’);
Name: john # Output
Age: 15 # Output
94 Introduction to Computing & Problem Solving using Python
3. Default arguments In default arguments, we can assign a value to a parameter at the time of function
definition. This value is considered the default value to that parameter. If we do not provide a value to the
parameter at the time of calling, it will not produce an error. Instead it will pick the default value and use it.
Example
# Function definition
>>>defprint_info(name, age=35):
... print “Name: “,name
... print “Age: “, age
... return
...
# function calling
>>>print_info(age=20, name=’john’);
Name: john # Output
Age: 20 # Output
>>>
>>>print_info(name=’john’);
Name: john # Output
Age: 35 # Output
In the given example, we have given a value 35 to the parameter age. It is the default value for age.
Now, in the first function call, we provide the value of age as 20. Hence, the Python interpreter takes the
value provided by us and does not use the default value.
However, in the second function call, we do not provide the value for age. Hence, the Python interpreter
Syntax
def function_name([formal_args] *var_args_tuple):
“function_docstring”
function_body
return[expression]
Functions 95
Example
# function definition here
>>>defprint_info(arg1,*vartuple):
... print “Result is: “
... print arg1
... for var in vartuple:
... print var
... return
# function call
>>>print_info(10);
10 # Output
>>>print_info(90,60,40);
90 # Output
60 # Output
40 # Output
Syntax
def functionname(parameters):
“function_docstring”
statement(s)
return [expression]
2. Write a function that takes exactly two arguments. One argument is the name of the
student, the other argument is fees and a default fee is 25000. Display at least two outputs
in support of your answer.
Ans. # Function definition
>>>defprint_info(name, fees=25000):
... print “Name: “,name
... print “fees: “, fees
... return
...
# function calling
>>>print_info(fees=20000, name=’Jack’);
96 Introduction to Computing & Problem Solving using Python
Example 1
# Function definition here
>>>defprintstring(str):
...“This prints the passed string into this function”#Docstring
... print str;
... return;
# Now we can call printstring function here
>>>printstring(“First String”);
>>>printstring(“Second String”);
The code given above will produce the following result on execution.
Output:
First String
Second String
Example 2
Multiplication of two numbers using function.
>>>defmult(a,b):
... multiplication = a*b
... return multiplication
# Now calling the function here
>>> a = 4
>>> b = 3
>>> m = mult(a,b) # calling the mult function
>>>print(m)
Functions 97
2. Write a function which accepts two numbers and returns their sum.
Ans. >>>def sum(arg1,arg2):
... sum = arg1 + arg2
... return sum
# Now calling the function here
>>> a = 4
>>> b = 3
>>>total = sum(a,b) # calling the mult function
>>>print(total)
Syntax
return [expression]
Example
# function definition here
>>>def div(arg1, arg2):
... division = arg1/arg2
... return division
...
In the given example, we define a function div that divides one argument by another and stores the
result in the variable division; then the value of division variable is returned by the function to the
caller variable arg3.
example, if an object is placed between two mirrors facing each other, the object will be reflected recursively.
In the programming context, the meaning of recursion remains the same. Here, if a function, procedure
or method calls itself, it is called recursive. In Python, we know that a function can call another function,
but it is also possible that a function calls itself.
Let us look at an example of a recursive function by computing the factorial of a number. The factorial
of 5 is 1*2*3*4*5 = 120.
Example
>>> def fact_rec(x):
‘Recursive function to find the factorial of an integer’
... if x == 1:
... return 1
... else:
... return(x * fact_rec(x-1))
>>> fact_rec(4)
24 # Output
>>> fact_rec(10)
3628800 # Output
Syntax
lambda [arg1[,arg2,......argn]]:expression
The syntax of the lambda function is a single statement.
Functions 99
Example
# function definition here
>>>mult = lambda val1, val2: val1*val2;
In the given example, the lambda function is defined with two arguments val1 and val2. The expression
val1*val2 does the multiplication of the two values. Now, in function call, we can directly call the mult
function with two valid values as arguments and produce the output as above.
Syntax
return [expression]
Syntax
lambda [arg1[,arg2,......argn]]:expression
The syntax of the lambda function is a single statement.
3. Write a function called ninelines that uses a function threelines to print nine blank
lines. Print twenty seven new lines using this.
Ans. # function definition here
>>>defthreelines():
... print # prints one newline
... print
... print
100 Introduction to Computing & Problem Solving using Python
>>>defninelines():
... threelines() # prints three new lines
... threelines()
... threelines()
Filename : example.py
#! /usr/bin/python
# Comment section.
“””
Docstring section
“””
# import section
Import os
Import sys
def main():
“ docstring for main function “
# the code for solving the problem goes here.
# This section is the standard way to invoke the main function. It makes
the code reusable.
if __name__ == ‘__main__’:
main()
Functions 101
The first line starts with #! Is known as ‘interpreter descriptor’ or ‘shebang’ as short form of ‘sharp bang’.
It is added to have compatibility with linux or unix based systems. In unix based systems, this line identifies
which interpreter to be used to execute this script. But in windows the file is identified as a python script
by extension ‘.py’
Comment section starts with a ‘#’ which is optional. This is where you can put details about script. You
can add any number of lines which starts with ‘#’ here.
Docstring is the section where you document your script. In this section you can write documentation for
the script, such as how to use your script or any other information that users should know to use your script.
It can span into multiple lines. Documentation tools picks docstrings automatically to create documentation
for the module.
Import section and from import section is the right place for adding import statements for importing
needed other modules or functions into this script.
main() is a good place to put all the high level code for solving the problem. The last section will be
common in all script. It invokes the main function only if the module is executed as a script. It prevents the
execution of main function when the module is imported in other scripts.
For example, a script to find the logarithm of a number may look like as follows. Let’s call it logme.py
#! /usr/bin/python
# Program for finding out Logarithm of a given number
“””
Program for finding Logarithm of a number.
Usage:
$ python logme.py
Welcome, this script allows you to find log of a number!
Enter a number: 100
Log of 100 is 2.0
Thank you!
“””
def main():
“reads a number from user and finds log of it”
try:
number = int(raw_input(“Enter a number: “))
except ValueError:
print “Error: given input is not valid, please enter a number.”
return
result = log10(number)
print “Log of {num} is {res}”.format(num=number, res=result)
102 Introduction to Computing & Problem Solving using Python
if __name__== ‘__main__’:
main()
#The End!
For windows:
1. Open cmd
2. Change directory to python folder. (Usually with in C drive)
C:\> cd C:\Python27\
3. Run python script example.py
C:\Python27\> python path\to\logme.py
Syntax
deffunctionname(parameters):
“function_docstring”
statement(s)
return [expression]
● A function is called using the name with which it was defined earlier, followed by a pair of parentheses
(()).
Functions 103
● Type coercion is a process through which Python interpreter automatically converts a value of one type
into a value of another type according to the requirement.
● Python provides a Math module that contains most of the familiar and important mathematical functions.
● A module is a file that contains some predefined Python codes. A module can define functions, classes
and variables. It is a collection of related functions grouped together.
● For importing the math module, we use:
>>> import math
● To use their own functions in Python, users have to define the functions first; this is known as Function
Definition.
● The anonymous functions are the functions that are created using a lambda keyword. They are not defined
as other functions are, i.e., by using def keyword.
● Parameters and arguments are the values or expressions that are passed to the functions between the
parentheses.
● There are four types of formal arguments using which a function can be called.
■
■ Keyword arguments
■ Default arguments
■ Variable-length arguments
● In keyword arguments, the caller recognises the arguments by the parameter’s names. This type of
argument can also be skipped or can also be out of order.
● In default arguments, we can assign a value to a parameter at the time of function definition that will be
considered the default value to that parameter.
✓ FUNCTION: Functions are self-contained programs that perform some particular tasks.
✓ FUNCTION OBJECT: A value created by the definition of a function. A variable which is the name of
the function refers to the function object.
✓ HEADER: The very first line of the function definition.
✓ BODY: The block of statements inside the function definition.
✓ PARAMETER: The variables used to pass some values to a function, defined between parentheses.
✓ FUNCTION CALL: It is a statement which executes the function.
✓ ARGUMENT: It is a value which is provided at the time of function calling. It is specified within
parentheses.
✓ RETURN VALUE: The value returned by the function as output to the caller.
✓ MODULE: A file that contains a collection of related functions and definitions.
✓ IMPORT STATEMENT: It is a type of statement used to import various modules in Python.
104 Introduction to Computing & Problem Solving using Python
PROGRAMS
1. Write a function to find the HCF of some given numbers.
Solution.
>>> def hcf(a, b):
if a > b:
small = b
else:
small = a
for i in range (1, small + 1):
if((a % i == 0) and (b % i == 0)):
hcf = i
return hcf
>>> hcf(20,40)
20 #Output
>>> hcf(529,456)
1 #Output
>>> factors(70)
1 #Output
2
5
7
10
14
35
70
>>> ascii_val_of(‘A’)
(“The ASCII value of ‘A’ is”, 65) #Output
>>> ascii_val_of(‘ ‘) #Finding Ascii value of space
(“The ASCII value of ‘ ‘ is”, 32) #Output
Functions 105
4. Write a function to convert a decimal number to its binary, octal and hexadecimal equivalents.
Solution.
>>> def bin_oct_hex(a):
print(bin(a), “binary equivalent”)
print(oct(a), “octal equivalent”)
print(hex(a), “hexadecimal equivalent”)
6. Write a function to find the sum of several natural numbers using recursion.
Solution.
>>> def sum_rec(n):
if n <= 1:
return n
else:
return n + sum_rec(n-1)
Output:
Welcome to Chap4.py
your options are:
1) Demonstrate conversion
2) Integer to float conversion
3) Mathematical Functions
4) Date and time
5) Quit Chap4.py
1) Demonstrate conversion
2) Integer to float conversion
3) Mathematical Functions
4) Date and time
5) Quit Chap4.py
1) Demonstrate conversion
2) Integer to float conversion
3) Mathematical Functions
4) Date and time
5) Quit Chap4.py
Welcome to Chap4.py
your options are:
1) Demonstrate conversion
2) Integer to float conversion
3) Mathematical Functions
4) Date and time
5) Quit Chap4.py
Welcome to Chap4.py
your options are:
1) Demonstrate conversion
2) Integer to float conversion
3) Mathematical Functions
4) Date and time
5) Quit Chap4.py
Output:
Chapter3.doc
Examples-chapter3.py
Chapter4.py
Sample.py
Functions 109
9. A Python program to implement recursion for factorial of a number that demonstrates the user
defined function and return statement.
Solution.
# Python program to find the factorial of a number using recursion
Output:
Enter a number: 6
Factorial of 6 is 720
Enter a number: -21
Factorial for negative values not exist
Enter a number: 1
Factorial of 1 is 1
Short Questions
1. What is a function in Python? What are the advantages of using a function?
2. What is the difference between user-defined function and built-in function?
3. Write a function which accepts three numbers and returns their multiplication.
4. Write a function which can take any number value and convert it into an integer, float and string.
5. What will be the output of the code given below?
a. str(54.0)
b. print(‘Python version’ + 7)
6. What do you mean by mathematical functions and how can they be used in Python? Explain with the
help of examples.
7. Briefly explain the types of formal arguments using which a function can be called.
8. Write a function that takes exactly two arguments. One argument is the name of the employee, and
the other argument is the PF. The default PF is 30000. Display at least two outputs in support of your
answer.
9. How are parameters passed in Python? By value or by reference.
10. What are anonymous functions in Python?
Functions 111
11. What is type coercion in Python? Explain with the help of an example.
12. Write a function called sixteenlines that uses fourlines to print sixteen blank lines. Print sixty
four new lines using this.
5.1 STRINGS
Strings are one of the most popular data types in Python. Strings are created by enclosing various characters
within quotes. Python does not distinguish between single quotes and double quotes. Creating strings is very
simple in Python.
Example
>>> var1 = ‘Hello Python!’
>>> var2 = ”Welcome to Python Programming!”
>>> var3 = ”””This is triple quoted string”””
>>> print var1
Hello Python # Output
>>> print var2
Welcome to Python Programming # Output
>>> print var3
This is triple quoted string # Output
Strings are of literal or scalar type. The Python interpreter treats them as a single value.
Note Strings are immutable. If you want to change an element of a string, you have to
create a new string.
TIP
Triple quoted strings can span to multiple lines.
Strings and Lists 113
Example
>>> var = “““Welcome # String written in multiple lines
to
Python
Programming”””
>>> print var
Welcome # Output
to
Python
Programming
TIP
In order to access a part of the string, a square bracket operator ([]) must be used.
Example
>>> string = "hello"
>>> letter = var[4]
>>> print letter
o # Output
In the given example, hello is stored in a variable string. Then the element of the string variable
with index number 4 is stored in the letter variable. As we know, in programming, every index starts
with 0. Hence, index 4 means the 5th letter of the string. The 5th letter of the string hello is o. Hence,
o is displayed in output.
Example
Let us now look at an example of how to get the first letter of the string:
>>> letter = string[0]
>>> print letter
h # Output
The first letter of the string, i.e., ‘h’ is displayed by the interpreter.
114 Introduction to Computing & Problem Solving using Python
Example
>>> var = “Hello Python!”
>>> len(var)
13 # Output
Here, we took a string ‘Hello Python!’ and used the len function with it. The len function returned
the value 13 because not only characters, but also special characters and blank spaces are considered in
the string. Therefore, the blank space and exclamation mark in our string will also be counted as elements.
Example
Access the last letter of our string with the help of length.
>>>length = len(var)
>>> last = [length - 1]
>>> print last
! # Output
In this example, we store the length of the string in a variable length to access the last element of our
string. To access the last element, we need the index of last element which is 12 and not 13 because the
index of the string starts with 0 not 1, as we discussed earlier. This is the reason we subtracted 1 from the
length of the string in order to get the last element index.
Alternatively, we can also use negative indices for accessing the string from last. So, the expression
var [-1] yields the last letter of the string and var [-2] yields the second last letter and so on.
Example
>>> var = “Hello world”
>>> last = var[-1]
>>> second_last = var[-2]
>>> print last
d # Output
>>> print second_last
l # Output
Strings and Lists 115
Example
>>> var = ‘Hello Python’
>>> print var[0:4]
Hell # Output
>>> print var[6:12]
Python # Output
In the above example, you can see that in the first case the slice is [0:4], which means that it will take
the 0th element and will extend to the 3rd element, while excluding the 4th element. Similarly, in the second
case where slice is [6:12], it will consider the 6th element and extend to the 11th element.
Example
>>> alphabet = “abcdefghij”
>>> print alphabet[1:8:3]
beh # Output
>>> print alphabet[1:8:2]
bdfh # Output
In the above example, you can see that in the first case the slice is [1:8:3], which means that it will
take the element at 1st index which is b and will extend till the 7th element. Since step is 3, it will print 1st
element, then 4th element and then 7th element. i.e. beh. Similarly, in second case where slice is [1:8:2],
it will print 1st , 3rd, 5th, 7th elements, i.e. bdfh.
116 Introduction to Computing & Problem Solving using Python
Now, if we do not give any value for the index before the colon, i.e., n, then the slice will start from the
first element of the string. Similarly, if we do not give any value for the index, i.e., m after the colon, the
slice will extend to the end of the string.
Example
>>> var = ‘banana’
>>> var[:4]
‘bana’ # Output
>>> var[4:0]
‘na’ # Output
Similarly, if we don’t give any value at both the sides of the colon, i.e., values for n and m are not given
then it will print the whole string.
>>> var[ : ]
'banana' # Output
Now, if the second index, i.e., m, is smaller than the first index, i.e., n, then output will be an empty string
represented by two single quotes:
>>> var = ‘banana’
>>> var[4:3]
‘’ # Output
Now, if we give the value of step as -1 and no value for n and m, then it will print the string in reverse
order. For example,
>>> var = 'banana'
>>> var[ : : -1]
'ananab' # Output
Note An empty string has length 0. Though it does not contain any character, it is still a
string.
Example
>>> var = ‘hello python’
>>> var[0] = ‘p’
Output:
TypeError: ‘str’ object does not support item assignment
Here, we try to change the 0th index of the string to a character p, but the Python interpreter generates
an error.
Strings and Lists 117
Now, the solution to this problem is to generate a new string rather than change the old string.
Example
>>> var = 'hello python'
>>> new_var = 'p' + var[1:]
>>> print new_var
pello python # Output
Note that we cut the slice from the original string and concatenate it with the character we want to insert
in the string. It does not have any effect on the original string.
Example
Let us try the traversal of string using while loop
>>> i=0
>>> while i < len(var): # string was assigned In the example given above
... letter = var[i]
... print letter
... i = i + 1
Output:
h
e
l
l
o
p
y
t
h
o
n
In the given example, we take a variable i and initialise it to 0. Then, we begin a while loop with the
condition i < len(var). At one point of time, the index becomes equal to the length of the string. As a
result, the condition of while loop becomes false and it halts. The last character is displayed with the index
len(var)-1, which will be the last character of the string. Thus, our whole string is traversed and displayed.
118 Introduction to Computing & Problem Solving using Python
p
y
t
h
o
n
TIP
Each time in the -for loop, the next character in the string will be assigned to the variable
char. The loop halts when the last character is processed.
Output:
j
a
c
k
j
o
h
n
Here, we define a function find that takes a string and a character as input (string and char respectively
in the example). A while loop traverses the string until the end and compares every element of the string
with the character passed by the user. If it matches any element of the string then the index of that element
is returned by the function. Otherwise, it returns -1.
Note The return statement in a while loop works in the same way as the break function
does. If the result is found, then it will break the loop and return the result back to the
function.
Example
>>>print “I am 6’2\” tall.” # escape double quotes inside string
I am 6’2” tall. # Output
120 Introduction to Computing & Problem Solving using Python
Note that we use a backslash operator before the 2nd double quotation marks. As a result, the Python
interpreter understands that the quotation marks are a part of the string and should be displayed in output.
Table 5.1 shows various common escape characters.
Example
>>> print “My name is %s and age is %d years.” %(‘John’, 26)
My name is John and age is 26. # Output
%o Octal integer
%x Hexadecimal integer (lowercase letters)
%X Hexadecimal integer (uppercase letters)
%e Exponential notation (with lowercase ‘e’)
%E Exponential notation (with uppercase ‘E’)
%f Floating point real number
%g The shorter of %f and %e
%G The shorter of %f and %E
The following example elaborates the usage of different string formatting operators
>>>print (“the first letter of %s is %c” %(‘python’,’p’))
>>>print(“The sum = %d” %(-15))
>>>print(“The sum = %i” %(-15))
>>>print(“The sum = %u” %(15))
>>>print(“%o is the octal equivalent of %d” %(9,9))
>>>print(“%x is the hexadecimal equivalent of %d” %(12,12))
>>>print(“%X is the hexadecimal equivalent of %d” %(12,12))
>>>print(“%e is the exponential equivalent of %f” %(8.98354,8.98354))
>>>print(“%E is the exponential equivalent of %f” %(8.98354,8.98354))
4. decode(encoding=’UTF-8’,errors=’strict’)
Decodes the string using the codec registered for encoding.
5. encode(encoding=’UTF-8’,errors=’strict’)
Returns encoded string version of string; on error, default is to raise a ValueError unless errors are given
with ‘ignore’ or ‘replace’.
6. endswith(suffix,beg=0,end=len(string))
Determines whether string or a substring of string ends with suffix, returning True if so and False
otherwise.
7. expandstab(tabsize=8)
Expands tab in string to multiple spaces.
8. find(str,beg=0,end=len(string))
Determine whether the str occurs in the string or in a substring of string provided that the starting index is
beg and the ending index is end. If the string is found, it returns the index otherwise returns -1.
9. index(str,beg=0,end=len(string))
Acts in the same way as find(); if str is not found, it raises an exception.
10. isalnum()
If string has at least one character and all characters are alphanumeric, then it returns True and False
otherwise.
11. isalpha()
If string has at least one character and all characters are alphabetic, it returns True and False otherwise.
12. isdigit()
If string contains only numbers, then it returns True and False otherwise.
13. islower()
If string has at least one cased character and all cased characters are in lower case, then it returns True
and False otherwise.
14. isnumeric()
If a Unicode string contains only numeric characters, then it returns True and False otherwise.
15. isspace()
If string contains only whitespace characters, then it returns True and False otherwise.
16. istitle()
If string is properly “titlecased”, then it returns True and False otherwise.
17. isupper()
If string has at least one cased character and all cased characters are in upper case, then it returns True and
False otherwise.
18. join(seq)
Concatenates the string representations of elements in sequence seq into a string with separator string.
19. len(string)
It returns the length of the string.
20. ljust(width[,fillchar])
It returns the padded string with spaces with the original string left-justified to a total of width columns.
21. lower()
It converts all the uppercase letters into lowercase in a string.
22. lstrip()
It removes all the leading whitespaces in a string.
23. maketrans()
It returns a translation table that is to be used in translate function.
Strings and Lists 123
24. max(str)
It returns the maximum alphabetic characters in a string str.
25. min(str)
It returns the minimum alphabetic characters in a string str.
26. replace(old,new[,max])
Replaces all occurrences of old in string with new or at most max occurrences if max provided.
27. rfind(str,beg=0,end=len(string))
It works same as find()but it searches backward in a string.
28. rindex(str,beg=0,end=len(string))
It works same as index()but it searches backward in a string.
29. rjust(width,[,fillchar])
It returns a space-padded string with the original string right-justified to a total of width columns.
30. rstrip()
It removes all trailing whitespaces in a string.
31. split(str=””,num=string.count(str))
It splits string according to delimiter str and returns list of substrings; split into at most num substrings
if provided.
32. splitlines(num=string.count(‘\n’))
It splits string at all NEWLINEs and returns a list of each line with NEWLINEs removed.
33. startswith(str,beg=0,end=len(string))
It determines whether a string or a substring of string begins with substring str; returning True if so
and False otherwise.
34. strip([chars])
It performs both lstrip() and rstrip() on string.
35. swapcase()
It inverts case for all characters in the string.
36. title()
It returns “titlecased” version of string, that is, all words start with uppercase and the rest are in lowercase.
37. translate(table,deletechars=””)
It translates string according to translation table str which is of 256 chars, removing those in the del string.
38. upper()
Converts all lowercase characters into uppercase.
39. zfill(width)
It returns the string left padded with zeros to a total of width characters; intended for numbers, zfill()
retains any sign given (less one zero).
40. isdecimal()
If a Unicode string contains only decimal characters, then it returns True if so and False otherwise.
5.2 LISTS
5.2.1 Values and Accessing Elements
Like strings, lists are also a series of values in Python. In a string, all the values are of character type but in
a list, values can be of any type. The values in a list are called elements or items.
A list is a collection of items or elements; the sequence of data in a list is ordered. The elements or items in
a list can be accessed by their positions, i.e., indices. We have already studied the index in the strings section.
Like all other variables, lists are also defined before they are used. There are several ways of defining or
creating a list. The most convenient way is using square brackets ([]).
Example
>>> list1 = [2,-1,0,-2,8]
>>> list2 = [‘crunchy chocolate’, ‘hello’, ‘python programming’]
The first line list contains only the numerals that are integers. The second line list contains strings.
However, it is not necessary that the lists have homogenous data type elements.
There can be elements of different data types in the list:
>>> list3 = [‘python’, 5.5, 8]
The list given above contains three different types of elements: string, float and integer. A list-type data
item can also be defined inside a list:
>>> list4 = [‘python’, 5.6, [20,40]]
Here, a list is contained in another list. Alternatively, we can say that a list is nested within another list.
Although, this statement doesn’t have any syntax error and also it works, but this is not the correct way
to copy of a list. Let’s understand why this is not a correct way and what is the correct way then?
Basically, what the statement list_original = [1,2,3,4] does is that it makes a variable named
list_original and it points to the list [1,2,3,4] and by the statement list_copy = list_original,
Strings and Lists 125
we are not copying the list but we are just making another variable named list_copy and attach it to the list
pointed by list_original. Hence, logically both variables are pointing to the same list. But by making
a duplicate of a list, we mean that two different lists but they contain same elements. This is illustrated in
Fig. 5.1.
list_original
[1, 2, 3, 4]
list_copy
List
Figure 5.1
In the figure, we can see that both variables are pointing to the same list.
If we modify list_original, then the modification will also take place in list_copy and vice versa.
For Example,
>>> list_original.append(10)
>>> print list_original
[1, 2, 3, 4, 10]
>>> print list_copy
[1, 2, 3, 4, 10]
Now, after understanding the concept of how the list is stored in Python, we will understand the correct
way of making copy of an existing list.
There are two ways to make copy of a list.
1. Using [ : ] operator
2. Using built-in copy function
Using [ : ] operator
>>> list_original = [1,2,3,4]
>>> list_copy = list_original[ : ] # Using [:] operator
>>> print list_copy
[1, 2, 3, 4]
Now, let us make changes in original list and we will see whether the changes take place in copied list
also or not.
>>> list_original.append(10) # Adding element to original
>>> print list_original
[1, 2, 3, 4, 10] # original list changed
>>> print list_copy
[1, 2, 3, 4] # copied list is unaffected
Hence, when we make changes in the original list, the copied list was unaffected by the changes.
Example
>>> from copy import copy #Import library
>>> list_original = [1,2,3,4]
>>> list_copy = copy(list_original) #Copying list
>>> print list_copy
[1, 2, 3, 4]
TIP
An empty list can also be created using enclosing brackets with no elements inside them.
>>> a = []
Example
>>> list = [10,20,30,40]
>>> list[1]
20 # Output
In the given example, we access the 2nd element of the list that has 1 as index number and the interpreter
prints 20.
Now, if we want to change a value in the list given above:
>>> list[3] = 50
>>> print list
[10,20,30,50] # Output
th
Note that the value of the 4 element is changed to 50.
The index number written within the square brackets indicates the distance from the beginning of the
list. Hence, the expression list[0] indicates the starting element (a distance zero from the beginning) and
list[1] indicates the second element (a distance of one from the beginning). This concept is illustrated
in Fig. 5.2.
Strings and Lists 127
list
8 –2 –3 –6
0 1 2 3
In Fig. 5.2, the numbers below each list element indicate the index of that element.
Indices in a list work in the same way as in strings:
● Any integer expression can be used as an index number.
● If any element that does not exist in the list is accessed, there will be an IndexError.
● If the indices are given in negative, then counting happens from the end of the list. (backward)
Note Every element or item inside a list always has an index number through which it is
accessed.
Example
>>> list = [1,2,3,4]
>>> list[1]
2 # Output
>>> list[3]
4 # Output
Example
>>> list = [1,2,3,4]
>>> list[2] = 6
>>> print list
[1,2,6,4] # Output
128 Introduction to Computing & Problem Solving using Python
Example
>>> list = [‘a’,’b’,’c’,’d’]
>>> for x in list:
... print x
Output:
a
b
c
d
In the example, we define a list of some elements. Using for loop, the list is traversed and all the elements
of the list are printed.
The for loop is used mostly when we want to read the elements of the list. However, in order to write
to a list, we need to access the indices of the elements in a list. The following example traverses the list and
also adds 4 to every element of the list.
>>> list = [10,20,30,40]
>>> for i in range(len(list)):
... list[i] = list[i] + 4
>>> print list
[14,24,34,44] # Output
Here, we make use of the range and len functions on a list, where len returns the length of the list
and range returns the list of indices. Hence, for each iteration of the loop, the variable i gets the index of
the next element and the statement defined in the body of for loop reads the old value at the index i and
assigns it a new value.
The pop operator deletes the element on the provided index and stores that element in a variable for
further use.
2. del Operator The del operator deletes the value on the provided index, but it does not store the value
for further use.
>>> list = [‘w’,‘x’,’y’,’z’]
>>> del list(1)
>>> print list
[‘w’, ‘y’, ‘z’] # Output
3. remove Operator We use the remove operator if we know the item that we want to remove or delete
from the list (but not the index).
>>> list = [10,20,30,40]
>>> list.remove(10)
>>> print list
[20,30,40] # Output
Note In order to delete more than one value from a list, del operator with slicing is used.
>>> list = [1,2,3,4,5,6,7,8]
>>> del list[1:3]
>>> print list
[1,4,5,6,7,8] # Output
Example
>>> list = [1,2,3]
>>> for x in list:
... print x
Output:
1
2
3
Example
>>> list1 = [10,20,30,40]
>>> list2 = [50,60,70]
>>> list3 = list1 + list2
>>> print list3
[10,20,30,40,50,60,70] # Output
In the given example, there are two lists, list1 and list2. Here, list1 and list2 are concatenated
using + operator between them and the resulting list is stored in the variable list3. Now, when we print
list3, it gives the concatenation of list1 and list2.
2. Repetition The repetition operator works as suggested by its name; it repeats the list for a given number
of times. Repetition is performed by the * operator.
Example
>>> list1 = [1,2,3]
>>> list1 * 4
[1,2,3,1,2,3,1,2,3,1,2,3] # Output
>>> [2] * 6
[2,2,2,2,2,2] # Output
In the given example, the list[1,2,3] was repeated 4 times and the list[2] was repeated 6 times.
3. In Operator The In operator tells the user whether the given string exists in the list or not. It gives
a Boolean output, i.e., True or False. If the given input exists in the string, it gives True as output,
otherwise, False.
Example 1
>>> list = [‘Hello’, ‘Python’, ‘Program’]
>>> ‘Hello’ in list
True # Output
>>> ‘World’ in list
False # Output
Example 2
>>> list = [10,20,30,40]
>>> 10 in list
True # Output
>>> 50 in list
False # Output
Strings and Lists 131
1. append Method This method can add a new element or item to an existing list.
Example
>>> list = [1,2,3,4,]
>>> list.append(0)
>>> print list
[1,2,3,4,0] # Output
2. extend Method This method works like concatenation. It takes a list as an argument and adds it to the
end of another list.
Example
>>> list1 = [‘x’,’y’,’z’]
>>> list2 = [1,2,3]
>>> list1.extend(list2)
>>> print list1
[‘x’, ‘y’, ‘z’, 1, 2, 3] # Output
132 Introduction to Computing & Problem Solving using Python
In this example, list1 is modified by adding list2 at the end of it while list2 is left as it is.
3. sort Method This method arranges the list in ascending order.
Example
>>> list=[4,2,5,8,1,9]
>>> list.sort()
>>> print list
[1, 2, 4, 5, 8, 9] # Output
● len is a built-in function in Python, which when used with a string, returns the length or the number of
characters in the string.
● Traversal is a process in which we access all the elements of the string one by one using some conditional
statements such as for loop, while loop, etc.
● The return statement in a while loop works in the same way as the break function does. If the result is
found then it will break the loop and return the result back to the function.
● The backslash character (\) is used to escape characters. It converts difficult-to-type characters into a
string.
● The strings in Python have one unique built-in operation: the %operator (modulo).
● A list is a collection of items or elements; the sequence of data in a list is ordered.
● The elements or items in a list can be accessed by their positions, i.e., indices.
● An empty list can also be created by enclosing brackets with no elements inside them.
● Lists are mutable which means that we can change the value of any element inside the list at any point
of time.
● If we know the index of the element that we want to delete then we can use the pop operator.
● If we know the item that we want to remove or delete from the list (but not the index) then we use remove
operator.
● The repetition operator works in the way its name suggests; it repeats the list a given number of times.
Repetition is performed by the * operator.
● extend method works in a way similar to concatenation. It takes a list as an argument and adds this list
to the end of another list.
● sort method arranges the list in ascending order.
● append method can add a new element or item to an existing list.
✓ REFERENCE: The mapping between a variable and its value is called reference.
✓ DELIMITER: It is a character or string used to specify where a string must be split.
PROGRAMS
1. Write a program to find duplicate characters in a given string.
Solution.
>>> str = ‘java’
>>> first_time = []
>>> dup = []
>>> for i in str:
if i not in first_time:
first_time.append(i)
else:
if i not in dup:
dup.append(i)
print “”.join(dup)
a #Output
Output:
In this line we display the single quotes ‘ ‘
Length of the strings: str and str2
14
17
First occurrences of o in str and r in str2 is
4
Strings and Lists 137
2
number of occurrences in str and str2 are
2
2
str string slice operations
thon pr
to r
thon
thon pr
margorp nohtyp
str2 string slice operations
tring
rn
ring o
ring o
snoitarepo gnirts
strings str and str2 in upper case
PYTHON PROGRAM
STRING OPERATIONS
strings str and str2 in lower case
python program
string operations
str and str2 string functions starts with
True
False
str and str2 ends with
False
True
str and str2 split operations
[‘python’, ‘program’]
[‘string’, ‘operations’]
string concatenation
python programstring operations
>>> d = c.split()
>>> print d
>>> print “slice of d”
>>> print d[1:3]
>>> print d[:2]
>>> h = ‘python-program-is-easy’
>>> print h
>>> delim = ‘-’
>>> h.split(delim)
>>> print “After split and delim”
>>> print h
>>> delim = ‘***’
>>> delim.join(h)
>>> print “join () on lsts”
>>> print h
>>> print “cmp () on lsts”
>>> print cmp(lst1, lst2)
>>> print cmp(lst2, lst1)
>>> lst4 = lst3 + [786];
>>> print cmp(lst3, lst4)
>>> print “Max values”
>>> print “Max value element : “, max(lst1)
>>> print “Max value element : “, max(lst2)
>>> print “Max value element : “, max(lst3)
>>> print “Min() values of lsts”
>>> print “min value element : “, min(lst1)
>>> print “min value element : “, min(lst2)
>>> print “min value element : “, min(lst3)
>>> print “new lst5 from existing lst2”
>>> lst5 = list(lst2)
>>> print “pop on lst”
>>> print”list elements”, lst5
>>> print “lst2”, lst2.pop()
>>> print “lst2:”, lst2.pop(2)
>>> print “reverse() on lst”
>>> lst2.reverse()
>>> print “sort() on lst”
>>> print lst2
>>> lst2.sort()
>>> print “After sort”, lst2
>>> print “end of chap5”
Output:
various list operations
lst1[0]: java
list split operations
lst2[1:5]: [6, 9, 12, 15]
value aviliable at index 2 :
1995
Insert elements into the list
140 Introduction to Computing & Problem Solving using Python
-1
-1
Max values
Max value element : java
Max value element : 181818
Max value element : s
Min() values of lsts
min value element : java
min value element : 9
min value element : q
new lst5 from exisiting lst2
pop on lst
list elements [9, 18, 27, 36, 45, ‘181818’]
lst2 181818
lst2: 27
reverse() on lst
sort() on lst
[45, 36, 18, 9]
After sort [9, 18, 36, 45]
end of chap5
Short Questions
1. What is string in Python? Why is len function used in string?
2. How we can access the last letter of the string with the help of length? Explain with an example.
3. What is the_slice operator? Explain with an example.
4. Write a program to search a character in a string.
5. What will be the output of the given code?
>>> string = “computer”
>>> letter = string[6]
>>> print letter
6. What will be the output of the given code? Give the reason.
>>> string = ‘keyboard’
>>> string[6:4]
7. Write a Python program to get a single string from two given strings separated by a space, and swap
the first two characters of each string.
8. What will be the output of the given code?
>>>str1 = “Hello World!”
>>>str2 = ‘Welcome to Programming’
Strings and Lists 145
6.1 TUPLES
In Python Programming, tuples are just like the lists we have seen in earlier chapters. Tuples are the sequence
or series values of different types separated by commas (,). Just like strings and lists, values in tuples can
also be accesed by their index values, which are integers starting from 0. The main difference between lists
and tuples is that in case of a list, a value in the list can be replaced with another anytime after its creation.
Whereas in tuples, the values in it cannot be replaced with another, once tuples are created. List allows us to
add new items to it. But tuple does not allow us to add new items, once it is created.
Example
The names of the months in a year can be defined in a tuple:
>>> months = (‘January’, ‘February’, ‘March’, ‘April’, ‘May’, ‘June’,
‘July’, ‘August’, ‘September’, ‘October’, ‘November’, ‘December’)
Examples
1. A tuple with integer data items
>>> tuple = (4,2,9,1)
>>> print tuple
(4,2,9,1) # Output
Tuples and Dictionaries 149
3. Nested tuple
>>>nested_tuple = (“Python”, [1,4,2],[“john”,3.9])
>>> print nested_tuple
(‘Python’, [1, 4, 2], [‘john’, 3.9]) # Output
Note Creating a tuple with one element is somewhat different. When we are creating a
tuple with one element, we need to add a final comma after the item or element in order to
complete the assignment of the tuple.
Example
>>>tuple = (“home”)
>>>type(tuple)
<type ‘str’> # Output
In the above assignment statement, we are trying to create a tuple with only one item, but when we print
its type in Python interpreter, the type is not tuple but str.
Now, consider the following code:
>>>tuple = (“home”,)
>>>type(tuple)
<type ‘tuple’> # Output
Here, we added a final comma after the element “home” and the python interpreter takes the tuple as
the type tuple.
This can also be done without parentheses:
>>>tuple = “home”,
>>>type(tuple)
<type ‘tuple’> # Output
Note We can also use slicing in order to print the continuous values in a tuple.
In the Example 1, we can see that the output does not comprise any braces, that is, because a single element
or item is being retrieved from the tuple whereas in the Example 2 above, tuples are cutting into parts i.e.
slicing. The output is also a tuple which we get after slicing and the tuples in Python programming language
are written in parentheses.
TIP
As with the lists and strings, we can access the elements of the tuple. However, unlike
strings and lists, we cannot update or delete the values in the tuple—tuples are immutable.
Example
>>>tuple = (10,20,30,40)
>>>tuple[1]
20 # Output
>>>tuple[3]
40 # Output
Example
# declaring a tuple
>>>tup = (12, 15, “Python”, 2.3)
# change the 3rd element “Python” to “Hello”
>>>tup[2] = “Hello”
TypeError: ‘tuple’ object does not support item assignment
In the given example, a tuple tup is declared with some items. Now, if we try changing the 3rd element
“Python” to “Hello” using the assignment operator, the Python interpreter generates an error. From this
example, it is clear that the values of tuple elements cannot be changed afterwards.
Example
# creating a tuple
>>>Anil = (‘221’,’Anil’,’Rahul’,’Delhi’,1971,’Jaipur Gwalior’)
# tuple assignment
>>>(id,fst_name,lst_name,city,year_of_birth,birth_place) = Anil
152 Introduction to Computing & Problem Solving using Python
Here, we created a tuple named john, with 7 elements inside it. Now, in the next statement, the value of
each element of this tuple is assigned to the respective variables. It can be seen that the number of variables
to the left of assignment is seven and the number of items in the tuple is also seven; hence, the number of
values are matching and the assignment is successful.
Now,
>>>print id
221 # Output
>>>print fst_name
John # Output
>>>print year_of_birth
1971 # Output
>>>print birth_place
atlanta Georgia # Output
In the assignment statement, each variable is assigned with a value that was inside the tuple and can be
accessed individually. If we had used the traditional assignment procedure, it would have been done in 7
lines of statement. With the help of tuple assignment, it is done in a one-line statement.
Similarly, sometimes we need to swap the values of two variables in the program. With the traditional
approach, this can be done by using a temporary variable for swapping the values of two variables.
Example
>>>temp = x
>>> x = y
>>> y = temp
In order to swap the values of variables x and y, we need a temporary variable temp. However, this
problem can be solved much more conveniently with tuple assignment.
>>>x = 3
>>>y = 4
>>>x , y = y , x # Using tuple assignment
>>>print x
4 # Output
>>>print y
3 # Output
Hence, with the use of tuple assignment approach, there is no need to use any temporary variable to swap
values of two variables. All it takes is one simple statement.
Note The number of variables on the left side of the assignment must match the number
of values on the right side of the assignment.
>>>x,y = 1,2,3,4
Traceback (most recent call last): # Output
File “<pyshell#62>”, line 1, in <module>
x,y = 1,2,3,4
ValueError: too many values to unpack
Tuples and Dictionaries 153
Example
>>>defdiv_mod(a,b): # defining function
... quotient = a/b
... remainder = a%b
... return quotient,remainder # function returning two values
# function calling
>>>x = 10
>>>y = 3
>>>t = div_mod(x,y)
>>>print t
(3, 1) # Output
>>>type(t)
<type ‘tuple’> # Output
In the given example, we have defined the function div_mod, which calculates the quotient and remainder.
It returns two values, the quotient and the remainder respectively. Now, at the time of calling the function, a
tuple needs to store the values returned by the function. Hence, we have taken a variable that calls the function
div_mod and stores the values (3,1), which, in our example, are quotient and remainder respectively.
When we tried to see the type of the variable t, it was tuple.
We can also use the tuple assignment approach in order to print the quotient and the remainder separately.
>>>quot, rem = div_mod(10,3)
>>> print quot
3 # Output
>>> print rem
1 # Output
Here, we have taken two variables at the left side which are quot and rem. Now, when the function div_
mod returns the values of quotient and remainder, the values will be stored in quot and rem respectively.
Now, we will see an example of a function that returns tuple as return value.
Example
>>>defmax_min(t):
... return max(t),min(t)
154 Introduction to Computing & Problem Solving using Python
max and min are the built-in functions in Python which return the maximum and minimum elements
from a sequence. We have defined a function max_min that returns both the values.
>>>a = (10,3,2,100,72,67)
>>>max_min(a)
(100, 2) # Output
Example
>>>def traverse(*t):
... i=0
... while i<len(t):
... print t[i]
... i=i+1
>>>traverse(1,2,3,4,5)
Output:
1
2
3
4
5
In the given example, we have defined a function traverse with argument *t, which means it can take
any number of arguments and will print each of them one by one.
Similarly, we know that the opposite of collect is scatter. In order to pass a series of arguments to a
function, we need to simply use * before the arguments.
For example, the function div_mod that was discussed in earlier section takes exactly two arguments;
but it does not work when we pass a tuple to it.
>>>t = (10,3)
>>>div_mod(t)
Traceback (most recent call last): # Output
File “<pyshell#142>”, line 1, in <module>
div_mod(t)
TypeError: div_mod() takes exactly 2 arguments (1 given)
To make it work with a tuple, it is necessary to scatter the values of the tuple.
>>>div_mod(*t)
(3, 1) # Output
We use * before t while passing an argument to the function div_mod. It scatters the values (10, 3)
in two values; the function accepts these arguments and gives the result.
Tuples and Dictionaries 155
TIP
When the asterisk (*) is used before the arguments at the time of function definition, it
collects all the calling function arguments in a tuple and when it is used at the time of
calling, it scatters the values of the tuple.
2. Write a function called sumall that takes any number of arguments and returns their
sum.
Ans. >>> def sumall(*t):
... i=0
... sum=0
... whilei<len(t):
... sum = sum + t[i]
... i = i + 1
... return sum
>>>sumall(1,2,3,4,5,6,7)
28 # Output
3. Write a function called circleinfo which takes the radius of circle as argument and
returns the area and circumference of the circle.
Ans. >>>defcircleinfo(r):
... c=2 * 3.14159 * r
... a=3.14159 * r * r
... return (c,a)
>>>circleinfo(10)
(62.8318, 314.159) # Output
Example
>>>t1 = (1,2,3,4)
>>>t2 = (5,6,7,8)
>>>t3 = t1 + t2
>>>print t3
(1, 2, 3, 4, 5, 6, 7, 8) # Output
In this example, there are two tuples, t1 and t2. Tuples t1 and t2 are concatenated using + operator
between them and the resulting tuple is stored in the variable t3. Now, when we print t3, it gives the
concatenation of t1 and t2.
2. Repetition The repetition operator works as its name suggests; it repeats the tuples a given number of
times. Repetition is performed by the* operator in Python.
Example
>>>tuple = (‘ok’,)
>>>tuple * 5
(‘ok’, ‘ok’, ‘ok’, ‘ok’, ‘ok’) # Output
>>>(‘Hello’,) * 3
(‘Hello’, ‘Hello’, ‘Hello’) # Output
Note that, the tuple (‘ok’,) was repeated 5 times and the tuple (‘Hello’,) was repeated 3 times.
3. in Operator The in operator also works on tuples. It tells user that the given element exists in the tuple
or not. It gives a Boolean output, that is, TRUE or FALSE. If the given input exists in the tuple, it gives the
TRUE as output, otherwise FALSE.
Example 1
>>>tuple = (10,20,30,40)
>>>20 in tuple
True # Output
>>>50 in tuple
False # Output
Example 2
>>>tuple = (‘anil’, ‘rahul’, ‘rohan’)
>>> ‘james’ in tuple
False # Output
>>> ‘rohan’ in tuple
True # Output
4. Iteration Iteration can be done in tuples using for loop. It helps in traversing the tuple.
Tuples and Dictionaries 157
Example
>>>tuple = (1,2,3,4,5,6)
>>>for x in tuple:
... print x
Output:
1
2
3
4
5
6
Example
>>> tuple1 = (‘physics’,’chemistry’,’mathematics’)
>>> tuple2 = (10,20,30,40,50)
>>>cmp(tuple1,tuple2)
1 # Output
>>>cmp(tuple2,tuple1)
-1 # Output
>>>len(tuple1)
3 # Output
>>>len(tuple2)
5 # Output
>>>zip(tuple1,tuple2)
[(‘physics’, 10), (‘chemistry’, 20), (‘mathematics’, 30)] # Output
>>>max(tuple1)
‘physics’ # Output
>>>max(tuple2)
50 # Output
>>>min(tuple1)
‘chemistry’ # Output
>>>min(tuple2)
10 # Output
158 Introduction to Computing & Problem Solving using Python
In the above example, physics is max element of tuple1 because if we compare the first letter of all
the words in the tuple then p is greater than c and m. Hence, the comparison stops here and physics is
declared as the max element of the tuple. Similarly, chemistry is the min element of this tuple.
Note Zip is a built-in function that takes two or more sequences and “zips” them into a
list of tuples where each tuple contains one element from each sequence.
TIP
When there are different numbers of elements in the tuples i.e. if the length of the tuples
are not same then the resulting tuple after applying the zip function will have the length
of shorter tuple.
Example
>>> s = (‘Hello’) # Length is 5
>>> t = (‘Python’) # Length is 6
>>> zip(s,t)
[(‘H’, ‘P’), (‘e’, ‘y’), (‘l’, ‘t’), (‘l’, ‘h’), (‘o’, ‘o’)]
# Resulting tuple has length 5 equal to s
Example
>>>t1 = (10,20,30)
>>>t2 = (50,60)
>>>t3 = t1 + t2
>>>print t3
(10, 20, 30, 50, 60) # Output
Iteration:
Iteration is done in tuples using for loop. It helps in traversing the tuple.
2. Give one-one example for zip, max and min methods.
Ans. >>>tuple1 = (‘a’,’b’,’c’)
>>>tuple2 = (1,2,3)
>>>max(tuple2)
Tuples and Dictionaries 159
3 # Output
>>>min(tuple1)
‘a’ # Output
>>>zip(tuple1,tuple2)
[(‘a’, 1), (‘b’, 2), (‘c’, 3)] # Output
6.2 DICTIONARIES
The Python dictionary is an unordered collection of items or elements. All other compound data types in
Python have only values as their elements or items whereas the dictionary has a key: value pair. Each value is
associated with a key. In the list and the tuple, there are indices that are only of integer type but in dictionary,
we have keys and they can be of any type.
Dictionary is said to be a mapping between some set of keys and values. Each key is associated to a value.
The mapping of a key and value is called as a key-value pair and together they are called one item or element.
A key and its value are separated by a colon (:) between them. The items or elements in a dictionary are
separated by commas and all the elements must be enclosed in curly braces. A pair of curly braces with no
values in between is known as an empty dictionary.
The values in a dictionary can be duplicated, but the keys in the dictionary are unique.
Example
Empty Dictionary
>>> dict1 = {}
>>>print dict1
{} # Output
In the above examples, we have seen many types of ways for creating a dictionary in Python programming
language. One thing to be noticed in initialization of dictionary is that the values of keys can be given in any
order but on printing the dictionary, it prints the sorted order of keys. This is because the dictionary has an
internal mechanism to sort the keys and then print them.
160 Introduction to Computing & Problem Solving using Python
Example
>>> d1 = dict({1:’red’, 2:’yellow’, 3:’green’})
>>> d2 = dict([(1,’red’), (2,’yellow’),(3,’green’)])
>>> d3 = dict(one=1, two=2, three=3)
>>> print d3
{‘three’: 3, ‘two’: 2, ‘one’: 1}
In the above example, three dictionaries d1, d2 and d3 are initialized using the built-in dict function
in the Python programming language.
TIP
When we try to access a key that does not exist in the dictionary, an error occurs.
>>> print dict1[‘address’]
Traceback (most recent call last): # Output
File “<pyshell#19>”, line 1, in <module>
print dict1[‘address’]
KeyError: ‘address’
>>> dict1.get(‘address’)
get() method returns None, which means nothing, when there is no value in the dictionary stored against
the given key. get() also allows us to specify custom default value.
Tuples and Dictionaries 161
Example
>>> dict1 = {‘name’ : ‘John’, ‘age’ : 27}
>>> dict1.get(“address”,0) # Default value is 0
0
Here, we have searched for a key ‘address’ which is not present in the dictionary. get() function
therefore gives the default value which is 0.
Example
>>> dict1 = {‘name’ : ‘John’, ‘age’ : 27}
>>> dict1[‘age’] = 30 # updating a value
>>> print dict
{‘age’: 30, ‘name’: ‘John’} # Output
>>> dict1[‘address’] = ‘Alaska’ # adding a key: value
>>>print dict1
{‘age’: 30, ‘name’: ‘John’, ‘address’: ‘Alaska’} # Output
Note that we tried to reassign the value ‘30’ to the key ‘age’, Python interpreter first searches the key in
the dictionary. In our example, the key ‘age’ exists. Hence, the value of ‘age’ is updated to 30. However,
in the next statement, it does not find the key ‘address’; hence, the key: value ‘address’: ‘Alaska’
is added to the dictionary.
162 Introduction to Computing & Problem Solving using Python
Example
>>>dict_cubes = {1:1, 2:8, 3:9, 4:64, 5:125, 6:216}
We have seen many examples of deleting items from a dictionary. When the clear() method was used,
all the items were removed and an empty dictionary was left. When the del method was used, the dictionary
was deleted from the memory.
Keys have some restrictions while defining them. There are two important points to be kept in mind about
keys which are as follows:
1. One key in a dictionary cannot have two values, i.e., duplicate keys are not allowed in the dictionary;
they must be unique. Whenever duplicate keys are assigned values in a dictionary, the latest value is
considered and stored whereas the previous one is lost.
Example
>>> dict1 = {‘Name’:’John’,’Age’:30,’Name’:’Jinnie’}
>>> print dict1[‘Name’]
Jinnie # Output
In the above example, two values have been assigned to the same key ‘Name’. However, when we
print the dictionary, only the latest one, i.e.,‘Jinnie’ is stored whereas ‘John’ is lost.
2. Keys are immutable, i.e., we can use string, integers or tuples for dictionary keys, but something like
[‘key’] is not valid.
Example
>>> dict1 = {[‘Name’]:’John’,’Age’:30}
Note that when we tried to input a key [‘Name’], Python interpreter gives an error message.
Example
We will define a function print_dict. Whenever a dictionary is passed as an argument to this
function, it will print the keys and values of the dictionary.
>>>defprint_dict(d):
... for c in d:
... print c,d[c]
Output:
1 a
2 b
3 c
4 d
5 e
6 f
7 g
8 h
This example prints the key: value pairs in the dictionary dict.
Note Traversing in the dictionary is done on the basis of keys because they are unique.
2. Membership Using the membership operator (in and not in), we can test whether a key is in the
dictionary or not. We have seen the in operator earlier as well in the list and the tuple. It takes an input key
and finds the key in the dictionary. If the key is found, then it returns True, otherwise, False.
Example
>>>cubes = {1:1, 2:8, 3:27, 4:64, 5:125, 6:216}
>>>3 in cubes
True # Output
>>>7 not in cubes
True # Output
>>>10 in cubes
False # Output
Tuples and Dictionaries 165
Example
>>>cubes = {1:1, 2:8, 3:27, 4:64, 5:125, 6:216}
>>>all(cubes)
True # Output
>>>any(cubes)
True # Output
>>>len(cubes)
6 # Output
>>>sorted(cubes)
[1, 2, 3, 4, 5, 6] # Output
>>>str(cubes)
‘{1: 1, 2: 8, 3: 27, 4: 64, 5: 125, 6: 216}’ # Output
166 Introduction to Computing & Problem Solving using Python
● The values in a dictionary are not unique and can be duplicated, but the keys in the dictionary are unique.
● The value of the key enclosed within square brackets is used to access the elements from a dictionary. An
alternative method of accessing the elements is the get() method, which is used with the key.
● The difference between the accessing methods of dictionary is that when the key is not found in dictionary,
it returns none instead of KeyError.
● Dictionaries are mutable and thus the elements or values can be modified.
● Four methods are used to delete the elements from the dictionary:
1. pop()
2. popitem()
3. clear()
4. del
✓ TUPLE: Tuples, just like lists, are the sequence or series of different types of values that are separated
by commas (,).
✓ TUPLE ASSIGNMENT: It allows assignment of values to a tuple of variables on the left side of
assignment from the tuple of values on the right side of the assignment.
✓ VARIABLE-LENGTH ARGUMENT TUPLES: A variable number of arguments can also be passed
to a function. A variable name which is preceded by an asterisk (*) collects the arguments into a tuple.
✓ CONCATENATION: This operator works in tuples in the same way as in lists. This operator concatenates
two tuples. This is done by the + operator in Python.
✓ REPETITION: This operator repeats the tuples a given number of times. Repetition is performed by *
operator.
✓ in OPERATOR: This operator tells the user whether the given element exists in the tuple or not. It gives
a Boolean output, i.e., TRUE or FALSE.
✓ ITERATION: Iteration can be done in tuples using for loop. It helps in traversing the tuple.
✓ len(tuple): It returns the length of the tuple.
✓ cmp(tuple1, tuple2): It compares the items of two tuples.
✓ max(tuple): It returns the largest value among the elements in a tuple.
✓ min(tuple): It returns the smallest value among the elements in a tuple.
✓ tuple(seq): It converts a list into a tuple.
✓ zip(tuple1, tuple2): It ‘zips’ elements from two tuples into a list of tuples.
✓ DICTIONARY: The Python dictionary is an unordered collection of items or elements. The dictionary
has a key: value pair.
✓ KEY: It is used to get the value in the dictionary.
✓ KEY-VALUE: This pair represents the items in the dictionary.
1. dict():This function is used to create a dictionary.
168 Introduction to Computing & Problem Solving using Python
2. get(): This method is used with the key to access the value in a dictionary.
3. pop(): This method removes the item from the dictionary and returns the value of the item.
4. popitem(): This method is used to delete and return an arbitrary item from the dictionary.
5. clear(): This method removes all the items from the dictionary.
6. del: It is used to delete the dictionary itself.
✓ IMMUTABLE: It is the type in which elements cannot be modified. Tuples are immutable.
✓ MUTABLE: It is the type in which elements are modified. Dictionaries are mutable.
1. len(dict): It returns the number of items (length) in the dictionary.
2. cmp(dict1,dict2): It compares the items of two dictionaries.
3. sorted(dict): It returns the sorted list of keys.
4. str(dict): It produces a printable string representation of dictionary.
PROGRAMS
1. Given an integral number n, write a program to generate a dictionary that contains (i, i*i) such that
i is an integral number between 1 and n (both included). The program should then print the dictionary.
Suppose the following input is supplied to the program:
7
Then, the output should be:
{1:1, 2:4, 3:9, 4:16, 5:25, 6:36, 7:49}
Solution:
>>>n = int(raw_input())
>>>d = dict()
>>>for i in range(1,n+1):
d[i] = i*i
print d
2. Define a function that prints a dictionary where the keys are numbers between 1 and 4 (both
included) and the values are cubes of the keys.
Solution:
>>>def dictionary():
n=dict()
n[1]=1**3
n[2]=2**3
n[3]=3**3
n[4]=4**3
print n
>>>dictionary()
{1: 1, 2: 8, 3: 27, 4: 64} #Output
Tuples and Dictionaries 169
3. Consider the tuple (1,3,5,7,9,2,4,6,8,10). Write a program to print half its values in one line and the
other half in the next line.
Solution:
>>>tup = (1,3,5,7,9,2,4,6,8,10)
>>>tup1 = tup[:5]
>>>tup2 = tup[5:]
>>>print tup1
(1,3,5,7,9) #Output
>>> print tup2
(2,4,6,8,10) #Output
4. Consider the tuple (12, 7, 38, 56, 78). Write a program to print another tuple whose values are even
numbers in the given tuple.
Solution:
>>> tup = (12,7,38,56,78)
>>> even_list = list()
>>> for i in tup:
if i % 2 == 0:
even_list.append(i)
print tuple(even_list)
5. Define a function that prints a tuple whose values are the cube of a number between 1 and 15 (both
included).
Solution:
>>> def printTup():
l = list()
for i in range(1,16):
l.append(i**3)
print tuple(l)
>>> printTup()
(1, 8, 27, 64, 125, 216, 343, 512, 729, 1000, 1331, 1728, 2197, 2744,
3375) # Output
Output:
tpl is empty ()
displaying the elements in tuple1 (1, 2, 3, 5, 7, 11)
displaying the elements in tuple2 (‘aaa’, ‘pqr’, ‘uvw’, ‘zzz’)
creating tpl3 from tpl1 and tpl2
displaying the elements in tuple3
(1, 2, 3, 5, 7, 11, ‘aaa’, ‘pqr’, ‘uvw’, ‘zzz’)
Display the lengths of the tuple
6
4
Max and Min functions on tuple
11
zzz
1
aaa
using in for tpl3 and tpl2
uvw found
9 not found
Using the index on the tuples
(2, 3, 5, 7, 11, ‘aaa’, ‘pqr’, ‘uvw’, ‘zzz’)
(‘aaa’,)
(5, 7, 11, ‘aaa’, ‘pqr’, ‘uvw’)
print the index value of python in tpl4
prin the index value of 3 in tpl1
(3, ‘python’)
Note When a tuple does not exist we get a name error and when an element does not exist
inside a tuple with an index method an error is generated. We need to be more conscious in
using the index method over tuples.
172 Introduction to Computing & Problem Solving using Python
Output:
dicti[‘Lang’]:
Python
dicti[‘Chap’]:
6
dicti[‘Dictionary’]:
Traceback (most recent call last):
dicti[‘Chap’]:
8
dicti[‘Topic’]:
Dictionary topic
{‘Topic’: ‘Dictionary topic’, ‘Chap’: 8}
dicti1[‘Chap’]: 11
dicti1[‘Topic’]:
Traceback (most recent call last):
Line 27, in <module>
print “dicti1[‘Topic’]: “, dicti1[‘Topic’]
KeyError: ‘Topic’
dicti2[‘Lang’]: c
cmp () on dictionaries
Return Value : -1
Return Value : -1
Return Value : -1
len() on dictionaries
Length : 2
str() on dictionaries
Equivalent String : {‘Lang’: ‘Python’, ‘Chap’: 11}
type() on dictionaries
Variable Type : <type ‘dict’>
174 Introduction to Computing & Problem Solving using Python
Start Len : 2
clear() on dictionaries
End Len : 0
copy () on dictionaries
seq on dictionaries
New dictionaries : % s
{‘lang’: None, ‘chap’: None, ‘program’: None}
New Dictiionary : %s
{‘lang’: 10, ‘chap’: 10, ‘program’: 10}
New Dictiinary : %s
{‘lang’: 10, ‘chap’: 10, ‘program’: 10}
New Dictiionary : {‘lang’: None, ‘chap’: None, ‘program’: None}
New Dictiionary : {‘lang’: 10, ‘chap’: 10, ‘program’: 10}
Value : None
Value : Never
Value : False
Value : False
Value : [(‘lang’, 10), (‘chap’, 10), (‘program’, 10)]
Value : [‘lang’, ‘chap’, ‘program’]
Value : None
Value : None
Value : {‘Lang’: ‘c’, ‘Chap’: 15}
Value : [‘c’, 15]
14. Which core data type in Python is an unordered collection of key-value pairs?
a. Tuple b. dictionary
c. function d. list
15. In which of the following operators are dictionaries enclosed?
a. { } b. ( )
c. [ ] d. <>
16. Which of the following represent keys in the dictionary?
a. function or list b. numbers or list
c. strings or functions d. numbers or strings
17. Which operator is used to access the values in dictionary?
a. { } b. ( )
c. [ ] d. <>
18. Which of the following statements will not create a dictionary?
a. {245:”book”, 1234:code} b. (“book”:245, “code”:1234)
c. { } d. {“book”:245, “code”:1234}
19. Which of the following forms do dictionaries appear in?
a. keys and values b. only keys
c. list and keys d. only values
20. What are the keys in the following code?
dictionary = {“book”:245, “code”:1234}
a. 245 and 1234 b. “book” and “code”
c. “book”, 245, “code” and 1234 d. (“book”:245, “code”:1234)
21. Which of the following methods is used to remove entire elements of a dictionary?
a. remove() b. remove{}
c. clear() d. clear{}
22. What will be the output of the following code?
dict = {‘name’: ‘ravi’, ‘age’:35}
“ravi” in dict
a. True b. false
c. error d. none
23. Which of the following functions of the dictionary gets all the keys from the dictionary?
a. dict.key() b. dict.keys()
c. allkeys() d. getkeys()
24. What will be the output of the following code?
dict = {‘name’,‘ravi’,‘age’:35}
>>>print dic[‘age’]
a. Age b. 35
c. Ravi d. error
25. What will be the output of the following code?
dict = {‘name’:’ravi’, ‘age’:35}
>>>print dict[‘age’]
a. Age b. [age]
c. 35 d. error
Tuples and Dictionaries 177
26. Which of the following functions will be used to get the number of entries in dictionary?
a. len(dict) b. dict.len
c. size(dict) d. dict.size
27. What will be the output of the following code?
dict1 = {’john’:25,’Salary’:18,000}
dict2 = {’kathy’:35,’Salary’:28,000}
>>>print dict1 > dict2
a. True b. error
c. false d. none
28. What will be the output of the following code?
dict = {’john’:25,’Salary’:18,000,‘Age’:45}
>>>print (len(dict))
a. 6 b. 5
c. 3 d. none
29. Which of the following functions of the dictionary gets all the values from the dictionary?
a. dict.values() b. dict.value()
c. getvalues() d. getvalue()
30. Which of the following functions returns a list of the dictionary?
a. list.items() b. dict.list()
c. list.dict() d. dict.items()
31. What value is returned by the method dict.has_key(key), when the key is in the dictionary?
a. False b. True
c. Error d. None
Short Questions
1. What is tuple in Python? Compare tuple and list.
2. What will be the output of the given code?
>>>tuple = (4, 6, 8, 10)
>>>tuple.append((12, 14, 20, 24))
>>> print len(tuple)
3. What will be the output of the given code? Justify your answer.
>>>tuple = (’computer’, 456, ‘book’)
>>>print(tuple * 2)
4. What will be the output of the given code? Justify your answer.
>>>tuple = (’computer’, 456, ‘book’)
>>>print(list)
5. What are the built-in tuple functions in Python?
6. What will be the output of the given codes?
a) >>> tuple = (’computer’, 456, ‘book’)
>>>print(len(tuple))
b) >>> tuple1 = (2400, 456, 33.7, 500)
>>> tuple2 = (33400, 4569, 6687, 4008)
>>>print (‘Maximum value in:”,tuple2,”is” max(tuple2))
>>>print (‘Minimum value in:”,tuple1,”is” min(tuple1))
178 Introduction to Computing & Problem Solving using Python
c) >>>dict = {‘Name’:’john’,’Age’:25,’Salary’:28,000}
>>>print(dict)
>>>print(“keys in dictionary:”,dict.keys())
d) >>>dict = {‘Name’:’john’,’Age’:25,’Salary’:28,000}
>>>print(dict)
>>>print(“values in dictionary:”,dict.values())
e) >>>dict = {‘Name’:’john’,’Age’:25,’Salary’:28,000}
>>>print(dict)
>>>print(“items in dictionary:”,dict.items())
15. What are the built-in dictionary methods? Explain some of the built-in methods.
16. Write a program to update the dictionary key-value pair.
17. What will be the output of the following code?
a) >>>dict = {‘Name’:’john’,’Age’:25,’Salary’:28,000}
>>>print(dict)
>>>print(“dict.get(‘Age’):”,dict.get(‘Age’))
>>>print(“dict.get(‘Code’):”,dict.get(‘Code’,0))
b) >>>dict1 = {‘Name’:’john’,’Age’:25,’Salary’:28,000}
>>>print(dict)
>>>print(“dict.setdefault(‘Age’):”,dict.setdefault(‘Age’))
>>>print(“dict.setdefault(‘Code’):”,dict.setdefault(‘Code’))
c) >>>list = [‘Name’,’Age’Salary’]
>>>dict=dict.fromkeys(list)
>>>print(“new dictionary:”,dict)
Syntax
file_object = open(file_name [, access_mode])
Files and Exceptions 181
● file_name: File name contains a string type value containing the name of the file which we want
to access.
● access_mode: The value of access_mode specifies the mode in which we want to open the file,
i.e., read, write, append, etc. A list of different access_mode is given in Table 7.1. The default
access_mode is r(reading).
Example
>>>f = open(“test.txt”) # opening file in current directory
>>>f = open(“C:/Python27/README.txt”) # specifying full path # Output
>>>f
<open file ‘C:/Python27/README.txt’, mode ‘r’ at 0x02BC5128> # Output
In the given example, we have looked at how to open a file with default access_mode r. When we type
the name of the file object, Python interpreter gives us the information about the opened file.
We can always specify the access mode in which a file should be opened for us. The different access
modes available in Python are given in Table 7.1. We can also specify whether a file should be opened in
the text mode or the binary mode. The default is reading in text mode. The binary mode deals with bytes
182 Introduction to Computing & Problem Solving using Python
while we get strings when reading from a text file. The binary mode is used when we deal with non-text
files, such as image files, etc.
Examples
>>>f = open(“test.txt”) # opens in r mode(reading only)
>>>f = open(“test.txt”,’w’) # opens in w mode(writing only)
>>>f = open(“image.bmp”,’rb+’) # read and write in binary mode
TIP
There is an access mode x in Python which opens a file for exclusive creation. If the file
already exists, then this operation fails rather than overwriting it.
Syntax
fileObject.close()
Files and Exceptions 183
Example
# open a file
>>>f = open(“test.txt”,”wb”)
# perform file operations
>>>f.close() # close the file
Most recommended way of using file is along with ‘with’ keyword. Because, once the ‘with’ block
exits, file is automatically closed and file_object is destroyed.
Example
>>> with open("test.txt") as f:
print f.read()
Hello Python---This is in File. # Output
Note Although the closing method will close the file instantly, it is not safe. When we are
performing some operations on a file and an exception occurs, the code exits without closing
the file. Hence, we should use try…finally block. We will learn about the exceptions in
more detail later in this chapter.
Example
>>>try:
... f = open(“test.txt”)
# perform operations
... finally:
... f.close()
Example
# open a file
>>>f = open(“C:/Python27/test.txt”,”wb”)
>>>print f.name
C:/Python27/test.txt # Output
>>> print f.closed
False # Output
>>>print f.mode
Wb # Output
>>>print f.softspace
0 # Output
>>>f.close() # Close the opened file
>>> print f.closed
True # Output
Note The write() method enables us to write any string to an opened file.
Syntax
fileobject.write(string)
The content that we want to write to a file is passed as parameter to the above syntax.
Example
# open the file with w mode
>>>f = open(“C:/Python27/test.txt”,”w”)
# perform write operation
>>>f.write(‘writing to the file line 1\n’)
>>>f.write(‘writing to the file line 2\n’)
>>>f.write(‘writing to the file line 3\n’)
>>>f.write(‘writing to the file line 4’)
# close the file after writing
>>>f.close()
Files and Exceptions 185
The given example creates a file named test.txt if it does not exist, and overwrites into it if it exists.
If you open the file, you will find the following content in it.
Output:
Writing to the file line 1
Writing to the file line 2
Writing to the file line 3
Writing to the file line 4
Note Python strings can have binary data, not just text.
Syntax
fileobject.read([size])
The count parameter gives the number of bytes to be read from an opened file. It starts reading from the
beginning of the file until the size given. If no size is provided, it ends up reading until the end of the file.
Example
# open the file
>>>f = open(“C:/Python27/test.txt”, “r”)
>>>f.read(7) # read from starting 7 bytes of data
‘writing’ # Output
>>>f.read(6) # read next 6 bytes of data
‘to the’ # Output
>>>f.read() # read rest of the file
‘ file line 1\nwriting to the file line 2\nwriting to the file line 3\
nwriting to the file line 4\n’ # Output
>>>f.read()
‘’ # Output
Here we are using the file ‘test.txt’ created earlier for reading. f.read(7)reads the first 7 bytes of
data. After this, f.read(6) reads the next 6 bytes and then f.read() reads the rest of the file._When we
try to read the file after fully reading it, we get an empty string. This is because we have ended up reading
the whole file and no string is left to read in the file.
186 Introduction to Computing & Problem Solving using Python
TIP
readline() is a method of reading a file line by line. Whenever we write fileobject.
readline(), it prints one line from that file and continues in this way until the end of the
file.
Example
#open a file
>>> f=open(“C:/Python27/test.txt”, “r”)
>>>f.readline() # reading 1st line
‘writing to the file line 1\n’ # Output
>>>f.readline() # reading 2nd line
‘writing to the file line 2\n’ # Output
>>>f.readline() # reading 3rd line
‘writing to the file line 3\n’ # Output
>>>f.readline() # reading 4th line
‘writing to the file line 4\n’ # Output
>>>f.readline() # no line to read
‘’ # Output
# close the file
>>>f.close()
Example
# open a file
>>> f = open(“example.txt”,”r”)
# perform reading operation
>>>f.close() # close the file
2. Give the syntax for reading from a file. What is the work of the readline() function?
Ans. Syntax
fileobject.read([size])
The count parameter size gives the number of bytes to be read from an opened file. It starts
reading from the beginning of the file until the size given. If no size is provided, it ends up
reading until the end of the file.
Files and Exceptions 187
readline()
File Positions
We have seen in the previous section that when we read a line or some data from a file, the pointer points to
the next line or data, and that when we end up reading whole file, it returns the empty string. In this section,
we will learn to check the current position of the pointer and to change the position of the pointer.
In Python, the tell() method tells us about the current position of the pointer. The current position tells
us where reading will start from at present.
We can also change the position of the pointer with the help of seek() method. A number of bytes are
passed to be moved by the pointer as arguments to the seek() method.
Note The value 0 indicates that the position of pointer should be set to the beginning of
the file; the value 1 indicates that it should be set to the current position; the value 2 indicates
that it should be set to the end of the file.
Example
# open the file
>>>f=open(“C:/Python27/test.txt”, “r”)
# read 28 bytes of data
>>>f.read(28)
‘writing to the file line 1’ # Output
# check the current position
>>>f.tell()
28L # Output
# change the position to beginning
>>>f.seek(0)
# again read 28 bytes
>>>f.read(28)
‘writing to the file line 1’ # Output
Syntax
os.rename(current_filename, new_filename)
188 Introduction to Computing & Problem Solving using Python
Example
# import os
>>>import os
# renaming the file
>>>os.rename(“C:/Python27/test.txt”,”C:/Python27/test1.txt”)
Syntax
os.remove(filename)
Example
# import os
>>>import os
# deleting the file
>>>os.remove(“C:/Python27/test1.txt”)
6. file.read([size])
Reads the size bytes from a file.
7. file.readline([size])
It reads the entire one line from a file.
8. file.readlines([sizehint])
It reads until the end of the file using readline. It returns the list of lines read.
9. file.seek([offset])
It changes the current position.
10. file.tell()
It returns the file’s current position.
11. file.truncate([size])
It truncates the file.
12. file.write(str)
It writes the str string to the file.
13. file.writelines(sequence)
It writes the sequence of strings into a file. If each string in the sequence should go into separate lines in file,
the string should end with a new line character, ‘\n’.
Syntax
os.rename(current_filename, new_filename)
Deleting a File
Deleting a file in Python is done with the help of the remove() method. The remove() method
takes the filename as an argument to be deleted.
Syntax
os.remove(filename)
190 Introduction to Computing & Problem Solving using Python
7.2 DIRECTORIES
Directories help us make things more manageable. If there is a large number of files, then related files are
placed in different directories. Hence, a directory can be said to be a collection of files and sub directories.
The module os in Python enables us to use various methods to work with directories.
Syntax
os.mkdir(“newdir”)
Example
# importos
>>>import os
# create a new directorytestdir
>>>os.makedir(“testdir”)
Syntax
os.chdir(“dir_name”)
Example
# importos
>>>import os
# change the current directory to “/home/testdir”
>>>os.chdir(“/home/testdir”)
Syntax
os.getcwd()
Example
# importos
>>>import os
>>>os.getcwd() # This will give the address of the current directory
‘C:\\Python27’ # Output
TIP
It is required to provide the full location of the directory; otherwise, the directory will be
searched in the current directory.
Syntax
os.rmdir(‘directory_name’)
Example
# importos
>>>import os
>>>os.rmdir(“/tmp/test”)
# it will remove the “/tmp/test” directory # Output
Note All the contents in a directory should be deleted before removing that directory.
and sub directories. The module os in Python enables us to use various methods to work with
directories.
Following are the four basic methods that are performed on directories:
■ mkdir() method (Creating a directory)
■ chdir() method (Changing the current directory)
■ getcwd() method (Displaying the current directory)
■ rmdir() method (Deleting the directory)
2. Give the syntax for each of basic directory methods.
Ans. mkdir() method:
Syntax
os.mkdir(“newdir”)
chdir() method:
Syntax
os.chdir(“dir_name”)
getcwd() method:
Syntax
os.getcwd()
rmdir() method:
Syntax
os.rmdir(‘directory_name’)
7.3 EXCEPTIONS
While writing a program, we often end up making some errors. There are many types of errors that can occur
in a program. The error caused by writing an improper syntax is termed syntax error or parsing error; these
are also called compile time errors.
Errors can also occur at runtime and these runtime errors are known as exceptions. There are various types
of runtime errors in Python. Let us look at a few examples. When a file we try to open does not exist, we
get a FileNotFoundError. When a division by zero happens, we get a ZeroDivisionError. When the module
we are trying to import does not exist, we get an ImportError. Python creates an exception object for every
Files and Exceptions 193
occurrence of these run-time errors. The user must write a piece of code that can handle the error. If it is not
capable of handling the error, the program prints a trace back to that error along with the details of why the
error has occurred.
Example
Compile time error (Syntax error)
>>>a = 3
>>>if (a < 4) # Semicolon is not included
SyntaxError: invalid syntax # Output
The error shown above is a syntax error because there is a problem with the syntax; the if statement
starts with semicolon.
ZeroDivisionError
>>>5/0
Output:
Traceback (most recent call last):
File “<pyshell#71>”, line 1, in <module>
5/0
ZeroDivisionError: integer division or modulo by zero
Here, we tried to divide 5 by 0. As a result, the interpreter prints ZeroDivisionError.
Note Python provides a very important feature (Exception Handling) for handling any
unexpected error in our Python programs, and it also adds debug capabilities to them.
Syntax
try:
the operation which can cause exception here,
.........................
Files and Exceptions 195
except Exception1:
if there is exception1, execute this.
except Exception2:
if there is exception2, execute this.
.........................
else:
if no exception occurs, execute this.
Note A try block can have multiple except clauses associated with it. It can be useful to
have the try block include statements that can cause different types of exceptions.
TIP
After except clause, we can add an else statement. The statements in the else block will
execute only when the statements in try block do not raise any exception.
Example
>>>try:
... file = open(“C:/Python27/test.txt”,”w”)
... file.write(“hello python”)
... exceptIOError:
... print “Error: cannot find file or read data”
... else:
... print “content written successfully”
>>>file.close()
In the given example, we are trying to open a file test.txt with write access mode, and want to write
to that file. We have added try and except blocks.
If the required file is not found or we do not have the permission to write to the file, an exception is raised.
The exception is handled by the except block and the following statement printed:
Error: cannot find file or read data
On the other hand, if the data is written to the file then the else block will be executed and it will print
the following.
Output:
content written successfully
2. except with No Exception We can also write our try-except clause with no exception. All types of
exceptions that occur are caught by the try-except statement. However, because it catches all exceptions,
the programmer cannot identify the root cause of a problem that may occur. Hence, this type of programming
approach is not considered good.
196 Introduction to Computing & Problem Solving using Python
Syntax
try:
The statements that can cause exceptions
..........................................
except:
If Exception occurs, execute this
..........................................
else:
If no exception occurs, execute this
Example
>>>while True:
... try:
... a = int(raw_input(“Enter an integer: “))
... div = 10/a
... break
... except:
... print “Error Occured”
... print “Please Enter Valid Value”
... print()
... print “Division is”,div
Enter an integer: 0
Error Occurred
Please Enter Valid Value
Enter an integer: 5
Division is 2
In the above example, break statement is used instead of else statement because the else statement only
executes when there is no exception.
3. except with Multiple Exceptions In Python, we can also use the same except statement for handling
multiple exceptions in one statement.
Files and Exceptions 197
Syntax
try:
the operation which can cause exception here,
.........................
except (Exception1 [,Exception2 [,...ExceptionN]]]):
if any of the exception occurs from the above list
execute this,
............................................
else:
if no exception occurs, execute this.
4. try….finally The try statement in Python has an optional finally clause that can be associated
with it. The statements written in finally clause will always be executed by the interpreter, whether the
try statement raises an exception or not.
Note With the try clause, we can use either except or finally, but not both.
TIP
We cannot use the else clause along with a finally clause.
Syntax
try:
the operation which can cause exception here,
.........................
This may be skipped due to exception
finally ():
This will always execute, no matter what
..................................
198 Introduction to Computing & Problem Solving using Python
Example
>>> try:
... file = open(“testfile”,”w”)
... try:
... file.write(“Write this to the file”)
... finally:
... print “Closing file”
... file.close()
... exceptIOError:
... print “Error Occurred”
In the given example, when an exception is raised by the statements of try block, the execution is
immediately passed to the finally block. After all the statements inside the finally block are executed,
the exception is raised again and is handled by the except block that is associated with the next higher
layer try block.
In the above example, a nested try block is used, which means a try block inside another try block. The
nested try blocks are allowed in python programming language. Although it is not considered as good
programming practice but it may be useful sometimes.
Syntax
try:
the operation which can cause exception here,
.........................
exceptExceptionType, Argument:
Print the argument value here.
If we are writing a code to handle the exceptions, we can define a variable after the name of exception
in the except statement. If we are defining multiple exceptions, we can define a variable after the tuple of
exceptions.
Example
# Define a function
>>>def integer(a):
... try:
Files and Exceptions 199
... returnint(a)
... exceptValueError, Argument:
... print “The Value does not contain Numbers\n”, Argument
Example
>>>class CustomError(Exception)
... pass
...
Here, we have created a class with CustomError that is derived from the Exception class. Now, we
can simply call the CustomError by using the raise keyword.
Example
>>>raise CustomError
Output:
Traceback (most recent call last):
File “<pyshell#144>”, line 1, in <module>
raiseCustomError
CustomError
Output:
Traceback (most recent call last):
File “<pyshell#145>”, line 1, in <module>
raiseCustomError(“An error occurred”)
CustomError: An error occurred
200 Introduction to Computing & Problem Solving using Python
Syntax
try:
the operation which can cause exception here,
.........................
except Exception1:
if there is exception1, execute this.
except Exception2:
if there is exception2, execute this.
.........................
else:
if no exception occurs, execute this.
try….finally:
Syntax
try:
the operation which can cause exception here,
.........................
This may be skipped due to exception
finally ():
This will always execute, no matter what
..................................
Example
>>>class Error(Exception)
... pass
...
We have created a class with Error that is derived from the exception class.
✓ CONCATENATION: This operator works in tuples in the same way as it does in lists. This operator
concatenates two tuples. This is done by the + operator in Python.
✓ DICTIONARY: A Python dictionary is an unordered collection of items or elements. The dictionary has
a key: value pair.
✓ IMMUTABLE: It is the type in which elements cannot be modified. Tuples are immutable.
✓ in OPERATOR: This operator tells the user whether a given element exists in the tuple or not. It gives
a Boolean output, that is, True or False.
✓ ITERATION: Iteration can be done in tuples using for loop. It helps in traversing through the tuple.
1. len(tuple):It returns the length of the tuple.
2. cmp(tuple1, tuple2): It compares the items of two tuples.
3. max(tuple): It returns the largest value among the elements in a tuple.
4. min(tuple): It returns the smallest value among the elements in a tuple.
5. tuple(seq): It converts a list into a tuple.
6. zip(tuple1, tuple2): It ‘zips’ elements from two tuples into a list of tuples.
✓ KEY: It is used to get the value in the dictionary.
✓ KEY-VALUE: This pair represents the items in the dictionary.
1. dict(): Python provides this function to create a dictionary.
2. get(): This method is used with the key to access the value in a dictionary.
3. pop(): This method removes the item from the dictionary and returns the value of the item.
4. popitem(): This method is used to delete and return an arbitrary item from the dictionary.
5. clear(): This method removes all the items from the dictionary.
6. del: It is used to delete the dictionary itself.
✓ MUTABLE: It is the type in which elements are modified. Dictionaries are mutable.
1. len(dict): It returns the number of items (length) in the dictionary.
2. cmp(dict1,dict2): It compares the items of two dictionaries.
3. sorted(dict): It returns the sorted list of keys.
4. str(dict): It produces a printable string representation of dictionary.
✓ REPETITION: This operator repeats the tuples for a given number of times. Repetition is performed
by the * operator.
✓ TUPLE: Tuples, just like lists, are the sequence or series of different types of values separated by commas
(,).
✓ TUPLE ASSIGNMENT: It allows the assignment of values to a tuple of variables on the left side of
assignment from the tuple of values on the right side of the assignment.
✓ VARIABLE-LENGTH ARGUMENT TUPLES: Variable number of arguments can also be passed to
a function. A variable name which is preceded by an asterisk (*) collects the arguments into a tuple.
Files and Exceptions 203
PROGRAMS
1. Write a function to print the resolution of an image file in Python.
Solution.
def imgres(file_name):
with open(file_name, ‘r’) as img:
img.seek(163)
x = img.read(2)
h = (x[0] << 8) + x[1]
x = img.read(2)
w = (x[0] << 8) + x[1]
print(“Resolution = “,w,”x”,h)
>>>imgres(“C:\Python27\1.jpg”)
Resolution= 320 X 280 #Output
2. Write a function to print the hash of any given file in python. (Hint: Use SHA-1 algorithm).
Solution.
>>>def hash_of_file(file_name):
o = hashlib.sha1()
with open(file_name,’rb’) as hash_file:
pointer = 0
while pointer != b’’:
pointer = file.read(1024)
o.update(pointer)
return o.hexdigest()
>>>code = hash_of_file(“C:\Python27\1.mp3”)
>>>print(code)
799d7356947cca543c50b76a1852f92427f4csa8 #Output
3. Write a program to catch on Divide by zero Exception. Add a finally block too.
Solution.
>>>try:
9/0
except ZeroDivisionError:
print “Divide by Zero”
except Exception, e:
print “Error Occurred”
finally:
print “This always executes”
4. Write a program to write data in a file for both write and append modes.
Solution.
# In write mode
>>>fi = open(‘note.txt’, ‘w’)
>>>fi.write(‘123\n456’)
>>>fi.close()
# In append mode
>>>fi = open(‘note.txt’, ‘a’)
>>>fi.write(‘789\n101112’)
>>>fi.close()
5. Write a custom exception that could be raised when the text entered by a user consists of less than
6 characters.
Solution.
>>>class CustExcp(Exception):
pass
>>>try:
i = input(“Enter the text: “)
if len(i) < 6:
raise CustExcp()
except CustExcp as ce:
print(“CustomException: Expected length at least 6”)
6. Write a python program to demonstrate the file and file I/O operations
Solution.
# python program to demonstrate files and file I/O operations
# reading the input from the user using raw_input
import os
str = raw_input(“Enter your input: “);
print “Received input is : “, str
# To open or create a file
print “opening a new file in writing in binary format mode”
newfl = open(“sample1.txt”, “wb”)
print “File name: “, newfl.name
print “Is the file closed : “, newfl.closed
print “Mode of the file opening : “, newfl.mode
print “ File Softspace flag for expicit : “, newfl.softspace
print “closing the file”
# Closing the file
newfl.close()
print “Is the file closed : “, newfl.closed
print “writing into the file”
newf2 = open(“sample2.txt”, “wb”)
newf2.write( “This is my first file to enter data in the python.\nIt is simple
and easy\n”);
Files and Exceptions 205
newf3.seek(0, 2)
lin = newf3.writelines( sequ )
newf3.seek(0,0)
for indx in range(7):
ln = newf3.next()
print “Line Number %d - %s” % (indx, ln)
Output:
Enter your input: Welcome to python
Received input is : Welcome to python
opening a new file in writing in binary format mode
File name: sample1.txt
Is the file closed : False
Mode of the file opening : wb
File Softspace flag for expicit : 0
closing the file
Is the file closed : True
writing into the file
reading the file sample1.txt
Read String is : This is my first f
Current file position : 18
seek function on a file
reread the same file the output is : This is my first f
rename the existing file
remove the file
create a new directory
change the directory
/home/sample
Opening a new file in writing in binary format mode
reading the file sample1.txt
flush operation on file
fileno () and isatty()
file name is: sample2.txt
Descriptor of the file: 5
Return value is: False
next function on file
Traceback (most recent call last):
StopIteration
Note There are prone to be errors when we use the directory functions and the next() using
the files.
def tmp_ftoc(var):
try:
return int(var)
except ValueError, Arg:
print “The argument does not contain numbers\n”, Arg
# Function call.
tmp_ftoc(“abc”);
print “exception on files”
try:
fs = open(“sample1”, “r”)
fs.write(“I am using this program for exception handling!”)
except IOError:
print “Error: File not found or file not read sucessfully”
else:
print “File read operation on the file sucessfull”
print “file I/O operation exception”
try:
fs1 = open(“sample2”, “w”)
fs1.write(“this is my second file for exception handling!”)
finally:
print “Error: File not found or file not read”
print “file exception in closing the file”
try:
fs2 = open(“sample3”, “w”)
try:
fs2.write(“Here I am using this file for exception handling!”)
finally:
print “the file is being closed”
fs2.close()
except IOError:
print “Error: File not found or file not read I/O exception”
fs2.close()
print “user defined exception”
class Ntwrkerr(RuntimeError):
def __innt1__(self1, arg1):
self1.args = arg1
try:
raise Ntwrkerr(“Hostname is bad”)
except Ntwrkerr,e1:
print e1.args
Output:
functions that handle exception
The argument does not contain numbers
invalid literal for int() with base 10: ‘abc’
exception on files
Error: File not found or file not read sucessfully
file I/O operation exception
Error: File not found or file not read
file exception in closing the file
208 Introduction to Computing & Problem Solving using Python
13. Which of the following statements is correct while using ‘a+’ mode for opening a file?
a. Opens a file for appending only
b. Opens a file for writing only
c. Opens a file for both appending and reading
d. Opens a file for both appending and writing
14. Which of the following statements is correct while using ‘x’ mode?
a. Open a file for reading b. Open a file for exclusive creation
c. Open a file for appending d. Does not open a file
15. In disk, the files are stored in?
a. Bytes b. Bit
c. Kilobits d. Gigabytes
16. What is the syntax to close a file?
a. file.close() b. close()
c. close(); d. fileObject.close()
17. The write() method does not add a newline character (‘\n’) at which position of the string?
a. Beginning b. Middle
c. End d. None of the above
18. What is the syntax of the write() method?
a. FileObject.write() b. fileObject.write(string)
c. file.object.write() d. file.write()
19. What is the syntax for reading from a file?
a. fileObject.read([size]) b. fileObject.read(size)
c. file.read() d. file.read(size)
20. Which module does Python provide to perform operations like renaming and deleting files?
a. Is b. os
c. op d. ip
21. Which of the following methods is used to create directories in the current directory?
a. chdir() b. rmdir()
c. mkdir() d. mcdir()
22. Which of the following methods is used to change the current directory?
a. chdir() b. rmdir()
c. mkdir() d. mcdir()
23. Which of the following methods is used to display the current working directory?
a. mkcwd() b. getcwd()
c. chcwd() d. setcwd()
24. Which of the following methods is used to delete the directory?
a. chdir() b. mkdir()
c. mrdir() d. rmdir()
25. Which of the following is not an attribute of a file in Python?
a. Mode b. Name
c. Delete d. Closed
26. Which of the following is a condition that is caused by a runtime error in the program?
a. Exception b. Assertion
c. Attribute d. Error
210 Introduction to Computing & Problem Solving using Python
Short Questions
1. What is a file in Python and why is it used?
2. How to open a file? What are the modes for opening a file?
3. What are the various attributes of the file object?
4. What will be the output of the code below? Justify your answer.
>>>fileObject = open(“xyz.txt”, “w”)
>>>print(“name of the file:”, fo.name)
>>>print(“closed or not:”, fo.closed)
>>>print(“opening mode:”, fo.mode)
>>>print(“softspace flag:”, fo.softspace)
Files and Exceptions 211
of data members and method members that are used by the instances (objects) of the class.
● Data Member: A variable defined in either a class or an object; it holds the data associated with the
class or object.
● Instance Variable: A variable that is defined in a method; its scope is only within the object that
defines it.
● Class Variable: A variable that is defined in the class and can be used by all the instances of that class.
● Method: Methods are the functions that are defined in the definition of class and are used by various
● Inheritance: A class ‘A’ that can use the characteristics of another class ‘B’ is said to be a derived
class, i.e., a class inherited from ‘B’. The process is called inheritance.
8.1.2 Polymorphism
The word ‘Poly’ means ‘many’. Therefore, the term ‘polymorphism’ means that the object of a class can
have many different forms to respond in different ways to any message or action.
In other words, polymorphism is the capability for a message or data to be processed in one or more ways.
Let us look at an example:
If a base class is mammals, then horse, human, and cat are its subclasses. All the mammals can see in the
daytime. Therefore, if the message ‘see in the daytime’ is passed to mammals, all the mammals including the
human, the horse and the cat will respond to it. Whereas, if the message ‘see during the night time’ is passed
to the mammals, then only the cat will respond to the message as it can see during the night as well as in the
daytime. Hence, the cat, which is a mammal, can behave differently from the other mammals.
This is called polymorphism and is illustrated in Fig. 8.1.
Class Shape
Draw()
For example:
● Fruit is a class, and apple, mango and banana are its objects. The attributes of these objects can be
Syntax
class class_name:
‘This is docstring which is optional’
class_suite
A new local new space is created by a Class, where all its attributes (data or function) are defined. Special
attributes with double underscores (_)are also present, for example- _doc_ gives the docstring of that class.
As soon as the class is defined, a new class object is created with same name, which allows access to the
different attributes, also to instantiate new object of that class.
Example
>>>class Student:
... ‘student details’
... def fill_details(self,name,branch,year):
... self.name = name
... self.branch = branch
... self.year = year
... print(“A Student detail object is created”)
... def print_details(self):
... print(‘Name: ‘, self.name)
... print(‘Branch: ‘,self.branch)
... print(‘Year: ‘,self.year)
In the given example, we have created a class Student that contains two methods: fill_details and
print_details. The first method fill_details takes four arguments: self, name, branch and year.
The second method print_details takes exactly one argument: self.
In the next section, we will find out how these class and methods are used.
Note The methods in the classes are defined in the same way as the functions are defined
in the preceding sections. The only difference is that the every method will have self as its
first argument.
Classes and Objects 215
TIP
At the time of calling the method, we do not need to add self as an argument. The Python
interpreter does it for us.
Syntax
obj_name = class_name()
216 Introduction to Computing & Problem Solving using Python
Example
s1 = Student()
The above statement creates an object s1 of the class Student which we defined earlier.
Now, we can access the methods (attributes) which are defined in the class Student. We can use a method
from the class Student with the object name followed by a dot, which is then followed by the method
name with valid arguments.
Example
# creating an object of Student class
>>> s1 = Student()
# creating another object of Student class
>>>s2 = Student()
# using the method fill_details with proper attributes
>>> s1.fill_details(‘John’,’CSE’,’2002’)
A Student detail object is created
>>>s2.fill_details(‘Jack’,’ECE’,’2004’)
A Student detail object is created
# using the print_detail method with proper attributes
>>>s1.print_details()
Name: John # Output
Branch: CSE # Output
Year: 2002 # Output
>>>s2.print_details()
Name: Jack # Output
Branch: ECE # Output
Year: 2004 # Output
In this example, we create two objects (instances) s1 and s2 of class Student. Then afterwards, we use
the fill_details method of class with the object names as prefix and passed the valid arguments. The
details of the students are stored in the objects. Now, the second method print_details is called with the
same convention. The method print_details prints the details of all stored students.
Example
# Create an instance of class Student
>>>s1 = Student()
# Fill details in that object
>>>s1.fill_details(‘John’,’ECE’,2004)
A Student detail object is created
# Printing details of the object s1
>>>s1.print_details()
Output:
Name: John
Branch: ECE
Year: 2004
Now, what if it is required to change the value of branch of object s1 to CSE? Will we create a new
object? Definitely not. We can change the value in the same object by simply reassigning the value to it.
#Change the value of branch from ECE to CSE
>>>s1.fill_details(‘John’,’CSE’,2004)
A Student detail object is created
# The branch is changed from ECE to CSE
>>>s1.print_details()
Output:
Name: John
Branch: CSE
Year: 2004
Note Objects can be passed as an argument to a function and a function can also return
an object.
Syntax
obj_name = class_name()
218 Introduction to Computing & Problem Solving using Python
Example
# define a class
>>>class A:
def print_det(self):
print ‘This is a class’
Example
First of all, we will create a class Triangle with no statements.
>>>class Triangle:
pass
Now, we create an object t1 of the class Triangle and assign the value of sides a, b, c of the
triangles here.
>>>t1 = Triangle()
>>>t1.a = 10
>>>t1.b = 18
>>>t1.c = 23
Now, we define a function perimeter, which calculates the perimeter of a triangle. This function takes
an object or instance of a class as an argument.
>>>def perimeter(obj):
per = t1.a + t1.b + t1.c
print(“Perimeter of triangle: “, per)
Classes and Objects 219
Now, we pass the object t1 to the function perimeter, which calculates the perimeter of the triangle
that is in this object.
>>>perimeter(t1) # Passing object as argument
Perimeter of triangle: 51 # Output
Example
Create a class triangle and define two methods: one is create_triangle, which will create
the triangle, and the other is print_sides, which will print the sides of the triangle.
>>>class Triangle:
defcreate_triangle(self,a,b,c):
self.a = a
self.b = b
self.c = c
print(“The triangle is created”)
defprint_sides(self):
print(‘Side a: ‘, self.a)
print(‘Side b: ‘, self.b)
print(‘Side c: ‘, self.c)
Define a function size_double that will take an object as an argument and return a triangle in the
form of an object that is double in size.
>>>defsize_double(obj):
t2 = Triangle()
t2.a = t1.a *2
t2.b = t1.b *2
t2.c = t1.c *2
return t2 # Returning object
>>>t2 = size_double(t1) # Passing object as argument
>>>t2.print_sides()
Output:
Side a: 20
Side b: 40
Side c: 60
Hence, we got a triangle that is double in size with the triangle that was passed as an argument.
220 Introduction to Computing & Problem Solving using Python
Note The purpose of the dot notation is to identify the variable you are referring to
unambiguously.
TIP
Class definitions can appear anywhere in the program, but they usually appear near the
beginning.
Example
# Create the class Student
>>>class Student:
‘student details’
Student.__name__: Student
Example
>>>print “__name__: “,PrintStatement.__name__
__name__: PrintStatement
8.7 INHERITANCE
Inheritance is a very important concept in OOP. Inheritance, generally, means to acquire the features of
something. In OOP, it means the reusability of code. It is the capability of a class to derive the properties of
another class that has already been created.
Let us look at an example illustrated in Fig. 8.2.
222 Introduction to Computing & Problem Solving using Python
● Vehicle is a class that is further divided into two subclasses, automobiles (driven by motors) and pulled
vehicles (driven by men). Therefore, vehicle is the base class and automobiles and pulled vehicles are
its subclasses. These subclasses inherit some of the properties of the base class vehicle.
● Truck and car are the subclasses of the class automobile that is the base class for them. They inherit
some of the properties of base class automobiles. Similarly, the rickshaw and bullock cart are the
subclasses of pulled vehicles that serves as the base class for them.
The main advantage of inheritance in the context of programming is that the code can be written once in
the base class and then reused repeatedly in the subclasses.
Vehicles
Inheritance generally involves acquiring the features of a predecessor. With the help of inheritance, we
can inherit a class from another class. If a class A is inherited from another class B, then class A can use all
the features (like variables and methods) of class B.
The class which inherits the features of another class is known as subclass. If we want to inherit a class,
we use the class name with the name of the class that is to be inherited in the parentheses.
Syntax
class sub_classname(Parent_classname):
‘Optional Docstring’
Class_suite
Example
Define a parent class Person
>>>class Person(object):
‘returns a Person object with given name’
defget_name(self,name):
self.name = name
defget_details(self):
‘returns a string containing name of person’
return self.name
In the example illustrated above, we have defined a parent class Person that has two methods: get_
name() and get_details().
Now, we have defined two subclasses: the student class, which has two methods: fill_details()
and get_details(), and teacher class, which also has two methods: fill_details() and get_
details().
We have used the parent class method get_details() in the subclasses student and teacher to
get the names of students and teachers respectively. This is called inheritance.
224 Introduction to Computing & Problem Solving using Python
Syntax
# Define your first parent class
class A
........class_suite..........
Example
>>> class A: #Defining class A
def x(self):
print(“method of A”)
>>> y = C()
>>> B.x(y)
method of B #Output
>>> A.x(y)
method of A #Output
In the above example, two classes A and B are defined and then another class C is defined which inherits
the two classes A and B. Now, an object of class C is created, through which the methods of classes A and
B are accessed.
Classes and Objects 225
Example
>>>class Parent:
defovr_method(self):
print ‘This is in Parent Class’
>>>class Child(Parent):
defovr_method(self):
print ‘This is in Child Class’
>>>c = Child()
>>>c.ovr_method()
This is in Child Class # Output
Note The pass statement has no effect; it is only necessary because a compound statement
must have something in its body.
TIP
The initialization method(__init__) is a special method that is invoked when an object is
created. It is also known as the constructor method for a class.
Example
>>> class MyClass(object): # Defining class
def __init__(self, x, y, z):
self.var1 = x # public data member
self._var2 = y # protected data member
self.__var3 = z # private data member
>>> obj._var2
4 # Output
>>> obj._var2 = 12
>>> obj._var2
12 # Output
Note The value of a private variable can be set by a Python method called setter method.
>>> a1 = A(22)
>>> a1.getP() #Getting value through get function
22
>>> a1.setP(43) #Setting value through set function
>>> a1.getP()
43
Classes and Objects 227
Example
>>> class MyClass: # defining class
__a = 0;
def sum(self, increment):
self.__a += increment
print self.__a
As seen in the above example that the variable __a is not accessible as we tried to access it; the Python
interpreter generates an error immediately. In such a case, the Python secures the members by internally
changing the names to incorporate the name of the class. If you intend to access these attributes then the
syntax for accessing the variable is:
objectName.__className__attributeName
In the above code, if we use the aforementioned syntax to access the attributes, then the following changes
are seen in the output:
>>> class MyClass: # Defining class
__a = 0;
def sum(self, increment):
self.__a += increment
print self.__a
Syntax
class sub_classname(Parent_classname):
‘Optional Docstring’
Class_suite
Multiple Inheritance
We can also define multiple inheritance in Python. When a class inherits the features of more
than one class it is known as multiple inheritance. It is defined in the same way as inheritance.
Syntax
# Define your first parent class
class A
........class_suite..........
● Class is a set of objects that share the same attributes, which can be data member and method member.
● Data member is a variable that is defined either in class or in object and that holds the data associated
with the class or object.
● Methods are the functions defined in the definition of class, and are used by various instances of the class.
● When a function is defined more than once with different behaviours, this is known as function overloading.
● In method overloading, the operations performed by the methods are different.
● When a class uses the characteristics of another class, it is said to be a derived class or inherited class and
the process is called inheritance.
● When a class inherits the features of more than one class, this is called multiple inheritance.
● Method overriding means that the method of parent class can be used in the subclass with different or
special functionality.
● The first argument of every method is self.
● Objects can be used to access the attributes of the class.
● The state of an object can be changed at any point of time by making changes to its attributes. Thus, it
can be said that the objects are mutable.
● The instance of a class can be passed as an argument to a function in Python.
● The instances of a class can also be returned by a function, i.e., a function can return the instances or
objects.
● There are various built-in attributes that can be accessed with a dot operator.
✓ INHERITANCE: A class ‘A’ that can use the characteristics of another class ‘B’ is said to be a derived
class or inherited from ‘B’. The process is called inheritance.
✓ METHOD OVERRIDING: When the method of the parent class can be used in a subclass with different
or special functionality, it is known as method overriding.
1. class: This is the keyword used to define a class.
2. self: It is the first argument of every method.
3. __dict__: A class attribute that displays the dictionary in which the class’s namespace is stored.
4. __name__: A class attribute that displays the name of the class.
5. __bases__: A class attribute that displays the tuple containing the base classes, possibly empty.
6. __doc__: A class attribute which displays the documentation string of the class
7. __module__: A class attribute which displays the name of the module in which the class is defined.
PROGRAMS
1. Write a program that defines a class with two methods: inputStr() that will get the string using
console input and printStr() that will print the string in upper case. Also, test the class methods
with a function.
Solution.
>>> class UpperString(object):
def __init__(self):
self.o = “”
def inputStr(self):
self.o = raw_input()
def printStr(self):
print self.o.upper()
>>> a = UpperString()
>>> a.inputStr()
‘python’ #Input from user
>>> a.printStr()
‘PYTHON’ #Output
2. Write a program that defines a class named Rectangle that takes the parameters length and breadth.
The class Rectangle should also contain a method for computing its perimeter.
Solution.
>>> class Rectangle(object):
def __init__(self,l,b):
self.length = l
self.breadth = b
Classes and Objects 231
def perimeter(self):
return
self.length+self.breadth
>>> a = Rectangle(10,15)
>>> print a.perimeter()
25 #Output
3. Write a function that has a class Animal with a method legs. Create two subclasses Tiger and
Dog. Now, access the method leg explicitly with the class Dog and implicitly with the class Tiger.
Solution.
#for explicitly access, we need to override the method in Dog class.
>>> class Animal(object):
def legs(self):
print “legs Animal() method”
>>> a = Animal()
>>> d = Dog()
>>> t = Tiger()
>>> a.legs()
legs Animal() method #Output
>>> d.legs() #Accessing method explicitly (override)
legs Dog() method #Output
>>> t.legs() #Accessing method implicitly
legs Animal() method #Output
4. Write a program that defines a class named Employee. Define two subclasses: Engineer and
Manager. Every class should have a method named printDesignation() that prints Engineer for
Engineer class and Manager for Manager class.
Solution.
>>> class Employee(object):
def printDesignation(self):
return “Not Known”
>>> e = Engineer()
>>> m = Manager()
>>> print e.printDesignation()
Engineer #Output
>>> print m.printDesignation()
Manager #Output
def dispcount(self):
print “Total number of persons”, Person.pcount
def dispperson(self):
print “Person Name : “, self.name, “, age:”, self.age, “Salary: “,
self.salary
print “creating objects to the class”
per1 = Person(“ruby”, 24, 2000)
per2 = Person(“Perl”, 27, 5000)
per1.dispperson()
per2.dispperson()
print “Total number of person %d” % Person.pcount
Output:
Total number of person 2
details of the person class and class attributes
Person.__doc__: None
Person.__name__: Person
Person.__module__: __main__
Person.__bases__: ()
Person.__dict__: {‘__module__’: ‘__main__’, ‘pcount’: 2, ‘dispcount’: <func-
tion dispcount at 0x7fc0ba6e27d0>, ‘dispperson’: <function dispperson at
0x7fc0ba6e2848>, ‘__d
oc__’: None, ‘__init__’: <function __init__ at 0x7fc0ba6e2758>}
False
3000
After deleting the atribute salary
Traceback (most recent call last):
File “Person.py”, line 37, in <module>
print “After deleting the atribute salary”, Person.salary
AttributeError: class Person has no attribute ‘salary’
Note: Save the file name as Person.py. The user can try the “getattr(Person,
age)” which is can be added to the code and check the functionality.
def PersonMethod(self):
print ‘Calling Person method’
def getAttr(self):
print “Person attribute :”, Person.PersonAttr
def myMethod(self):
print ‘Calling Person method’
def SubpersonMethod(self):
print ‘Calling Subperson method’
def myMethod(self):
print ‘Calling Subperson method’
234 Introduction to Computing & Problem Solving using Python
Output:
Calling Subperson constructor
Calling Subperson method
Calling Subperson constructor
Calling Subperson method
Calling Person method
Person attribute : 300
Calling Subperson constructor
Calling Subperson method
Calling Person method
Person attribute : 300
Calling Subperson constructor
Calling Subperson method
class trans(object):
def higher(this,that):
if this.getcapc() > that.getcapc():
return this
return that
@staticmethod
def maximumm(collect):
uptonow = collect[0]
for tryme in collect:
uptonow = uptonow.higher(tryme)
return uptonow
# base class-2
class label(object):
def nameset(this,name):
this.name = name
def nameget(this):
return this.name.upper()
class mulchildclass(trans,label):
def __init__(current,dest,time,length,pereach):
Classes and Objects 235
current.time = time
current.leng = length
current.pe = pereach
current.nameset(dest)
def getcapc(current):
return current.leng * current.pe
class secmulchild(trans,label):
def __init__(current,dest,pereach):
current.pe = pereach
current.nameset(dest)
def getcapc(current):
return current.pe -1
perl = mulchildclass(“perl”,”07:17”,2,75)
ruby = mulchildclass(“ruby”,”07:24”,1,61)
rhino= secmulchild(“rhino”,5)
Mystore = mulchildclass(“Mystore sales”,”07:45”,7,65)
sara = secmulchild(“sara jane”,8)
flows = [rhino,perl,sara,Mystore,ruby]
Output:
o RHINO carrying 4
To PERL carrying 150
To SARA JANE carrying 7
To MYSTORE SALES carrying 455
To RUBY carrying 61
Note This program is demonstration for multiple inheritance and transfer of funds which
is a simple application to find who has made the highest transfer. There are 2 base classes
and 2 child classes.
236 Introduction to Computing & Problem Solving using Python
defgetq(xyz):
returnself._q
a=A()
a.p=20
print(a.p)
a. The program has an error because p is private
b. The program has an error because q is private
c. The program prints 1
d. The program prints 20
5. Analyse the following code:
class A:
def__init__(self,p):
self.p=p
def print(self):
print(p)
a=A(“Python”)
a.print()
a. The program has an error because class A does not have a constructor.
b. The program has an error because class A should have a print(self,p) method.
c. The program has an error because class A should have a print(p) method.
d. The program will execute fine if print(p) is replaced by print(self.p).
6. Analyse the following code:
class A:
def__init__(self,p=“Python”):
self.p=p
def print(self):
print(self.p)
a=A()
a.print()
Classes and Objects 237
a. The program has an error because class A does not have a constructor.
b. The program has an error because class A should have a print(self,p) method.
c. The program executes fine and prints nothing.
d. The program executes fine and prints Python.
7. Which of the following is used to create an object?
a. Constructor b. Class
c. Method d. Data field
8. Which of the following statements is not correct?
a. Each object must have unique id.
b. Same kind objects must have same type.
c. Same type objects must have same id.
d. A variable that holds a value is the reference to an object of that value.
9. What is the output of the following code?
Print(type((‘US’,‘India’,’Africa’)))
a. <class,’set’> b. <class,’list’>
c. <class,’dict’> d. <class,’tuple’>
10. What is the output of the following code?
Print(type(1J))
a. <class,’int’> b. <class,’list’>
c. <class,’float’> d. <class,’command’>
11. defMyFunction():
“Python is an interesting language”
return 1
print(MyFunction.__doc__[10:12])
What will be the output?
a. Is b. an
c. te d. er
12. What is the output of the following code?
Class Employee:
def__init__(self):
pass
defgetEmpId(self):
print(__name__)
s=Employee()
s.getEmpId()
a. __name__ b. __main__
c. Employee d. Error
13. What is the output of the following code?
Print(type(1/5))
a. <class,’int’> b. <class,’list’>
c. <class,’float’> d. <class,’command’>
14. Which of the following is known as an instance of class?
a. Object b. Program
c. Data d. Method
238 Introduction to Computing & Problem Solving using Python
15. Which of the following is a blueprint that defines objects of the same type?
a. A class b. An object
c. A method d. A program
16. Which of the following is most accurate for the given declaration:
x=Square()
a. x contains an int value. b. x contains an object of square type.
c. An int value can be assigned to x. d. x contains a reference to a square object.
17. Which of the following is the description of a set of objects that share the same attributes, operations,
and semantics?
a. Class b. Constructor
c. Function d. Method
18. Which of the following is responsible for initialising the objects of its class?
a. Constructor b. Destructor
c. Iterator d. None of the above
Short Questions
1. What is the OOP concept? Define classes and objects in Python.
2. Explain the OOP principle inheritance in Python.
3. What is docstring in Python?
4. Differentiate between method overloading and method overriding.
5. What is the use of pass in Python?
6. What is __init__.py? Give an example.
7. How can we count the number of instances in a program?
8. How can we copy an object in Python?
9. What will be the output of the given code? Explain your answer.
classParent (object):
a=1
class Child1(Parent):
pass
class Child2(Parent):
pass
print Parent.a,Child1.a,Child2.a
Child2.a=5
print Parent.a,Child1.a,Child2.a
Parent.a=4
print Parent.a,Child1.a,Child2.a
10. Consider the code of dictionary:
classSubDict(dict):
def __missing__(self, key):
return[]
Classes and Objects 239
Practice Problem 1 Write a program to determine the Greatest Common Divisor (GCD) of two numbers.
Algorithm
Step 1 - Start
Step 2 – Accept the two numbers whose GCD is to be found (num1, num2)
Step 3 – Call function GCD(num1,num2)
Step 4 – Display the value returned by the function call GCD(num1,num2)
Step 5 – Stop
GCD(a,b)
Step 1 – Start
Step 2 – If b > a goto Step 3 else goto Step 4
Step 3 – Return the result of the function call GCD(b,a) to the calling
function
Step 4 – If b = 0 goto Step 5 else goto Step 6
Step 5 – Return the value a to the calling function
Step 6 – Return the result of the function call GCD(b,a mod b) to the calling
function
Practice Exercises with Algorithm and Flow Chart 241
Flow Chart
Yes Return
Is b > a? GCD (b, a)
Call GCD (num1, num2)
No
No
Stop
Return
GCD (b, a%b)
Output
GCD of 18 and 12 is 6
Practice Problem 2 Write a program to accept two complex numbers and find their sum.
Algorithm
Step 1 - Start
Step 2 – Define a structure to represent a complex number
STRUCTURE complex
REAL real
REAL img
END STRUCTURE
STRUCTURE complex c1, c2
Step 3 – Read the real and imaginary parts of the first complex number
(c1.real, c1.img)
Step 4 – Read the real and imaginary parts of the second complex number
(c2.real, c2.img)
Step 5 – Calculate c3.real=c1.real+c2.real
Step 6 – Calculate c3.img=c1.img+c2.img
Step 7 – Display c3
Step 8 - Stop
242 Introduction to Computing & Problem Solving using Python
Flow Chart
Start
Read c1.real,c1.img
Read c2.real,c2.img
c3.real=c1.real+c2.real
c3.img=c1.img+c2.img
Display c3
Stop
Output
Practice Problem 3 Write a program to simulate a simple calculator for performing basic arithmetic
operations.
Algorithm
Step 1 - Start
Step 2 – Display a list of operations for the user to choose from
1. Addition
2. Subtraction
3. Multiplication
4. Division
Step 3 – Read the choice entered by the user (choice)
Step 4 – Read the two operands (num1, num2)
Step 5 – If choice = 1 goto Step 6 else goto Step 7
Step 6 – Calculate num1 + num2, display the result and goto Step 14
Step 7 – If choice = 2 goto Step 8 else goto Step 9
Step 8 – Calculate num1 - num2, display the result and goto Step 14
Step 9 - If choice = 3 goto Step 10 else goto Step 11
Step 10 - Calculate num1 X num2, display the result and goto Step 14
Step 11 - If choice = 4 goto Step 12 else goto Step 13
Step 12 - Calculate num1 / num2, display the result and goto Step 14
Step 13 – Display the message “Invalid Choice”
Step 14 - Stop
Practice Exercises with Algorithm and Flow Chart 243
Flow Chart
Start
Is Yes
choice Result = num1 + num2 Display result
=1?
No
Is Yes
choice Result = num1 – num2 Display result
=2?
No
Is Yes
choice Result = num1 * num2 Display result
=3?
No
Is
Yes
choice Result = num1/num2 Display result
=4?
No
Display “Invalid Choice”
Stop
Output
**********Simple Calc***********
Step 1 - Start
Step 2 – Pass the system generated time value as a seed to the srand function,
srand(time(NULL))
Step 3 – Call the rand function to generate a random number, rand()
Step 4 – Display the generated random number value
Step 5 – Stop
Flow Chart
Start
srand(time(NULL))
rand()
Stop
Output
Step 1 - Start
Step 2 – Set b = 1 and y = 0
Step 3 – Read the number of rows for the Pascal’s triangle (row)
Step 4 – Repeat Steps 5-17 while y < row
Step 5 – Initialise the looping counter x = 40-3*y
Step 6 – Repeat Steps 7-8 while x > 0
Step 7 – Print a blank space on the output screen
Step 8 – x = x - 1
Step 9 – Initialize the looping counter z = 0
Step 10 – Repeat Steps 11-15 while z <= y
Step 11 – If z = 0 OR y = 0 goto Step 12 else goto Step 13
Step 12 – b = 1
Practice Exercises with Algorithm and Flow Chart 245
Step 13 – b=(b*(y-z+1))/z
Step 14 – Display the value of b in a field width of 6 characters
Step 15 – z = z + 1
Step 16 – Print a new line character
Step 17 - y = y + 1
Step 18 - Stop
Flow Chart
Start
b=1
y=0
Read row
Is No
y<row? Stop
Yes
x = 40 – 3*y
Is x>0? No z=0
Yes
Is z<=y? No
Print one blank space Print new line
Is z = 0 No b=(b*(y–z+1))/z
& y = 0?
Display b
Yes
b=1
246 Introduction to Computing & Problem Solving using Python
Output
******Pascal’s Triangle******
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
Step 1 - Start
Step 2 – Read a value for generating the pyramid (num)
Step 3 – Set x = 40
Step 4 – Initialize the looping counter y=0
Step 5 – Repeat Steps 6-12 while y <= num
Step 6 – Move to the coordinate position (x,y+1)
Step 7 – Initialise the looping counter i=0-y
Step 8 – Repeat Steps 9-10 while i <= y
Step 9 – Display the absolute value of i, abs(i)
Step 10 – i = i + 1
Step 11 – x = x – 3
Step 12 - y = y + 1
Step 13 - Stop
Practice Exercises with Algorithm and Flow Chart 247
Flow Chart
Start
Read num
x = 40
y=0
Is No
y<=num?
Yes
x= x – 3 goto xy (x, y + 1)
i=0–y
No
Is i<=y?
i=i+1
Yes
Display absolute(i)
Stop
248 Introduction to Computing & Problem Solving using Python
Output
0
Enter a number for 1 0 1
generating the pyramid: 2 1 0 1 2
7 3 2 1 0 1 2 3
4 3 2 1 0 1 2 3 4
5 4 3 2 1 0 1 2 3 4 5
6 5 4 3 2 1 0 1 2 3 4 5 6
7 6 5 4 3 2 1 0 1 2 3 4 5 6 7
Practice Problem 7 Write a program to find the one’s compliment of a binary number.
Algorithm
Step 1 - Start
Step 2 – Read a binary number string (a[])
Step 3 – Initialise the looping counter i=0
Step 4 – Repeat Steps 5-9 while a[i] != ‘\0’
Step 5 – If a[i]!= 0 AND a[i]!= 1 goto Step 6 else goto Step 7
Step 6 – Display error “Incorrect binary number format” and terminate the
program
Step 7 – If a[i] = 0 goto Step 8 else goto Step 9
Step 8 – b[i]=’1’
Step 9 – b[i]=’0’
Step 10 – b[i] = ‘\0’
Step 11 – Display b[] as the one’s compliment of the binary number a[]
Step 12 - Stop
Practice Exercises with Algorithm and Flow Chart 249
Flow Chart
Start
i=0
Is No
a[i]!=‘\0’?
Yes
Is a[i]!=0
& Yes
b[i] = ‘\0’
a[i]!=1?
Display “Incorrect
Display b[] as
Binary Number
No Format” the one’s
compliment
No
Is a[i]=0?
Yes
b[i] = 1 b[i] = 0
Stop
250 Introduction to Computing & Problem Solving using Python
Output
Practice Problem 8 Write a program to find the two’s compliment of a binary number.
Algorithm
Step 1 - Start
Step 2 – Read a binary number string (a[])
Step 3 - Calculate the length of string str (len)
Step 4 – Initialise the looping counter k=0
Step 5 – Repeat Steps 6-8 while a[k] != ‘\0’
Step 6 – If a[k]!= 0 AND a[k]!= 1 goto Step 7 else goto Step 8
Step 7 – Display error “Incorrect binary number format” and terminate the
program
Step 8 – k = k + 1
Step 9 – Initialise the looping counter i = len - 1
Step 10 – Repeat Step 11 while a[i]!=’1’
Step 11 – i = i - 1
Step 12 – Initialise the looping counter j = i - 1
Step 13 – Repeat Step 14-17 while j >= 0
Step 14 – If a[j]=1 goto Step 15 else goto Step 16
Step 15 – a[j]=’0’
Step 16 – a[j]=’1’
Step 17 – j = j - 1
Step 18 – Display a[] as the two’s compliment
Step 19 - Stop
Practice Exercises with Algorithm and Flow Chart 251
Flow Chart
Start
Is a[i]!=1? No
len = strlen(a)
k=0
Yes
i=i–1
Is
No i = len –1
a[k]!=‘\0’
?
Yes j=i–1
k=k+1
No
Is a[k]!=0 Is j>=0?
Yes
&
j = j –1
a[k]!=1?
Yes
Display a[]
Display “Incorrect as the two’s
Binary Number compliment
No No
Format” Is a[j]=1?
Yes
a[j] = 0 a[j] = 1
Stop
252 Introduction to Computing & Problem Solving using Python
Output
Practice Problem 9 Write a program to find the number of instances of different digits in a given number.
Algorithm
Step 1 - Start
Step 2 – Read an integer number (num)
Step 3 – Repeat steps 4-25 while (num!=0)
Step 4 – Calculate temp = num % 10
Step 5 – If temp = 0 goto Step 6 else goto Step 7
Step 6 – Increment the 0-digit counter by 1 (d0=d0+1)
Step 7 – If temp = 1 goto Step 8 else goto Step 9
Step 8 – Increment the 1-digit counter by 1 (d1=d1+1)
Step 9 – If temp = 2 goto Step 10 else goto Step 11
Step 10 – Increment the 2-digit counter by 1 (d2=d2+1)
Step 11 – If temp = 3 goto Step 12 else goto Step 13
Step 12 – Increment the 3-digit counter by 1 (d3=d3+1)
Step 13 – If temp = 4 goto Step 14 else goto Step 15
Step 14 – Increment the 4-digit counter by 1 (d4=d4+1)
Step 15 – If temp = 5 goto Step 16 else goto Step 17
Step 16 – Increment the 5-digit counter by 1 (d5=d5+1)
Step 17 – If temp = 6 goto Step 18 else goto Step 19
Step 18 – Increment the 6-digit counter by 6 (d6=d6+1)
Step 19 – If temp = 7 goto Step 20 else goto Step 21
Step 20 – Increment the 7-digit counter by 1 (d7=d7+1)
Step 21 – If temp = 8 goto Step 22 else goto Step 23
Step 22 – Increment the 8-digit counter by 1 (d8=d8+1)
Step 23 – If temp = 9 goto Step 24 else goto Step 25
Step 24 – Increment the 9-digit counter by 1 (d9=d9+1)
Step 25 – Set num = num / 10
Step 26 – Display the number of instances of digits (0-9) present in the
number num (d0, d1, d2, d3, d4, d5, d6, d7, d8, d9)
Step 27 - Stop
Practice Exercises with Algorithm and Flow Chart 253
Flow Chart
R
Start
Display d0, d1, d2, d3, d4, d5, d6, d7, d8, d9
Read num
Stop
No Is
R num = num / 10
num!=0?
d5 =
d5 + 1
Yes Is Yes
temp =5?
temp=num%10
No
d6 =
d6 + 1
Is Yes
temp =0? d0 = d0 + 1 Is Yes
temp =6?
Yes No
d7 =
d7 + 1
Is Yes
temp =1? d1 = d1 + 1 Is Yes
temp =7?
No
No
d8 =
d8 + 1
Is Yes
temp =2? d2 = d2 + 1 Is Yes
temp =8?
No
No
d9 =
d9 + 1
Is Yes
temp =3? d3 = d3 + 1 Is Yes
temp =9?
No
No
Is Yes
temp =4? d4 = d4 + 1
No
254 Introduction to Computing & Problem Solving using Python
Output
Practice Problem 10 Write a program to find the number of vowels and consonants in a text string.
Algorithm
Step 1 - Start
Step 2 – Read a text string (str)
Step 3 – Set vow = 0, cons = 0, i = 0
Step 4 – Repeat steps 5-8 while (str[i]!=’\0’)
Step 5 – if str[i] = ‘a’ OR str[i] = ‘A’ OR str[i] = ‘e’ OR str[i] = ‘E’ OR
str[i] = ‘i’ OR str[i] = ‘I’ OR str[i] = ‘o’ OR str[i] = ‘O’ OR str[i] = ‘u’
OR str[i] = ‘U’ goto Step 6 else goto Step 7
Step 6 – Increment the vowels counter by 1 (vow=vow+1)
Step 7 – Increment the consonants counter by 1 (cons=cons+1)
Step 8 – i = i + 1
Step 9 – Display the number of vowels and consonants (vow, cons)
Step 10 – Stop
Practice Exercises with Algorithm and Flow Chart 255
Flow Chart
Start
vow = 0
cons = 0
i=0
No
i=i+1
Yes
Output
Number of Vowels = 3
Number of Consonants = 4
256 Introduction to Computing & Problem Solving using Python
Practice Problem 11 Write a program that uses a simple structure for storing different students’ details.
Algorithm
Step 1 - Start
Step 2 – Define a simple structure to store student details
STRUCTURE student
STRING name
INTEGER rollno
INTEGER t_marks
END STRUCTURE
STRUCTURE student std[]
Step 3 – Read the number of students for which details are to be entered (num)
Step 4 – Initialise looping counter i = 0
Step 5 – Repeat Steps 6=8 while i < num
Step 6 – Read student’s name, roll no and total marks (std[i].name,
std[i].rollno, std[i].t_marks)
Step 7 – i = i + 1
Step 8 – Display the different students’ details stored in structure array
std[]
Step 9 - Stop
Flow Chart
Start
Read num
i=0
No Is i <
num?
Yes
Stop
Practice Exercises with Algorithm and Flow Chart 257
Output
Name Arjun
Roll No. 1
Name Binoy
Roll No. 2
Name Chitra
Roll No. 3
student 2
Name Binoy
Roll No. 2
Total Marks 432
student 3
Name Chitra
Roll No. 3
Total Marks 402
Practice Problem 12 Write a program to find the sum of the following series:
1 + x + x2 + x3 + …… + xn
258 Introduction to Computing & Problem Solving using Python
Algorithm
Step 1 - Start
Step 2 – Read the values of x and n
Step 3 – If n <= 0 OR x <=0 goto Step 4 else goto Step 5
Step 4 – Display error “Invalid values” and terminate the program
Step 5 – Set sum = 1
Step 6 – Initialise the looping counter i = 1
Step 7 – Repeat Steps 8-9 while i<=n
Step 8 – sum = sum + POWER(x,i)
Step 9 – i = i + 1
Step 10 – Display sum as the resultant sum of the series
Step 11 – Stop
Flow Chart
Start
Read x, n
Is x <=0
Yes Display
OR
“Invalid Values”
n<=0?
No
sum = 1
i=1
No Display sum of
Is i<=n? series (sum)
Yes
sum = sum + POWER(x,y) Stop
i=i+1
Practice Exercises with Algorithm and Flow Chart 259
Output
Practice Problem 13 Write a program to find the sum of the following series:
1 + 2 + 3 + …+ n
Algorithm
Step 1 - Start
Step 2 – Read n
Step 3 – Set sum = 0
Step 4 – Initialise the looping counter i = 1
Step 5 – Repeat Steps 6-8 while i<=n
Step 6 – sum = sum + i
Step 7 – i = i + 1
Step 8 – Display sum as the resultant sum of the series
Step 9 – Stop
Flow Chart
Start
Read n
sum = 0
i=1
No Display sum
Is i <= n?
i=i+1
Yes
Stop
sum = sum + i
260 Introduction to Computing & Problem Solving using Python
Output
Practice Problem 14 Write a program to print the value and address of variables.
Algorithm
Step 1 - Start
Step 2 – Read the values of x and y
Step 3 – Determine the addresses of x and y using ampersand (&) operator (&x, &y)
Step 4 – Print the address and value of x (&x, *&x)
Step 5 – Print the address and value of y (&y, *&y)
Step 6 – Stop
Flow Chart
Start
Read x, y
Stop
Practice Exercises with Algorithm and Flow Chart 261
Output
Practice Problem 15 Write a program to copy the contents of one file into another.
Algorithm
Step 1 - Start
Step 2 – Read the command line arguments (argc, argv)
Step 3 – If argc !=3 goto Step 4 else goto Step 5
Step 4 – Display “Invalid number of arguments” and terminate the program
Step 5 – Open the source file specified by argv[1] in read mode and assign
its starting location to file pointer fs (fs = fopen(argv[1],”r”))
Step 6 – If fs=NULL goto Step 7 else goto Step 8
Step 7 – Display “Source file cannot be opened” and terminate the program
Step 8 – Open the target file specified by argv[2] in write mode and assign
its starting location to file pointer ft (ft = fopen(argv[2],”w”))
Step 9 – If ft=NULL goto Step 10 else goto Step 11
Step 10 – Display “Target file cannot be opened” and terminate the program
Step 11 – Repeat Steps 12-14 indefinitely
Step 12 – Read the first character of the source file (ch)
Step 13 – If ch = EOF goto Step 15 else goto Step 14
Step 14 – Copy character ch into the target file
Step 15 – Close the file pointers fs and ft
Step 16 – Display “Files copied successfully”
Step 17 - Stop
262 Introduction to Computing & Problem Solving using Python
Flow Chart
Start
No
fs = fopen(argv[1], "r")
No
ft = fopen(argv[2], "w")
No
ch=fgetc(fs)
Display “File
copy operation
Is ch Yes fclose(fs) performed
=EOF? fclose(ft)
successfully”
No
fputc(ch,ft)
Practice Exercises with Algorithm and Flow Chart 263
Output
Step 1 - Start
Step 2 – Read the command line arguments (argc, argv)
Step 3 – Initialise count = 0
Step 4 – If argc !=2 goto Step 5 else goto Step 6
Step 5 – Display “Invalid number of arguments” and terminate the program
Step 6 - Open the source file specified by argv[1] in read mode and assign
its starting location to file pointer fs (fs = fopen(argv[1],”r”))
Step 7 – If fs=NULL goto Step 8 else goto Step 9
Step 8 – Display “Source file cannot be opened” and terminate the program
Step 9 – Repeat Steps 10-12 indefinitely
Step 10 – Read the first character of the source file (ch)
Step 11 – If ch = EOF goto Step 13 else goto Step 12
Step 12 – count = count + 1
Step 13 – Close the file pointer fs
Step 14 – Display count as the number characters contained in the source file
Step 15 - Stop
264 Introduction to Computing & Problem Solving using Python
Flow Chart
Start
count = 0
No
fs = fopen(argv[1], "r")
No
ch=fgetc(fs)
No
count = count + 1
Output
D:\TC\BIN>16.exe s1.txt
Step 1 - Start
Step 2 – Read a 3 X 3 matrix (a[3][3])
Step 3 – Initialise the looping counter i = 0
Step 4 – Repeat Steps 5-9 while i<3
Step 5 – Initialize the looping counter j = 0
Step 6 - Repeat Steps 7-8 while j<3
Step 7 – b[i][j]=a[j][i]
Step 8 – j = j + 1
Step 9 – i = i + 1
Step 10 – Display b[][] as the transpose of the matrix a[][]
Step 11 – Stop
Flow Chart
Start
Read a[3][3]
i=0
Yes
j=0
i=i+1
No
Is j < 3? Stop
Yes j=j+1
b[i][j] = a[j][i]
266 Introduction to Computing & Problem Solving using Python
Output
Enter a 3 X 3 matrix:
a[0][0] = 1
a[0][1] = 2
a[0][2] = 3
a[1][0] = 4
a[1][1] = 5
a[1][2] = 6
a[2][0] = 7
a[2][1] = 8
a[2][2] = 9
1 2 3
4 5 6
7 8 9
1 4 7
2 5 8
3 6 9
Step 1 - Start
Step 2 – Read two 3 X 3 matrices (a[3][3], b[3][3])
Step 3 – Initialize the looping counter i = 0
Step 4 – Repeat Steps 5-9 while i<3
Step 5 – Initialise the looping counter j = 0
Step 6 - Repeat Steps 7-8 while j<3
Step 7 – c[i][j] = a[i][j] + b[i][j]
Step 8 – j = j + 1
Step 9 – i = i + 1
Step 10 - Display c[][] as the resultant sum of the two matrices
Step 11 - Stop
Practice Exercises with Algorithm and Flow Chart 267
Flow Chart
Start
i=0
Yes
j=0
i=i+1
No
Is j < 3? Stop
Yes j=j+1
c[i][j] = a[i][j] + b[i][j]
Output
1 1 1 2 2 2
1 1 1 2 2 2
1 1 1 2 2 2
3 3 3
3 3 3
3 3 3
Step 1 - Start
Step 2 – Read two 3 X 3 matrices (a[3][3], b[3][3])
Step 3 – Initialise the looping counter i = 0
Step 4 – Repeat Steps 5-13 while i<3
Step 5 – Initialise the looping counter j = 0
Step 6 - Repeat Steps 7-12 while j<3
Step 7 – c[i][j]=0
Step 8 - Initialise the looping counter k = 0
Step 9 - Repeat Steps 10-11 while k<3
Step 10 - c[i][j]=c[i][j]+a[i][k]*b[k][j]
Step 11 – k = k + 1
Step 12 – j = j + 1
Step 13 – i = i + 1
Step 14 - Display c[][] as the resultant product of the two matrices
Step 15 - Stop
Practice Exercises with Algorithm and Flow Chart 269
Flow Chart
Start
i=0
Yes
j=0
i=i+1
No
Is j < 3? Stop
Yes
c[i][j] = 0
j=j+1 k=0
No
Is k < 3?
Yes k=k+1
c[i][j] = c[i][j] + a[i][k]*b[k][j]
Output
1 2 3 1 1 1
4 5 6 2 2 2
7 8 9 3 3 3
14 14 14
32 32 32
50 50 50
Practice Problem 20 Write a program that uses insertion sort technique to sort an array of ten elements.
Algorithm
Step 1 - Start
Step 2 – Accept a ten element array which needs to be sorted (num[])
Step 3 – Call function i_sort(num)
Step 4 – Display the sorted array num[]
Step 5 – Stop
i_sort(num[])
Step 1 – Start
Step 2 – Initialise the looping counter j = 1
Step 3 – Repeat Steps 4–10 while j<10
Step 4 – Set temp = num[j]
Step 5 – Initialise the looping counter i = j-1
Step 6 – Repeat Steps 7–8 while i>=0 AND temp<num[i]
Step 7 – num[i+1]=num[i]
Step 8 – i = i - 1
Step 9 – num[i+1]=temp
Step 10 – j = j + 1
Step 11 - Stop
Practice Exercises with Algorithm and Flow Chart 271
Flow Chart
Start i_sort(num)
Read num[10]
j=1
Call i_sort(num)
No Is
Stop j<10?
temp=num[j], i = j–1
j=j+1
Stop
Is i>=0
No num[i+1]=temp
AND
temp<num[i]
i=i–1
Yes
num[i+1]=num[i]
Output
18
7
54
78
5
Practice Problem 21 Write a program that uses bubble sort technique to sort an array of ten elements.
Algorithm
Step 1 - Start
Step 2 – Accept a ten element array which needs to be sorted (num[])
Step 3 – Call function bubblesort(num)
Step 4 – Display the sorted array num[]
Step 5 – Stop
bubblesort(num[])
Step 1 – Start
Step 2 – Initialise the looping counter i = 0
Step 3 – Repeat Steps 4–9 while i<9
Step 4 – Initialise the looping counter j = i
Step 5 – Repeat Steps 6–8 while j<10
Step 6 – If num[i] > num[j] goto Step 7 else goto Step 8
Step 7 – Swap the values of num[i] and num[j]
Step 8 – j = j + 1
Step 9 – i = i + 1
Step 10 - Stop
Practice Exercises with Algorithm and Flow Chart 273
Flow Chart
Start bubblesort(num)
Read num[10]
i=0
Call bubblesort(num)
Stop No
Is i<9?
j=i
i=i+1
Stop
No
Is j<10
j=j+1
Yes
No Is
num[i]>num[j]
Yes
temp = num[i]
num[i] = num[j]
num[j] = temp
274 Introduction to Computing & Problem Solving using Python
Output
Enter element 2: 99
Enter element 3: 3
Enter element 4: 85
Enter element 5: 19
Enter element 6: 74
Enter element 7: 5
Enter element 8: 59
Enter element 9: 18
[1], [99], [3], [85], [19], [74], [5], [59], [18], [33],
[1], [3], [5], [18], [19], [33], [59], [74], [85], [99],
Step 1 - Start
Step 2 – Reserve a 100 element array in the memory stack[100] and set its
top pointer to -1 (top = -1)
Step 3 – Repeat Steps 4-15 indefinitely
Step 4 – Display a list of stack operations for the user to choose from
1. Push an element into the stack
2. Pop out an element from the stack
3. Display the stack elements
4. Exit
Practice Exercises with Algorithm and Flow Chart 275
push(element)
Step 1 – Start
Step 2 – If top = 99 goto Step 3 else goto Step 4
Step 3 – Display message ”Stack Full” and exit
Step 4 – top = top + 1
Step 5 – Stack[top] = element
Step 6 – Stop
pop()
Step 1 – Start
Step 2 – If top = -1 goto Step 3 else goto Step 4
Step 3 – Display message ”Stack Empty” and exit
Step 4 – Return stack[top] and set top = top - 1
Step 5 – Stop
display()
Step 1 – Start
Step 2 – Set i = 0
Step 3 – Repeat steps 4-5 while i<=top
Step 4 – Display stack[i]
Step 5 – i = i + 1
Step 6 – Stop
276 Introduction to Computing & Problem Solving using Python
Flow Chart
Start
top = –1
Read choice
Is Yes
choice Read num 1 push(num1)
=1?
No
Is Yes
choice num2 = pop() Display num2
=2?
No
Is Yes
choice display()
=3?
No
Is
Yes Stop
choice
=4?
No
No No
display ()
i=0
i=i+1
No
Stop
Output
Your choice: 1
278 Introduction to Computing & Problem Solving using Python
Your choice: 1
Your choice: 3
Your choice: 2
Your choice: 4
Practice Exercises with Algorithm and Flow Chart 279
Step 1 - Start
Step 2 - Define a structure to represent a stack
STRUCTURE stack
INTEGER element
STRUCTURE stack *stptr
END STRUCTURE
STRUCTURE stack *top
Step 3 – Repeat Steps 4-X indefinitely
Step 4 – Display a list of stack operations for the user to choose from
1. Push an element into the stack
2. Pop out an element from the stack
3. Display the stack elements
4. Exit
Step 5 – Read the choice entered by the user (choice)
Step 6 – If choice = 1 goto Step 7 else goto Step 9
Step 7 – Read the element to be pushed (num1)
Step 8 - Call the push function, push(num1) and goto Step 3
Step 9 – If choice = 2 goto Step 10 else goto Step 12
Step 10 – Call the pop function, pop()
Step 11 - Display the popped element and goto Step 3
Step 12 - If choice = 3 goto Step 13 else goto Step 14
Step 13 - Call the display function, display() and goto Step 3
Step 14 - If choice = 4 goto Step 16 else goto Step 15
Step 15 – Display message “Invalid Choice” and goto Step 3
Step 16 – Stop
push(value)
Step 1 – Start
Step 2 – Reserve a block of memory of size stack and assign its address to
pointer ptr, (ptr=(struct stack*)malloc(sizeof(struct stack)))
Step 3 – Set ptr->element = value
Step 4 – Set ptr->stptr=top
Step 5 – top = ptr
Step 6 – Return
pop()
Step 1 – Start
Step 2 – If top = NULL goto Step 3 else goto Step 4
Step 3 – Display message ”Stack Empty” and exit
Step 4 – Set temp=top->element
Step 5 – Set top=top->stptr
Step 6 - return (temp)
display()
Step 1 – Start
280 Introduction to Computing & Problem Solving using Python
Step 2 – Create a pointer (ptr1) of type stack and assign it the value
contained in top, (struct stack *ptr1=top)
Step 3 – Repeat steps 4-5 while ptr1!=NULL
Step 4 – Display ptr1->element
Step 5 – ptr1=ptr1->stptr
Step 6 – Stop
Flow Chart
Start
Read choice
Is Yes
choice Read num 1 push(num1)
=1?
No
Is Yes
choice num2 = pop() Display num2
=2?
No
Is Yes
choice display()
=3?
No
Is
Yes Stop
choice
=4?
No
display ()
Is
ptr1!= Yes Display
NULL? ptr1->element
No
Stop
Output
Your choice: 1
Your choice: 1
Your choice: 3
Your choice: 2
Your choice: 4
Practice Problem 24 Write a program that uses linear search technique to search an element in an array.
Algorithm
Step 1 - Start
Step 2 – Read a 10 element array (array[])
Step 3 – Read the element that needs to be searched (element)
Step 4 – Set flag = 0
Step 5 – Initialise the looping counter j = 0
Step 6 – Repeat Steps 7-9 while j<10
Step 7 – If array[j] = element goto Step 8 else goto Step 9
Practice Exercises with Algorithm and Flow Chart 283
Step 8 – Display j as the location where element has been found, set flag =
1 and goto Step 10
Step 9 – Set j = j + 1
Step 10 – If flag = 0 goto Step 11 else goto Step 12
Step 11 – Display message “element not found in the array”
Step 12 - Stop
Flow Chart
Start
Read array[10]
Read element
flag = 0
j=0
No
Is j <10?
Yes
j=j+1
Display j as the
No Is array[j] Yes
location of element in
=element?
array
flag = 1
No
Is flag=0?
Yes
Display
“Element Not Found”
Stop
284 Introduction to Computing & Problem Solving using Python
Output
Practice Problem 25 Write a program that uses binary search technique to search an element in an array.
Algorithm
Step 1 - Start
Step 2 – Read a 10 element array (array[])
Step 3 – Read the element that needs to be searched (element)
Step 4 – Set flag = 0
Step 5 – Set i = o, j = 10
Step 6 – Repeat Steps 7-12 while i<=j
Step 7 – k = (i+j)/2
Step 8 – If array[k] = element goto Step 9 else goto Step 10
Step 9 – Display k+1 as the location where element has been found, set flag
= 1 and goto Step 13
Step 10 – If array[k] < element goto Step 11 else goto Step 12
Step 11 – i = k + 1
Step 12 – j = k-1
Step 13 – If flag = 0 goto Step 14 else goto Step 15
Step 14 – Display message “Element not found”
Step 15 = Stop
Practice Exercises with Algorithm and Flow Chart 285
Flow Chart
Start
Read array[10]
Read element
flag = 0
i = 0, j = 10
No
Is i <=j?
Yes
k = (i+j)/2
No flag = 1
j=k–1 No Is array[k] No
=element? Is flag=0?
Yes
Yes
i=k+1 Display
“Element Not Found”
Stop
286 Introduction to Computing & Problem Solving using Python
Output
Enter the 10 elements of the list in ascending order:
1
3
5
6
13
19
27
33
99
102
Algorithm
Step 1 - Start
Step 2 – Read n
Step 3 – Set sum = 1.0
Step 4 – Set i = 2.0
Step 5 – Repeat Steps 6-7 while i<=n
Step 6 – sum = sum + 1.0/i
Step 7 – i = i + 1
Step 8 – Display sum as the resultant sum of the series
Step 9 – Stop
Practice Exercises with Algorithm and Flow Chart 287
Flow Chart
Start
Read n
sum = 1.0
i = 2.0
No
Is i <=n? Display sum
i=i+1
Yes
Stop
sum = sum + 1.0/i
Output
Step 1 - Start
Step 2 – Set gd = DETECT
Step 3 – Call in-build function, initgraph(&gd, &gm, “..\\bgi”)
Step 4 – Call in-built function, circle(320, 225, 50)
Step 5 – closegraph()
Step 6 – Stop
288 Introduction to Computing & Problem Solving using Python
Flow Chart
Start
gd = DETECT
close graph()
Stop
Output
Practice Exercises with Algorithm and Flow Chart 289
Step 1 - Start
Step 2 – Set gd = DETECT
Step 3 – Call in-build function, initgraph(&gd, &gm, “..\\bgi”)
Step 4 – Call in-built function, rectangle(320, 225, 50,100)
Step 5 – closegraph()
Step 6 – Stop
Flow Chart
Start
gd = DETECT
close graph()
Stop
290 Introduction to Computing & Problem Solving using Python
Output
Step 1 - Start
Step 2 – Set gd = DETECT
Step 3 – Call in-build function, initgraph(&gd, &gm, “..\\bgi”)
Step 4 – Call in-built function, bar3d(150, 50, 250,150, 10, 1)
Step 5 – closegraph()
Step 6 – Stop
Flow Chart
Start
gd = DETECT
closegraph()
Stop
Practice Exercises with Algorithm and Flow Chart 291
Output
Practice Problem 30 Write a program to draw a shape and fill it with color.
Algorithm
Step 1 - Start
Step 2 – Set gd = DETECT
Step 3 – Call in-build function, initgraph(&gd, &gm, “..\\bgi”)
Step 4 - Call in-build function, setfillstyle(SOLID_FILL,RED)
Step 4 – Call in-built function, bar3d(150, 50, 250,150, 10, 1)
Step 5 – closegraph()
Step 6 – Stop
Flow Chart
Start
gd = DETECT
setfillstyle(SOLID_FILL,RED)
closegraph()
Stop
292 Introduction to Computing & Problem Solving using Python
Output
Appendix
PROBLEM SOLVING
B EXERCISES—WITH ALGO-
RITHM AND PSEUDOCODE
Step 1 - Start
Step 2 – Accept the length of the Fibonacci series from the user (len)
Step 3 – Initialise variables num1 = 0, num2 = 1
Step 4 – Display the values of num1 and num2
Step 5 – Initialise looping counter i = 1
Step 6 – Repeat Steps 7-11 while i <= len-2
Step 7 – Set fab = num1 + num2
Step 8 – Display the value of fab
Step 9 – Set num1 = num2
Step 10 – Set num2 = fab
Step 11 – Increment the value of i by 1
Step 12 - Stop
294 Introduction to Computing & Problem Solving using Python
Flow Chart
Start
Read len
num1 = 0
num2 = 1
i=1
No
Is i <= len-2?
Yes
fab = num1 + num2
Stop
Display fab
num1 = num2
num2 = fab
i=i+1
Pseudocode
BEGIN
DEFINE: Integer num1, num2, len, i, fab
SET: num1=0, num2=1
DISPLAY: “Enter Length of the Fibonacci Series: “
READ: len
DISPLAY: num1, num2
FOR: i = 1 to len-2
COMPUTE: fab = num1 + num2
DISPLAY: fab
Problem Solving Exercises—With Algorithm and Pseudocode 295
Practice Problem 2 Write a program to find out whether the given number is even or odd.
Algorithm
Step 1 - Start
Step 2 – Accept a number from the user (num)
Step 3 – If remainder of num divided by 2 (num/2) is Zero then goto Step 4
else goto Step 5
Step 4 – Display “num is an even number” and goto Step 6
Step 5 – Display “num is an odd number”
Step 6 - Stop
Flow Chart
Start
Read num
Is No
(num%2)=0?
Yes
Stop
296 Introduction to Computing & Problem Solving using Python
Pseudocode
BEGIN
DEFINE: Integer num
DISPLAY: “Enter a number: “
READ: num
IF: num%2=0
DISPLAY: “’num’ is an even number”
ELSE
DISPLAY: “’num’ is an odd number”
END IF
END
Practice Problem 3 Write a program to find out whether the given number is a prime number.
Algorithm
Step 1 - Start
Step 2 – Accept a number from the user (num)
Step 3 – Initialise looping counter i = 2
Step 4 – Repeat Step 5 while i < num
Step 5 – If remainder of num divided by i (num%i) is Zero then goto Step 6
else goto Step 4
Step 6 - Display “num is not a prime number” and break from the loop
Step 7 – If i = num then goto Step 8 Else goto Step 9
Step 8 – Display “num is a prime number”
Step 9 - Stop
Problem Solving Exercises—With Algorithm and Pseudocode 297
Flow Chart
Start
Read num
i=2
No Is i <=
num-1?
Yes
No
Is num%i=0? i=i+1
Yes
Display “Not a Prime
Number”
No
Stop
Pseudocode
BEGIN
DEFINE: Integer num, i
DISPLAY: “Enter a number: “
READ: num
FOR: i = 2 to num-1
IF: num%i=0
DISPLAY: “’num’ is not a prime number”
BREAK
END IF
298 Introduction to Computing & Problem Solving using Python
END FOR
IF: i=num
DISPLAY: “’num’ is a prime number”
END IF
END
Practice Problem 4 Write a program to display the result of one number raised to the power of another.
Algorithm
Step 1 - Start
Step 2 – Accept two numbers from the user (x,y)
Step 3 – Calculate x raise to the power of y, POWER(x,y)
Step 4 – Display the computed result
Step 5 - Stop
Flow Chart
Start
Read x, y
Stop
Problem Solving Exercises—With Algorithm and Pseudocode 299
Pseudocode
BEGIN
DEFINE: Integer x, y
DEFINE: Long Integer result
DISPLAY: “Enter the values of x and y: “
READ: x, y
COMPUTE: result = POW(x,y)
DISPLAY: “’x’ raised to the power of ‘y’ is equal to ‘result’”
END
Step 1 - Start
Step 2 – Accept a number from the user (num)
Step 3 – Calculate square root of num, Sqrt(num)
Step 4 – Display the computed result
Step 5 - Stop
Flow Chart
Start
Read num
Stop
300 Introduction to Computing & Problem Solving using Python
Pseudocode
BEGIN
DEFINE: Integer num
DEFINE: Real result
DISPLAY: “Enter the value whose square root is to be computed: “
READ: num
COMPUTE: result = SQRT(num)
DISPLAY: “The square root of ‘num’ is ‘result’”
END
Practice Problem 6 Write a program to determine whether a given string is a palindrome or not.
Algorithm
Step 1 - Start
Step 2 – Accept a string from the user (str)
Step 3 – Calculate the length of string str (len)
Step 4 – Initialise looping counters left=0, right=len-1 and chk = ‘t’
Step 5 – Repeat Steps 6-8 while left < right and chk = ‘t’
Step 6 – If str(left) = str(right) goto Step 8 else goto step 7
Step 7 – Set chk = ‘f’
Step 8 – Set left = left + 1 and right = right + 1
Step 9 - If chk=’t’ goto Step 10 else goto Step 11
Step 10 – Display “The string is a palindrome” and goto Step 12
Step 11 – Display “The string is not a palindrome”
Step 12 - Stop
Problem Solving Exercises—With Algorithm and Pseudocode 301
Flow Chart
Start
Read str
len = strlen(str)
left = 0
right = len-1
chk = ‘t’
Yes
Is str(left) = Yes
str(right)?
No
Is chk = ‘t’?
No
Yes
chk = ‘f’
Display “Palindrome Display “Not a
String” Palindrome String”
left = left + 1
right = right – 1
Stop
Pseudocode
BEGIN
DEFINE: String str
DEFINE: Character chk
DEFINE: Integer left, right, len
SET: chk = ‘t’
DISPLAY: “Enter a string: “
READ: str
COMPUTE: len = strlen(str)
302 Introduction to Computing & Problem Solving using Python
SET: left = 0
SET: right = len-1
REPEAT
IF: str(left)=str(right)
CONTINUE
ELSE
SET: chk = ‘f’
END IF
COMPUTE: left = left + 1
COMPUTE: right = right - 1
UNTIL: left<right AND chk=’t’
IF: chk=’t’
DISPLAY: “’str’ is a palindrome string”
ELSE
DISPLAY: “’str’ is not a palindrome string”
END IF
END
Practice Problem 7 Write a program to find the roots of the quadratic equation.
Algorithm
Step 1 - Start
Step 2 – Accept three numbers (a, b, c) from the user for the quadratic
equation ax2 + bx + c
Step 3 – Calculate root1=((-1)*b+sqrt(b*b-4*a*c))/2*a
Step 4 – Calculate root2=((-1)*b-sqrt(b*b-4*a*c))/2*a
Step 5 – Display the computed roots of the quadratic equation
Step 6 - Stop
Flow Chart
Start
Read a, b, c
root1=((–1)*b+sqrt(b*b-4*a*c))/2*a
root2=((–1)*b-sqrt(b*b-4*a*c))/2*a
Stop
Problem Solving Exercises—With Algorithm and Pseudocode 303
Pseudocode
BEGIN
DEFINE: Integer a, b, c
DEFINE: Real root1, root2
DISPLAY: “Enter the values of a, b and c for the quadratic equation ax2 + bx
+ c: “
READ: a, b, c
COMPUTE: root1=((-1)*b+sqrt(b*b-4*a*c))/2*a
COMPUTE: root2=((-1)*b-sqrt(b*b-4*a*c))/2*a
DISPLAY: “The roots of the quadratic equation are ‘root1’ and ‘root2’
END
Step 1 - Start
Step 2 – Accept the radius of the circle from the user (radius)
Step 3 – Calculate area of the circle using formula area = 3.14 * radius *
radius
Step 4 – Display the computed area of the circle
Step 5 - Stop
Flow Chart
Start
Read radius
area = 3.14*radius*radius
Display area
Stop
304 Introduction to Computing & Problem Solving using Python
Pseudocode
BEGIN
DEFINE: Real radius, area
DISPLAY: “Enter the radius of the circle: “
READ: radius
COMPUTE: area = 3.14*radius*radius
DISPLAY: “The area of the circle is ‘area’”
END
Practice Problem 9 Write a program to find the average of marks obtained by a student in three subjects.
Algorithm
Step 1 - Start
Step 2 – Accept the marks in three subjects from the user (marks1, marks2,
marks3)
Step 3 – Calculate average marks using formula, average = (marks1 + marks2
+ marks3)/3
Step 4 – Display the computed average of three subject marks
Step 5 - Stop
Flow Chart
Start
Display average
Stop
Problem Solving Exercises—With Algorithm and Pseudocode 305
Pseudocode
BEGIN
DEFINE: Integer marks1, marks2, marks3
DEFINE: Real average
DISPLAY: “Enter the marks in three subjects: “
READ: marks1, marks2, marks3
COMPUTE: average = (marks1 + marks2 + marks3)/3
DISPLAY: “The average value of marks is ‘average’”
END
Practice Problem 10 Write a program to determine whether the given year is a leap year or not.
Algorithm
Step 1 - Start
Step 2 – Accept an year value from the user (year)
Step 3 – If remainder of year value divided by 4 (year%4) is 0 then goto Step
4 else goto Step 5
Step 4 – Display “’year’ is a leap year” and goto Step 6
Step 5 – Display “’year’ is not a leap year”
Step 6 - Stop
Flow Chart
Start
Read year
Is No
(year%4) = 0?
Yes
Stop
Pseudocode
BEGIN
DEFINE: Integer year
DISPLAY: “Enter the year value: “
READ: year
306 Introduction to Computing & Problem Solving using Python
IF: year%4=0
DISPLAY: “’year’ is a leap year”
ELSE
DISPLAY: “’year’ is not a leap year”
END IF
END
Step 1 - Start
Step 2 – Accept an integer value from the user (num)
Step 3 – Define a variable Sum to store the sum of digits and initialise it
to 0
Step 4 – Assign the value of num to a temporary variable (temp=num)
Step 5 – Repeat Steps 6-7 while temp is not equal to 0 (temp!=0)
Step 6 – Calculate Sum = Sum+(temp%10)
Step 7 – Calculate temp=temp/10
Step 8 – Display Sum as the result containing sum of digits of num
Step 9 - Stop
Flow Chart
Start
Read num
sum = 0
temp = num
No
Is temp ! = 0?
Display sum
Yes
sum = sum+temp%10
temp=temp/10 Stop
Pseudocode
BEGIN
DEFINE: Long Integer num, temp
Problem Solving Exercises—With Algorithm and Pseudocode 307
Step 1 - Start
Step 2 – Accept a string from the user, str
Step 3 – Calculate the length of the string, strlen(str)
Step 4 – Display the computed result
Step 5 - Stop
Flow Chart
Start
Read str
len = strlen(str)
Display len
Stop
Pseudocode
BEGIN
DEFINE: String str
DEFINE: Integer len
DISPLAY: “Enter a string: “
READ: str
308 Introduction to Computing & Problem Solving using Python
Step 1 - Start
Step 2 – Accept a string from the user (str)
Step 3 – Calculate the length of string str (len)
Step 4 – Initialise looping counter i=0
Step 5 – Repeat Step 6-7 while i < len
Step 6 – Set revstr[len-i-1]=str[i]
Step 7 – Set i = i+ 1
Step 8 – Set revstr[len]=’\0’
Step 9 – Display revstr as the reverse of the original string str
Step 10 - Stop
Flow Chart
Start
Read str
len = strlen(str)
i=0
No
Is i <= len-1?
revstr[len]= ‘\0’
Yes
Display revstr
revstr[len-i-1]=str[i]
Stop
Pseudocode
BEGIN
DEFINE: String str, revstr
DEFINE: Integer i, len
DISPLAY: “Enter a string: “
Problem Solving Exercises—With Algorithm and Pseudocode 309
READ: str
COMPUTE: len = strlen(str)
FOR: i = 0 to len-1
COMPUTE: revstr[len-i-1]=str[i]
END FOR
SET: revstr[len]=’\0’
DISPLAY: “The reverse of string ‘str’ is ‘revstr’”
END
Practice Problem 14 Write a program to determine whether there is a profit or a loss during the selling of
an item.
Algorithm
Step 1 - Start
Step 2 – Accept the cost price and selling price of an item from the user
(cp, sp)
Step 3 – If sp>cp then goto step 4 else goto step 5
Step 4 – Display “There is a profit of (sp-cp)” and goto Step 8
Step 5 – If cp>sp then goto step 6 else goto step 7
Step 6 - Display “There is a loss of (cp-sp)”
Step 7 - Display “No profit no loss!”
Step 8 - Stop
Flow Chart
Start
Read cp, sp
No
Is sp > cp?
Yes No
Is cp > sp?
Display profit = sp-cp
Display “No Profit
Yes No Loss”
Stop
310 Introduction to Computing & Problem Solving using Python
Pseudocode
BEGIN
DEFINE: Long Integer cp, sp
DISPLAY: “Enter the cost price and selling price of an item: “
READ: cp, sp
IF: sp>cp
DISPLAY: “There is a profit of ‘sp-cp’”
ELSE
IF: cp>sp
DISPLAY: “There is a loss of ‘cp-sp’”
ELSE
DISPLAY: “No profit no loss!”
END IF
END IF
END
Practice Problem 15 Write a program to print the ASCII value of a given character.
Algorithm
Step 1 - Start
Step 2 – Accept a character from the user (ch)
Step 3 – Determine the ASCII value of ch
Step 4 – Display the computed ASCII value
Step 5 - Stop
Flow Chart
Start
Read ch
asc = ASCII(ch)
Display asc
Stop
Problem Solving Exercises—With Algorithm and Pseudocode 311
Pseudocode
BEGIN
DEFINE: Character ch
DEFINE: Integer asc
DISPLAY: “Enter a character: “
READ: ch
COMPUTE: asc = ASCII(ch)
DISPLAY: “The ASCII value of ‘ch’ is ‘asc’”
END
Practice Problem 16 Write a program to find out whether a given number is positive or negative.
Algorithm
Step 1 - Start
Step 2 – Accept a number from the user (num)
Step 3 – If num is greater than 0 (num>0) then goto Step 4 else goto Step 5
Step 4 – Display “num is a positive number” and goto Step 6
Step 5 – Display “num is a negative number”
Step 6 - Stop
Flow Chart
Start
Read num
No
Is num > 0?
Yes
Stop
312 Introduction to Computing & Problem Solving using Python
Pseudocode
BEGIN
DEFINE: Integer num
DISPLAY: “Enter a number: “
READ: num
IF: num>0
DISPLAY: “’num’ is a positive number”
ELSE
DISPLAY: “’num’ is a negative number”
END IF
END
Step 1 - Start
Step 2 – Accept two strings from the user (str1, str2)
Step 3 – Compare the two strings str1 and str2 using a string comparison
function. If str1 and str2 are same goto Step 4 else goto Step 5
Step 4 – Display “The two strings are equal” and goto Step 6
Step 5 – Display “The two strings are not equal”
Step 6 - Stop
Flow Chart
Start
Is strcmp (str1, No
str2) = 0?
Yes
Stop
Problem Solving Exercises—With Algorithm and Pseudocode 313
Pseudocode
BEGIN
DEFINE: String str1, str2
DISPLAY: “Enter the 1st string: “
READ: str1
DISPLAY: “Enter the 2nd string: “
READ: str2
IF: strcmp(str1, str2)=0
DISPLAY: “The strings str1 and str2 are equal!”
ELSE
DISPLAY: “The strings str1 and str2 are not equal!”
END IF
END
Step 1 - Start
Step 2 – Accept the value of distance traveled in KMs (d)
Step 3 – Accept the value of travel time in hours (t)
Step 4 – Calculate speed using formula, speed = d/t
Step 5 – Display the computed value of speed
Step 6 - Stop
Flow Chart
Start
Read d, t, s
s = d/t
Display s
Stop
314 Introduction to Computing & Problem Solving using Python
Pseudocode
BEGIN
DEFINE: Real d, t, s
DISPLAY: “Enter the distance traveled in Kms: “
READ: d
DISPLAY: “Enter the travel time in hours: “
READ: t
COMPUTE: s = d/t
DISPLAY: “Speed = ‘s’ Km/h”
END
Practice Problem 19 Write a program to find the sine and cosine of a given value.
Algorithm
Step 1 - Start
Step 2 – Accept the degree value, the sine and cosine of which is to be
calculated (x):
Step 3 – Calculate Sin(x) = sin(x*3.14/180)
Step 4 – Calculate Cos(x) = cos(x*3.14/180)
Step 5 – Display the computed Sin(x) and Cos(x) values
Step 6 - Stop
Flow Chart
Start
Read x
sinx = sin(x*3.14/180)
cosx = cos(x*3.14/180)
Stop
Pseudocode
BEGIN
DEFINE: Real x, sinx, cosx
DISPLAY: “Enter the degree value, the sine and cosine of which is to be
calculated: “
READ: x
Problem Solving Exercises—With Algorithm and Pseudocode 315
Practice Problem 20 Write a program to determine whether a given number is Armstrong or not.
Algorithm
Step 1 - Start
Step 2 – Accept a number from the user (num)
Step 3 – Store the value of num in a temporary variable temp, temp=num
Step 4 – Define a variable sum and initialise it to 0
Step 5 – Repeat Steps 6-8 while temp > 0
Step 6 – Calculate i=temp%10;
Step 7 – Calculate sum=sum+i*i*i;
Step 8 – Calculate temp=temp/10;
Step 9 – if num is equal to sum then goto Step 10 else goto Step 11
Step 10 – Display ”num is an Armstrong number” and goto Step 12
Step 11 – Display ”num is not an Armstrong number”
Step 12 - Stop
Flow Chart
Start
Read num
sum = 0
temp = num
No
Is temp > 0?
Yes Is No
sum = num?
i=temp%10
sum=sum+i*i*i Display “Not an
temp=temp/10 Yes Armstrong Number”
Display “Armstrong
Number”
Stop
316 Introduction to Computing & Problem Solving using Python
Pseudocode
BEGIN
DEFINE: Integer num, temp, sum, i
SET: sum = 0
DISPLAY: “Enter a number: “
READ: num
SET: temp=num
REPEAT
COMPUTE: i=temp%10
COMPUTE: sum=sum+i*i*i
COMPUTE: temp=temp/10
UNTIL: temp>0
IF: sum=num
DISPLAY: “’num’ is an Armstrong number”
ELSE
DISPLAY: “’num’ is not an Armstrong number”
END IF
END
Appendix
FUNDAMENTAL
C STANDARD LIBRARY
MODULES
There is a wide range of methods in Python’s standard library. In this section, some fundamental standard
library modules are discussed. Any Python program uses these modules either directly or indirectly.
4. REGULAR EXPRESSIONS
The regular expressions support for Python is provided by re module. Regular expressions are used to match
strings and slice the substrings. They are nothing but the patterns of strings that are written in special syntax.
318 Introduction to Computing & Problem Solving using Python
re Module
re module is a built in module in Python programming language which provides support for regular
expressions. A regular expression consists of some special sequence of characters that helps us in finding
another strings or matching set of strings using some predefined syntax which are kept in a pattern.
When any error occurs while handling the regular expressions, python interpreter throws a re.error
exception.
There are two very important functions in re module which are listed below:
1. match() function
2. search() function
1. match() function
It matches the RE pattern to the string.
Syntax
re.match(pattern, string)
where,
pattern – pattern stands for the regular expression which is to be matched in the string.
string – it is the string in which the searching will be done to match the pattern at the starting of the string.
On successful match, match() function will return a match object, None otherwise.
2. search() function
It searches the first occurrence of the Regular Expression within the given string.
Syntax
re.search(pattern, string)
where,
pattern – pattern stands for the regular expression which is to be matched.
string – it is the string in which the searching will be done to match the pattern anywhere within the string.
On successful search, search() function will return a match object, None otherwise.
sys Module
sys helps in accessing various interpreter variables, such as module search path and interpreter version.
random Module
This module helps in generating random numbers or select a random item from a series or sequence.
time Module
This module measures the number of seconds since ‘epoch’. The standard value of epoch in Unix and
Windows OS is January 1, 1970 and it is January 1, 1900 in Macintosh.
re Module
This is a module that is required for regular expressions. Regular expressions are used to match strings and
slice substrings. These are patterns of strings that are written in special syntax.
Common patterns that are used for forming regular expression are as follows:
os Module
This module provides file manipulation and process operations. Os.path offers a platform-independent
way to put together file names and time that allows functions or methods working with date and time.
tempfile Module
This module is used to create temporary files at the time of execution of a program.