Python Unit 1-4 Notes
Python Unit 1-4 Notes
Python Unit 1-4 Notes
N COLLEGE OF ENGINEERING
(An Autonomous Institution, Affiliated to Anna University – Chennai)
REGULATION: R2020
STUDY MATERIAL
Prepared by
Mrs. C.Sasirekha,
Assistant Professor,
ECE Department,
KLNCE
20GE101 PROBLEM SOLVING USING PYTHON PROGRAMMING L T P C
3 0 0 3
OBJECTIVES:
To know the basics of Computers and algorithmic problem solving
To understand Python programs with conditional and looping constructs.
To define Python functions and strings.
To use Python data structures – lists, tuples, dictionaries.
To do input/output with files in Python.
UNIT - I COMPUTER FUNDAMENTALS AND PROBLEM SOLVING 9
Introduction to Computer System – Block Diagram of Computer, Types of Memory, I/O Devices, Application Programs, System
Programs – Loader, linker, assembler, compiler, interpreter, Programming process – source code to executable code, Problem
Solving Strategies – Problem analysis, Algorithms, Flow Charts, Pseudo Code. Illustrative problems: odd or even number, Leap
year, Biggest of three numbers, square root of a number, Sum of n numbers, Armstrong number, Palindrome, Fibonacci Series,
Prime number, Bubble Sort and Linear Search.
TOTAL: 45 PERIODS
TEXT BOOKS:
1. E. Balagurusamy, “Problem Solving and Python Programming”, First edition, McGraw Hill Education (India) Private
Limited, 2017.
2. Allen B. Downey, ``Think Python: How to Think Like a Computer Scientist‘‘, 2nd edition, Updated for Python 3,
Shroff/O‘Reilly Publishers, 2016 (http://greenteapress.com/wp/think-python/)
REFERENCES:
1. John V Guttag, Introduction to Computation and Programming Using Python‘‘, Revised and expanded Edition, MIT
Press, 2013
2. Robert Sedgewick, Kevin Wayne, Robert Dondero, Introduction to Programming in Python: An Inter-disciplinary
Approach, Pearson India Education Services Pvt. Ltd., 2016.
3. Timothy A. Budd,Exploring Python‖, Mc-Graw Hill Education (India) Private Ltd.,, 2015.
4. Kenneth A. Lambert, Fundamentals of Python: First Programs‖, CENGAGE Learning, 2012.
5. Charles Dierbach, Introduction to Computer Science using Python: A Computational Problem-Solving Focus, Wiley
India Edition, 2013.
6. Paul Gries, Jennifer Campbell and Jason Montojo,Practical Programming: An Introduction to Computer Science using
Python 3‖, Second edition, Pragmatic Programmers, LLC, 2013.
7. Dr. A. Kannan, Dr. L. Sai Ramesh, Problem Solving and Python Programming, Updated Edition, April 2018, United
Global Publishers Pvt. Ltd.
UNIT I COMPUTER FUNDAMENTALS AND PROBLEM SOLVING
INTRODUCTION
What is a computer?
Definitions
A computer is a machine that manipulates data according to a list ofinstructions called a program.
A computer can also be defined as an electronic machine that accepts input (data), processes it and
gives out results (information). A program in memory manages the processing. It can make use of data or
informationstored in memory and remember the results of the processing for later use, again in memory.
A computer is also a (fairly complicated) tool intended to assist the user in accomplishing information-
based tasks ranging from locating and acquiring data/information to to processing it to presenting or
transmitting it.
1. Speed: - As you know computer can work very fast. It takes only few seconds for calculations that we
take hours to complete. You will be surprised to know that computer can perform millions (1,000,000) of
instructions and even more per second.
Therefore, we determine the speed of computer in terms of microsecond (10-6 part of a second) or nanosecond
(10 to the power -9 part of a second).From this you can imagine how fast your computer performs work.
2. Accuracy: - The degree of accuracy of computer is very high and every calculation is performed with
the same accuracy. The accuracy level is 7 determined on the basis of design of computer. The errors in
computer aredue to human and inaccurate data.
3. Diligence: - A computer is free from tiredness, lack of concentration, fatigue, etc. It can work for
hours without creating any error. If millions of calculations are to be performed, a computer will perform every
calculationwith the same accuracy. Due to this capability it overpowers human being in routine type of work.
4. Versatility: - It means the capacity to perform completely different type of work. You may use your
computer to prepare payroll slips. Next moment you may use it for inventory management or to prepare
electric bills.
5. Power of Remembering: - Computer has the power of storing any amount of information or data.
Any information can be stored and recalled as long as you require it, for any numbers of years. It depends
entirely upon you how much data you want to store in a computer and when to lose or retrieve these data.
6. No IQ: - Computer is a dumb machine and it cannot do any work without instruction from the user. It
performs the instructions at tremendous speed and with accuracy. It is you to decide what you want to do and
in what sequence. So a computer cannot take its own decision as you can.
7. No Feeling: - It does not have feelings or emotion, taste, knowledge and experience. Thus it does not
get tired even after long hours of work. It doesnot distinguish between users.
8. Storage: - The Computer has an in-built memory where it can store a large amount of data. You can
also store data in secondary storage devicessuch as floppies, which can be kept outside your computer and can
be carried to other computers.
Block Diagram of Computer
Computers can be generally classified by size and power as follows,though there is considerable
overlap:
Mainframe was a term originally referring to the cabinet containing the central processor unit or "main
frame" of a room-filling Stone Age batch machine. After the emergence of smaller "minicomputer" designs
in the early 1970s, the traditional big iron machines were described as "mainframe computers" and
eventually just as mainframes. Nowadays a Mainframe is a very large and expensive computer capable of
supporting hundreds, or even thousands, of users simultaneously. The chief difference between a
supercomputer and a mainframe is that a supercomputer channels all its power into executing a few programs
as fast as possible, whereas a mainframe uses its power to execute many programs concurrently. In some
ways, mainframes are more powerful than supercomputers because they support more simultaneous
programs. But supercomputers can execute a single program faster than a mainframe. The distinction between
small mainframes and minicomputers is vague, depending really on how the manufacturer wants to market its
machines.
Mini computer
It is a midsize computer. In the past decade, the distinction between large minicomputers and small
mainframes has blurred, however, as has the distinction between small minicomputers and workstations. But
in general, a minicomputer is a multiprocessing system capable of supporting from up to 200 users
simultaneously.
Workstation
It is a type of computer used for engineering applications (CAD/CAM), desktop publishing,
software development, and other types of applications that require a moderate amount of computing power
and relatively high quality graphics capabilities. Workstations generally come with a large, high-resolution
graphics screen, at large amount of RAM, built-in network support, and a graphical user interface. Most
workstations also have a mass storage device such as a disk drive, but a special type of workstation, called a
diskless workstation, comes without a disk drive. The most common operating systems for workstations are
UNIX and Windows NT. Like personal computers, most workstations are single-user computers. However,
workstations are typically linked together to form a local-area network, although they can also be used as
stand-alone systems.
Personal computer:
It can be defined as a small, relatively inexpensive computer designed for an individual user. In price,
personal computers range anywhere from a few hundred pounds to over five thousand pounds. All are based on
the microprocessor technology that enables manufacturers to put an entire CPU on one chip. Businesses use
personal computers for word processing, accounting, desktop publishing, and for running spreadsheet and
database management applications. At home, the most popular use for personal computers is for playing games
and recently for surfing the Internet.
Personal computers first appeared in the late 1970s. One of the first and most popular personal computers
was the Apple II, introduced in 1977 by Apple Computer. During the late 1970s and early 1980s, new models
and competing operating systems seemed to appear daily. Then, in 1981, IBM entered the fray with its first
personal computer, known as the IBM PC. The IBM PC quickly became the personal computer of choice,
and most other personal computer manufacturers fell by the wayside. P.C. is short for personal computer or
IBM PC. One of the few companies to survive IBM's onslaught was Apple Computer, which remains a
major player in the personal computer marketplace. Other companies adjusted to IBM's dominance by building
IBM clones, computers that were internally almost the same as the IBM PC, but that cost less. Because IBM
clones used the same microprocessors as IBM PCs, they were capable of running the same software. Over the
years, IBM has lost much of its influence in directing the evolution of PCs. Therefore after the release of the
first PC by IBM the term PC increasingly came to mean IBM or IBM-compatible personal computers, to the
exclusion of other types of personal computers, such as Macintoshes. In recent years, the term PC has become
more and more difficult to pin down. In general, though, it applies to any personal computer based on an
Intel microprocessor, or on an Intel-compatible microprocessor. For nearly every other component, including
the operating system, there are several options, all of which fall under the rubric of PC
Memory
A memory is just like a human brain. It is used to store data and instructions. Computer memory is the
storage space in computer where data is to be processed and instructions required for processing are stored.
The memory is divided into large number of small parts called cells. Each location or cell has a unique
address which varies from zero to memory size minus one. For example if computer has 64k words, then this
memoryunit has 64 * 1024=65536 memory locations. The address of these locations varies from 0 to 65535.
Memory is primarily of three types
Cache Memory
Primary Memory/Main Memory
Secondary Memory
Cache Memory
Cache memory is a very high speed semiconductor memory which can speed up CPU. It acts as a buffer
between the CPU and main memory. It is used to hold those parts of data and program which are most
frequently used by CPU. The parts of data and programs are transferred from disk to cache memory by
operating system, from where CPU can access them.
Advantages
The advantages of cache memory are as follows:
Cache memory is faster than main memory.
It consumes less access time as compared to main memory.
It stores the program that can be executed within a short period of time.
It stores data for temporary use.
Disadvantages
The disadvantages of cache memory are as follows:
It is very expensive.
RAM stands for Random Access Memory. It is the primary storage for the computer. All programs,
including the operating system, and any data theyare using must be in RAM for the computer to access them.
Whenever I hear the term, I think, "DAM, why'd they call it RAM?" It is called random because the
computer can directly access any location in RAM (using its memory "address"), though we rarely have call
to access memoryrandomly. Thus, Direct Access Memory would have been a better name.
By comparison, a tape (video or audio) is a sequential medium. Accessing a particular note in a song is
virtually impossible and requires scanning forward to find it. An audio editing program working on a song
in RAM can and does directly access any point you want in the song. (Specifying it might be a problem, but
consider cutting a section out to use as a ring tone. Once you specify the end points, the program goes directly
to the indicatedbeginning and end.)
RAM is volatile, or temporary, storage. When the computer is booted, the operating system is loaded
into RAM. Any applications you use are locatedin RAM, along with the data the application may use. A loss
of power means that everything in RAM is lost. Data that you did not save (any changes you have made
recently) are lost. To help protect you from this loss many applications automatically save a working copy to
the (permanent) storage on the hard disk at regular intervals. (You can then recover most of your work.)
Secondary Memory
This type of memory is also known as external memory or non-volatile. It is slower than main memory.
These are used for storing data/Information permanently. CPU directly does not access these memories
instead they are accessed via input-output routines. Contents of secondary memories are first transferred to
main memory, and then CPU can access it. For example :disk, CD-ROM, DVD etc.
Input
Since the computer is a digital device, all input devices must provide datain digital form. A key function
of most of the devices listed below is to convert data from analog to digital form for transmission to the
computer through a hardware interface (for our purposes, a port).
Keyboard
The keyboard is the most popular input device for a computer. It translates numbers, letters, symbols and
control keys into digital data (bytes) that canbe interpreted by the PC. Most English keyboards today are based
on the QWERTY design, a de facto standard. It takes its name from the first six letters seen in the keyboard's
top first row of letters.
Mouse/Pointing Device
A mouse is an input device that allows the user to point (locate) and click (select) . With the rise in
graphical user interfaces, mice became the mostcommonly used method in controlling a computer. A mouse is
used to manipulate objects and text on the computer screen. This device can be plugged in or can be cordless.
Ball mouse
The ball mouse utilizes a small rubber ball inside to transmit a spatial relationship between objects on
the screen. The mechanical movement is done by 2 scroll bars that detects X and Y axis movement of the ball
to allowit go glide on the desktop plane. The ball mouse was invented by Bill English in 1972.
Since it contained moving parts, the ball mouse was prone to dirt build up inside. Hairs would often get
caught and rolled into the ball mechanism, causing the mouse to function erratically. With the falling cost of
technology, ball mice have now been mostly replaced with lighter optical mice.
Trackball
By essentially flipping the mechanical ball mouse "upside down", we get atrackball. The ball is directly
manipulated to move the screen pointer. These are great for mobile applications and public computer kiosks.
Optical
The optical mouse uses a light-emitting diode and photodiodes to detect movement relative to the
underlying surface, rather than moving some of its parts like the traditional ball mouse. In order to increase the
precision ofthe mouse, multiple infrared lasers with increasing resolution are used.
Microphone
A microphone converts sound to an electrical signal that is digitized andsent to the computer.
Microphones on laptops and smartphones typically appear as no more thana pin hole on the device.
Images
Cameras
Digital cameras are now standard, with most people uploading the pictures to their computer for processing,
printing or sharing. Digital cameras are built into most laptops and hand-held devices, especially mobile
phones. They are commonly added onto computers as webcams.
Video cameras are not yet all digital, although videos created using laptopsand smartphones are digital. Older
videos need to be converted (using a CODEC) for storage or manipulation on the computer.
Scanner
A scanner is a device that uses light to read an image or text and turn it into digital information. This
media can then be used to store, change and send the image or text. There are various types of scanners. The
three most common are drum, flatbed and hand. Drum scanners mechanically move the document to be
scanned past the sensor. Flatbed scanners use a glass pane on which a document is placed while the sensor
moves underneath – generally the most accurate method. Hand-held scanners are dragged across the image
manually.
Output
Monitor
A monitor, or visual display unit, is an electronic visual display for computers. It is now common for a
single computer to have multiple monitors. Currently, most monitors are backlit LCD (flat panel liquid
crystal) displays, which use much less energy than the older CRT (CathodeRay Tube) displays. CRTs aim a
stream of electrons through a mask at a phosphor coated, fluorescent screen creating a bright, sharp image,
and much more electromagnetic radiation and heat.
The image is created from approximately one million (1000x1000) pixels, or picture elements. Each pixel
includes sub pixels for the primary colors (red,green & blue) which are mixed to create a color on the screen.
You will recall that a true color display provides approximately 16 million colors (using one byte each for
the red, green & blue sub pixels).
Printers
Printers are routinely classified by the printer technology they employ; numerous such technologies
have been developed over the years. The choice of engine has a substantial effect on what jobs a printer is
suitable for, as different technologies are capable of different levels of image or text quality, print speed, cost,
and noise. In addition, some printer technologies are inappropriate for certain types of physical media, such as
carbon paper or transparencies.
Plotter
The plotter is a computer printer for printing vector graphics. In the past, plotters were used in
applications such as computer-aided design, though they have generally been replaced with wide-format
conventional printers. A plotter gives a hard copy of the output. It draws pictures on a paper using a pen.
Plotters are used to print designs of ships and machines, plansfor buildings and so on.
PROBLEM SOLVING
Problem solving is the systematic approach to define the problem and creating number of solutions. The
problem solving process starts with the problem specifications and ends with acorrect program.
It is defined as a sequence of instructions that describe a method for solving a problem. In other words it is a
step by step procedure for solving a problem
The following are the primary factors that are often used to judge the quality of the algorithms.
Time – To execute a program, the computer system takes some amount of time. The lesser
is the time required, the better is the algorithm.
Memory – To execute a program, computer system takes some amount of memory space.
The lesser is the memory required, the better is the algorithm.
Accuracy – Multiple algorithms may provide suitable or correct solutions to a given
problem, some of these may provide more accurate results than others, and such algorithms may be
suitable
Control Flow
Control flow which is also stated as flow of control, determines what section of code is to run in
program at a given time. There are three types of flows, they are
1. Sequential control flow
2. Selection or Conditional control flow
3. Looping or repetition control flow
Sequential control flow:
The name suggests the sequential control structure is used to perform the action one after
another. Only one step is executed once. The logic is top to bottom approach.
Example
Description: To find the sum of two numbers.
1. Start
2. Read the value of ‘a’
3. Read the value of ‘b’
4. Calculate sum=a+b
5. Print the sum of two number
6. Stop
Selection or Conditional control flow
Selection flow allows the program to make choice between two alternate paths based on condition.
It is also called as decision structure
Basic structure:
IFCONDITION is TRUE then
perform some action
ELSE IF CONDITION is FALSE then
perform some action
The conditional control flow is explained with the example of finding greatest of twonumbers.
Example
Description: finding the greater number
1. Start
2. Read a
3. Read b
4. If a>b then
4.1. Print a is greater
else
4.2. Print b is greater
5. Stop
Repetition control flow
Repetition control flow means that one or more steps are performed repeatedly until some condition
is reached. This logic is used for producing loops in program logic when one one more instructions may
need to be executed several times or depending on condition.
Basic Structure:
Repeat until CONDITION is true
Statements
Example
Description: to print the values from 1 to n
1. Start
2. Read the value of ‘n’
3. Initialize i as 1
4. Repeat step 4.1 until i< n
4.1. Print i
5. Stop
Function
A function is a block of organized, reusable code that is used to perform a single, relatedaction.
Function is also named as methods, sub-routines.
Elements of functions:
1. Name for declaration of function
2. Body consisting local declaration and statements
3. Formal parameter
4. Optional result type.
Basic Syntax
function_name(parameters)
function statements
end function
Algorithm for addition of two numbers using functionMain function()
Step 1: Start
Step 2: Call the function add()
Step 3: Stop
sub function add()
Step1:Functionstart
Step2:Geta,bValues
Step 3: add c=a+b
Step 4: Printc
Step 5: Return
Algorithm can be expressed in many different notations, including Natural Language, Pseudo
code, flowcharts and programming languages. Natural language tends to be verboseand ambiguous.
Pseudocode and flowcharts are represented through structured human language.
A notation is a system of characters, expressions, graphics or symbols designs used among each
others in problem solving to represent technical facts, created to facilitate the best result for a program
Pseudocode
Pseudocode is an informal high-level description of the operating principle of a computer
program or algorithm. It uses the basic structure of a normal programming language,but is intended for
human reading rather than machine reading.
It is text based detail design tool. Pseudo means false and code refers to instructions written in
programming language.
Pseudocode cannot be compiled nor executed, and there are no real formatting or syntax rules.
The pseudocode is written in normal English language which cannot be understood by the computer.
Example:
Pseudocode: To find sum of two numbers
BEGIN
DEFINE: num1, num2, Sum
READ: num1, num2
Sum = num1+ num2
DISPLAY sum
END
Basic rules to write pseudocode:
1. Only one statement per line.
Statements represents single action is written on same line. For example to read theinput, all the
inputs must be read using single statement.
2. Capitalized initial keywords
The keywords should be written in capital letters. Eg: BEGIN, READ, WRITE, IF, ELSE,ENDIF,
WHILE, REPEAT, UNTIL, END
Example:
Pseudocode: Find the total and average of three subjects
BEGIN
DEFINE: name, department, mark1, mark2, mark3, Total, Average
READ name, department, mark1, mark2, mark3 Total=mark1+mark2+mark3
Average=Total/3
DISPLAY name, department,mark1, mark2, mark3
END
3. Indent to show hierarchy
Indentation is a process of showing the boundaries of the structure.
4. End multi-line structures
Each structure must be ended properly, which provides more clarity.
Example:
Pseudocode: Find greatest of two numbers
BEGIN
DEFINE: a,b
READ a, b
IF a>b then
DISPLAY a is greater
ELSE
DISPLAY a is greater
ENDIF
5. Keep statements language independent.
Pesudocode must never written or use any syntax of any programming language.
Advantages of Pseudocode
Can be done easily on a word processor
Easily modified
Implements structured concepts well
It can be written easily
It can be read and understood easily
Converting pseudocode to programming language is easy as compared withflowchart
Disadvantages of Pseudocode
It is not visual
There is no standardized style or format
Flowchart
A graphical representation of an algorithm. Flowchart is a diagram made up of boxes, diamonds,
and other shapes, connected by arrows.
Each shape represents a step in process and arrows show the order in which they occur.
Table 1: Flowchart Symbols
S.No Name of Symbol Type Description
symbol
1. Terminal Oval Represent the start and
Symbol stop of the program.
6. If flowchart becomes complex, it is better to use connector symbols to reduce thenumber of flow lines.
7. Ensure that flowchart has logical start and stop.
Advantages of Flowchart
Communication:
Flowcharts are better way of communicating the logic of the system.
Effective Analysis
With the help of flowchart, a problem can be analyzed in more effective way.
Proper Documentation
Flowcharts are used for good program documentation, which is needed for variouspurposes.
Efficient Coding
The flowcharts act as a guide or blue print during the system analysis and programdevelopment phase.
Systematic Testing and Debugging
The flowchart helps in testing and debugging the program
Efficient Program Maintenance
The maintenance of operating program becomes easy with the help of flowchart. It helps the programmer
to put efforts more efficiently on that part.
Disadvantages of Flowchart
Complex Logic: Sometimes, the program logic is quite complicated. In that case flowchartbecomes
complex and difficult to use.
Alteration and Modification: If alterations are required the flowchart may require re-drawing completely.
Reproduction: As the flowchart symbols cannot be typed, reproduction becomesproblematic.
Sequence Structure
Process 3
Example
READ a
Start
READ b
Result c=a+b
PRINT c a=10, b=20
c=a+b
print c
Stop
Conditional Structure
Conditional structure is used to check the condition. It will be having two outputs only (True or False)
IF and IF…ELSE are the conditional structures used in Python language.
CASE is the structure used to select multi way selection control. It is not supported in Python.
Pseudocode Flow Chart
General Structure
IF condition THEN Yes
Process 1 if(condition)
ENDIF
Process 1 No
Process 2
Example
READ a
READ b Start
IF a>b THEN
PRINT a is greater a=10,b=20
Yes if (a>b)
Print a is greater No
Stop
IF… ELSE
IF…THEN…ELSE is the structure used to specify, if the condition is true, then execute Process1,
else, that is condition is false then execute Process2
Process 2
Example
READ a Start
READ b
IF a>b THEN
a=10,b=20
PRINT a is greater
Yes if (a>b)
Print a is greater
No
Print b is greater
Stop
Yes
Body of the loop
Example
DO…WHILE is exit checked loop, so the loop will be executed at least once.
INITIALIZE a=1 Start
Yes
Stop
Print a
a=a+1
Programming Language
A programming language is a vocabulary and set of grammatical rules for instructing a computer
or computing device to perform specific tasks. In other word it is set of instructions for the
computer to solve the problem.
Programming Language is a formal language with set of instruction, to the computer to solve a
problem. The program will accept the data to perform computation.
Program= Algorithm +Data
Need for Programming Languages
Programming languages are also used to organize the computation
Using Programming language we can solve different problems
To improve the efficiency of the programs.
Types of Programming Language
In general Programming languages are classified into three types. They are
Low – level or Machine Language
Intermediate or Assembly Language
High – level Programming language
Machine Language:
Machine language is the lowest-level programming language (except for computers that utilize
programmable microcode). Machine languages are the only languages understood by computers. It is also
called as low level language.
Example code:100110011
111001100
Assembly Language:
An assembly language contains the same instructions as a machine language, but the instructions
and variables have names instead of being just numbers. An assembler language consists of mnemonics,
mnemonics that corresponds unique machine instruction.
Example code: start
addx,y
subx,y
High – level Language:
A high-level language (HLL) is a programming language such as C, FORTRAN, or Pascal that
enables a programmer to write programs that are more or less independent of a particular type of
computer. Such languages are considered high-level because they are closer to human languages and
further from machine languages. Ultimately, programs written in a high-level language must be translated
into machine language by a compiler or interpreter.
Example code: print(“Hello World!”)
High level programming languages are further divided as mentioned below.
Figure : Interpreter
Figure: Compiler
Interpreted vs. Compiled Programming Language
Interpreted Programming Language Compile Programming Language
Translates one statement at a time Scans entire program and translates it as whole
into machine code
It takes less amount of time to analyze the It takes large amount of time to analyze the
source code but the overall execution time is source code but the overall execution time is
slower comparatively faster
No intermediate object code is generated, Generates intermediate object code which
hence are memory efficient further requires linking, hence requires more
memory
Continues translating the program until first It generates the error message only after
error is met, in which case it stops. Hence scanning the whole program. Hence debugging
debugging is easy. is comparatively hard.
Eg: Python, Ruby Eg: C,C++,Java
If the instructions are executed one after another, it is called sequential algorithm
Programming language can be fed into an electronic computer directly. Instead, it needs to be
converted into a computer program written in a particular computer language. We can look at such
a program as yet another way of specifying the algorithm, although it is preferable to consider it as
the algorithm’s implementation.
Once an algorithm has been specified, you have to prove its correctness. That is, you have to
prove that the algorithm yields a required result for every legitimate input in a finite amount of
time.
It might be worth mentioning that although tracing the algorithm’s performance for a few specific
inputs can be a very worthwhile activity, it cannot prove the algorithm’s correctness conclusively.
But in order to show that an algorithm is incorrect, you need just one instance of its input for
which the algorithm fails.
Analyzing an Algorithm
1. Efficiency
Time efficiency: indicating how fast the algorithm runs,
Space efficiency: indicating how much extra memory it uses
2. Simplicity
An algorithm should be precisely defined and investigated with mathematical
expressions.
Simpler algorithms are easier to understand and easier to program.
Simple algorithms usually contain fewer bugs.
Illustrative problems:
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 go to 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:
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
2. Leap year
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:
Pseudocode:
BEGIN
DEFINE: Integer year
DISPLAY: “Enter the year value: “
READ: year
IF: year%4=0
DISPLAY: “’year’ is a leap year”
ELSE
DISPLAY: “’year’ is not a leap year”
END IF
END
Algorithm:
Step 1 - Start.
Step 2 - Read three numbers p, q, r.
Step 3 - If p is greater than q, go to step 5.
Step 4 - If q is greater than r then,
Display q is the largest number and go to step6
else,
Display r is the largest number and go to step 6
Step 5 - If p is greater than r then,
Display p is the largest number and go to step6
else,
Display r is the largest number and go to step6
Step 6 - Stop.
Flow Chart:
Pseudocode:
BEGIN
DEFINE: p,q,r
READ: p,q,r
IF p>q AND p>r THEN
DISPLAY “p is bigger”
ELSE IF q > r THEN
DISPLAY “q is bigger”
ELSE
DISPLAY “r is bigger”
ENDIF
END
Algorithm
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
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
5. Sum of n numbers
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
Flowchart
Pseudocode
BEGIN
DEFINE: counter, sum=0
FOR counter=1 TO 100 DO
sum=sum+counter
ENDFOR
DISPLAY sum
END
6. Armstrong number
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
Flowchart
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
7. Palindrome
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
Flowchart
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)
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
8. Fibonacci Series
Algorithm
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
Flowchart
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
SET: num1 = num2
SET: num2 = fab
END FOR
END
9. 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
Flowchart
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
END FOR
IF: i=num
DISPLAY: “’num’ is a prime number”
END IF
END
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
Pseudocode
BEGIN
DEFINE: num, i, j
READ num
INITIALIZE: i=0
WHILE i<9: DO
j=i
WHILE j<10 DO
IF num[i]>num[j], THEN
num[i],num[j]=num[j],num[i]
j=j+1
ENDWHILE
i=i+1
ENDWHILE
END
Flowchart
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
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
Flowchart
Pseudocode
BEGIN
DEFINE: array, element, flag, j
READ: array, element
INITIALIZE: flag=0, j=0
REPEAT:
IF array[j]=element
DISPLAY “Element Found at”,j
FLAG=1
break
ELSE:
SET:j=j+1
ENDIF
UNTIL j<10
IF flag=0
DISPLAY: “Element Not Found”
ENDIF
END
UNIT II - DATA, EXPRESSIONS, CONTROL FLOW STATEMENTS
INTRODUCTION TO PYTHON:
Interpreter: To execute a program in a high-level language by translating it one line ata time.
Compiler: To translate a program written in a high-level language into a low-level language all at once, in
preparation for later execution.
Compiler Interpreter
Compiler Takes Entire program as input Interpreter Takes Single instruction as input
Script mode:
In script mode, we type python program in a file and then use interpreter to execute the content of the
file.
Scripts can be saved to disk for future use. Python scripts have the
extension .py, meaning that the filename ends with.py
Save the code with filename.py and run the interpreter in script mode to execute the script.
Can’t save and edit the code Can save and edit the code
If we want to experiment with the code,we If we are very clear about the code, we can
can use interactive mode. use script mode.
we cannot save the statements for further use and we we can save the statements for further use and we no
have to retype all the statements to re-run them. need to retype all the statements to re-run them.
We can see the results immediately. We can’t see the code immediately.
Value:
Value can be any letter, number or string.
Eg, Values are 2, 42.0, and 'Hello, World!'. (These values belong to different datatypes.)
Data type:
Every value in Python has a data type.
It is a set of values, and the allowable operations on those values.
Python has four standard data types:
Numbers:
Number data type stores Numerical Values.
This data type is immutable [i.e. values/items cannot be changed].
Python supports integers, floating point numbers and complex numbers. They are defined as,
Sequence:
A sequence is an ordered collection of items, indexed by positive integers.
It is a combination of mutable (value can be changed) and immutable (values cannot be changed)
datatypes.
There are three types of sequence data type available in Python, they are
1. Strings
2. Lists
3. Tuples
Strings:
A String in Python consists of a series or sequence of characters - letters, numbers, and special
characters.
Strings are marked by quotes:
Single quotes(' ') E.g., 'This a string in single quotes'
double quotes(" ") E.g., "'This a string in double quotes'"
triple quotes(""" """)E.g., """This is a paragraph. It is made up of multiple
lines and sentences."""
Individual character in a string is accessed using a subscript(index).
Characters can be accessed using indexing and slicing operations .Strings are
Immutable i.e the contents of the string cannot be changed after it is created.
Indexing:
Positive indexing helps in accessing the string from the beginning
Negative subscript helps in accessing the string from the end.
Subscript 0 or –ven(where n is length of the string) displays the first element.
Example: A[0] or A[-5] will display “H”
Subscript 1 or –ve (n-1) displays the second element.
Example: A[1] or A[-4] will display “E”
Operations on string:
i. Indexing
ii. Slicing
iii. Concatenation
iv. Repetitions
v. Membership
Creating a string >>> s="good morning" Creating the list with elements of different
data types.
Indexing >>>print(s[2]) Accessing the item in the
o position0
>>>print(s[6]) Accessing the item in the
O position2
Slicing( ending >>>print(s[2:]) - Displaying items from 2ndtill
position -1) od morning last.
st
Slice operator is used to >>>print(s[:4]) - Displaying items from 1
extract part of a data Good position till 3rd.
type
Lists
List is an ordered sequence of items. Values in the list are called elements /items.
It can be written as a list of comma-separated items (values) between square brackets[].
Items in the lists can be of different datatypes.
Operations on list:
Indexing
Slicing
Concatenation
Repetitions
Updation, Insertion, Deletion
Creating a list >>>list1=["python", 7.79, 101, Creating the list with
"hello”] elements of different data
>>>list2=["god",6.78,9] types.
Indexing >>>print(list1[0]) python Accessing the item in the
>>>list1[2] position0
101 Accessing the item in the
position2
Tuple:
A tuple is same as list, except that the set of elements is enclosed in parentheses
instead of square brackets.
A tuple is an immutable list.i.e. once a tuple has been created, you can't add elements to a tuple or
remove elements from the tuple.
Benefit of Tuple:
Tuples are faster than lists.
If the user wants to protect the data from accidental changes, tuple can be used.
Tuples can be used as keys in dictionaries, while lists can't.
Basic Operations:
Creating a tuple >>>t=("python", 7.79, 101, Creating the tuple with elements
"hello”) of different data types.
Indexing >>>print(t[0]) python Accessing the item in the
>>>t[2] position0
101 Accessing the item in the
position2
Altering the tuple data type leads to error. Following error occurs when user tries to do.
>>>t[0]="a"
Trace back (most recent call last):
File "<stdin>", line 1, in <module>
Type Error: 'tuple' object does not support item assignment
Mapping
-This data type is unordered and mutable.
-Dictionaries fall under Mappings.
Dictionaries:
Lists are ordered sets of objects, whereas dictionaries are unorderedsets.
Dictionary is created by using curly brackets. i,e.{}
Dictionaries are accessed via keys and not via their position.
A dictionary is an associative array (also known as hashes). Any key of the dictionary is associated
(or mapped) to a value.
The values of a dictionary can be any Python data type. So dictionaries are unordered key-value-
pairs(The association of a key and a value is called a key- value pair)
Dictionaries don't support the sequence operation of the sequence data types like strings, tuples and lists.
Creating adictionary >>> food = {"ham":"yes", "egg" : Creating the dictionary with
"yes", "rate":450 } elements of different data
>>>print(food) types.
{'rate': 450, 'egg': 'yes', 'ham':
'yes'}
Indexing >>>>print(food["rate"]) Accessing the item with keys.
450
Slicing( ending >>>print(t[1:3]) Displaying items from 1st till 2nd.
position -1) (7.79, 101)
If you try to access a key which doesn't exist, you will get an error message:
>>>words = {"house" : "Haus", "cat":"Katze"}
>>>words["car"]
Traceback (most recent call last): File
"<stdin>", line 1, in <module>KeyError: 'car'
VARIABLES:
A variable allows us to store a value by assigning it to a name, which can be used later.
Named memory locations to store values.
Programmers generally choose names for their variables that are meaningful.
It can be of any length. No space is allowed.
We don't need to declare a variable before using it. In Python, we simply assign a value to a variable
and it will exist.
Assigning value to variable:
Value should be given on the right side of assignment operator(=) and variable on left side.
>>>counter =45
print (counter)
33
Assigning a single value to several variables simultaneously:
>>> a=b=c=100
Assigning multiple values to multiple variables:
>>>a,b,c=2,4,"ram"
KEYWORDS:
Keywords are the reserved words in Python.
We cannot use a keyword as name, function name or any other identifier.
They are used to define the syntax and structure of the Python language.
Keywords are case sensitive.
IDENTIFIERS:
Identifier is the name given to entities like class, functions, variables etc. in Python.
Identifiers can be a combination of letters in lowercase (a to z) or uppercase (A to
Z) or digits (0 to 9) or an underscore (_).
all are valid example.
An identifier cannot start with a digit.
Keywords cannot be used as identifiers.
Cannot use special symbols like!, @, #, $, % etc. in our identifier.
Identifier can be of any length.
Example:
Names like myClass, var_1, and this_is_a_long_variable
Here, The first line is an assignment statement that gives a value to n. The second line is
a print statement that displays the value of n.
Expressions:
-An expression is a combination of values, variables, and operators.
- A value all by itself is considered an expression, and also a variable.
- So the following are all legal expressions:
>>> 42
42
>>> a=2
>>>a+3+2 7
>>> z=("hi"+"friend")
>>>print(z) hifriend
INPUT: Input is data entered by user (end user) in the program. In python, input
() function is available for input.
Syntax for input() is:
variable = input (“data”)
Example:
>>> x=input("enter the name:")enter
the name: george
>>>y=int(input("enter the number"))
enter the number 3
#python accepts string as default data type. Conversion is required for type.
COMMENTS:
A hash sign (#) is the beginning of a comment.
Anything written after # in a line is ignored by interpreter.
Eg: percentage = (minute * 100)/60 # calculating percentage of an hour
Python does not have multiple-line commenting feature. You have to comment each line
individually as follows:
Example:
# This is a comment.
# This is a comment, too.
# I said that already.
35
DOCSTRING:
Docstring is short for documentation string.
It is a string that occurs as the first statement in a module, function, class, or method definition. We
must write what a function/class does in the docstring.
Triple quotes are used while writing docstrings.
Syntax:
functionname doc. Example:
def double(num):
"""Function to double thevalue"""
return2*num
>>>print (double. doc )
Function to double the value
QUOTATION INPYTHON:
Python accepts single ('), double (") and triple (''' or """) quotes to denote string literals. Anything that is
represented using quotations are considered as string.
TUPLE ASSIGNMENT
36
Example:
-It is useful to swap the values of two variables. With conventional assignment statements, we have to use a
temporary variable. For example, to swap a and b:
(a, b) = (b, a)
-In tuple unpacking, the values in a tuple on the right are ‘unpacked ‘into the variables/names on theright:
4.OPERATORS:
Operators are the constructs which can manipulate the value of operands.
Consider the expression 4 + 5 = 9. Here, 4 and 5 are called operands and + is called operator
Types of Operators:
37
-Python language supports the following types of operators
Arithmetic Operators
Comparison (Relational)Operators
Assignment Operators
Logical Operators
Bitwise Operators
Membership Operators
Identity Operators
Arithmetic operators:
They are used to perform mathematical operations like addition, subtraction, multiplication etc.
Assume, a=10 and b=5
% Modulus Divides left hand operand by right hand operand and returns b%a=0
remainder
// Floor Division - The division of operands where the result is the 5//2=2
quotient in which the digits after the decimal point are removed
Examples
CODE OUTPUT
a=10 a+b=15
b=5 a-b= 5
print("a+b=",a+b)
a*b= 50
print("a-b=",a-b)
print("a*b=",a*b) a/b=
print("a/b=",a/b) 2.0
print("a%b=",a%b) a%b=0
print("a//b=",a//b) a//b=2
print("a**b=",a**b) a**b= 100000
Comparison (Relational)Operators:
Comparison operators are used to compare values.
It either returns True or False according to the condition. Assume, a=10 and b=5
38
Operator Description Example
!= If values of two operands are not equal, then condition becomes true. (a!=b) is
true
> If the value of left operand is greater than the value of right operand, then (a > b) is not
condition becomes true. true.
< If the value of left operand is less than the value of right operand, then (a < b) is true.
condition becomes true.
>= If the value of left operand is greater than or equal to the value of right (a >= b) is not
operand, then condition becomes true. true.
<= If the value of left operand is less than or equal to the value of right (a <= b) is
operand, then condition becomes true. true.
Example
CODE OUTPUT
a=10 a>b=>True
b=5 a>b=> False
print("a>b=>",a>b) a==b=> False
print("a>b=>",a<b) a!=b=> True
print("a==b=>",a==b) a>=b=> False
a>=b=> True
print("a!=b=>",a!=b)
print("a>=b=>",a<=b)
print("a>=b=>",a>=b)
Assignment Operators:
-Assignment operators are used in Python to assign values to variables.
Operator Description Example
= Assigns values from right side operands to left side operand c=a+b
assigns value
of a + b into c
+= Add AND It adds right operand to the left operand and assign the result to c += a is
leftoperand equivalent to c
=c+a
39
-= Subtract It subtracts right operand from the left operand and assign the result c -= a is
AND to left operand equivalent to c
= c -a
*= Multiply It multiplies right operand with the left operand and assign the c *= a is
AND result to left operand equivalent to c
= c *a
/= Divide It divides left operand with the right operand and assign the result c /= a is
AND to left operand equivalent to c
= c /ac
/= a is
equivalent to c
= c /a
%= Modulus It takes modulus using two operands and assign the result to left c %= a is
AND operand equivalent to c
=c%a
//= Floor It performs floor division on operators and assign value to the left c //= a is
Division operand equivalent to c
= c // a
Example
CODE OUTPUT
a =21
b =10 Line 1 - Value of c is 31
Line 2 - Value of c is 52
c=0
Line 3 - Value of c is 1092
c=a+b Line 4 - Value of c is 52.0
print("Line 1 - Value of c is ",c)c += a Line 5 - Value of c is2
print("Line 2 - Value of c is ", c)c *= a Line 6 - Value of c is 2097152
print("Line 3 - Value of c is ",c)c /= a Line 7 - Value of c is9986
print("Line 4 - Value of c is ", c)c = 2
c %=a
print("Line 5 - Value of c is ",c)c **= a
print("Line 6 - Value of c is ",c)c //= a
print ("Line 7 - Value of c is ", c)
40
Logical Operators:
-Logical operators are the and, or, not operators.
Example Output
a = True x and y is False
b = False x or y is True
print('a and b is', a and b) not x is False
print('a or b is' ,a or b)
print('not a is', not a)
Bitwise Operators:
A bitwise operation operates on one or more bit patterns at the level of individual bits
Example: Let x = 10 (0000 1010 in binary)and
y = 4 (0000 0100 in binary)
Example Output
a = 60 # 60 = 0011 1100 Line 1 - Value of c is 12
b = 13 # 13 = 0000 1101 Line 2 - Value of c is 61
c=0 Line 3 - Value of c is 49
c = a & b; # 12 = 0000 1100 Line 4 - Value of c is-61
print "Line 1 - Value of c is ", c Line 5 - Value of c is 240
c = a|b; # 61 = 00111101 Line 6 - Value of c is 15
print "Line 2 - Value of c is ", c
c = a^b; # 49 = 00110001
print "Line 3 - Value of c is ", c
c =~a; # -61 = 11000011
41
print "Line 4 - Value of c is ", c
c = a<<2; # 240 = 11110000
print "Line 5 - Value of c is ", c
c = a>>2; # 15 = 00001111
print "Line 6 - Value of c is ", c
Membership Operators:
Evaluates to find a value or a variable is in the specified sequence of string, list, tuple, dictionary or
not.
Let, x=[5,3,6,4,1]. To check particular item in list or not, in and not in operators areused.
Example:
x=[5,3,6,4,1]
>>>5 in x
True
>>>5 not in x
False
Identity Operators:
• They are used to check if two values (or variables) are located on the same partof the
memory.
Example
Output
x =5
False
y =5 True
x2 = 'Hello'
y2= 'Hello'
print(x1 is not y1)
print(x2 is y2)
42
5.OPERATOR PRECEDENCE:
When an expression contains more than one operator, the order of evaluation
depends on the order of operations.
Operator Description
~+- Complement, unary plus and minus (method names for the
last two are +@ and -@)
43
Examples:
a=9-12/3+3*2-1 A=2*3+4%5-3/2+6
a=? A=6+4%5-3/2+6 find m=?
a=9-4+3*2-1 A=6+4-3/2+6 A=6+4- m=-43||8&&0||-2 m=-
a=9-4+6-1 1+6 43||0||-2 m=1||-2
a=5+6-1 a=11-1 A=10-1+6 m=1
a=10 A=9+6 A=15
Conditional Statements
Conditional if
Alternative if… else
Chained if…elif…else
Nested if….else
Conditional (if):
conditional (if) is used to test a condition, if the condition is true the statements inside if will be
executed.
syntax:
Flowchart:
61
Alternative (if-else):
In the alternative the condition must be true or false. In this else statement can be combined with if
statement. The else statement contains the block of code that executes when the condition is false. If the
condition is true statements inside the if get executed otherwise else part gets executed. The alternatives are
called branches, because they are branches in the flow of execution.
syntax:
Flowchart:
Examples:
1. odd or even number
2. positive or negative number
3. leap year or not
62
Chained conditionals (if-elif-else)
If the condition1 is False, it checks the condition2 of the elif block. If all the conditions are
False, then the else part is executed.
Among the several if...elif...else part, only one part is executed according to the condition.
The if block can have only one else block. But it can have multiple elif blocks.
The way to express a computation like that is a chained conditional.
Syntax:
Flowchart:
63
Example:
1. student mark system
2. traffic light system
Nested conditionals
One conditional can also be nested within another. Any number of condition can be nested inside
one another. In this, if the condition is true it checks another if condition1. If both the conditions are true
statement1 get executed otherwise statement2 get execute. if the condition is false statement3 gets
executed
Syntax
64
Flowchart:
Example:
1. greatest of three numbers
2. positive negative or zero
greatest of three numbers output
a=eval(input(“enter the value of a”)) enter the value of a 9
b=eval(input(“enter the value of b”)) enter the value of a 1
c=eval(input(“enter the value of c”)) enter the value of a 8
if(a>b): the greatest no is 9
if(a>c):
print(“the greatest no is”,a)
else:
print(“the greatest no is”,c)
else:
if(b>c):
else:
print(“the greatest no is”,c)
State:
Transition from one process to another process under specified condition with in a time is called
state.
While loop:
While loop statement in Python is used to repeatedly executes set of statement as long as a given
condition is true.
In while loop, test expression is checked first. The body of the loop is entered only if the test
expression is True. After one iteration, the test expression is checked again. This process continues
until the test expression evaluates to False.
In Python, the body of the while loop is determined through indentation.
The statements inside the while start with indentation and the first unintended line marks the end.
Syntax:
Flow chart:
66
Examples:
For loop:
for in range:
We can generate a sequence of numbers using range() function. range(10) will
generate numbers from 0 to 9 (10 numbers).
In range function have to define the start, stop and step size
as range(start,stop,step size). step size defaults to 1 if not provided.
syntax
Flowchart:
67
For in sequence
The for loop in Python is used to iterate over a sequence (list, tuple, string). Iterating over a
sequence is called traversal. Loop continues until we reach the last element in the sequence.
The body of for loop is separated from the rest of the code using indentation.
2
2. For loop in list for i in [2,3,5,6,9]: 3
print(i) 5
6
9
for i in (2,3,1): 2
3. For loop in tuple print(i) 3
1
Examples:
1. Program to print Fibonacci series.
2. check the no is prime or not
Fibonacci series output
a=0 Enter the number of terms: 6
b=1 Fibonacci Series:
n=eval(input("Enter the number of terms: ")) 01
print("Fibonacci Series: ") 1
print(a,b) 2
for i in range(1,n,1): 3
c=a+b 5
print(c) 8
a=b
b=c
68
check the no is prime or not output
n=eval(input("enter a number")) enter a no:7
for i in range(2,n): The num is a prime number.
if(n%i==0):
print("The num is not a prime")
break
else:
print("The num is a prime number.")
Flowchart
69
example Output
for i in "welcome": w
if(i=="c"): e
break l
print(i)
70
CONTINUE
It terminates the current iteration and transfer the control to the next iteration in the loop.
Syntax: Continue
Flowchart
Example: Output
for i in "welcome": w
if(i=="c"): e
continue l
print(i) o
m
e
PASS
It is used when a statement is required syntactically but you don’t want any code to execute.
It is a null statement, nothing happens when it is executed.
71
Syntax:
pass
break
Example Output
for i in “welcome”: w
if (i == “c”): e
pass l
print(i) c
o
m
e
break continue
It terminates the current loop and It terminates the current iteration and
executes the remaining statement outside transfer the control to the next iteration in
the loop. the loop.
syntax: syntax:
break continue
w w
e e
l l
o
m
e
72
example output
for i in range(1,6): 1
print(i) 2
else: 3
print("the number greater than 6") 4
5 the number greater than 6
ILLUSTRATIVE PROGRAMS
Example:
def my_add(a,b):
c=a+b
return c
Flow of Execution:
• The order in which statements are executed is called the flow of execution
• Execution always begins at the first statement of the program.
• Statements are executed one at a time, in order, from top to bottom.
• Function definitions do not alter the flow of execution of the program, but remember that statements
inside the function are not executed until the function is called.
• Function calls are like a bypass in the flow of execution. Instead of going to the next statement, the
flow jumps to the first line of the called function, executes all the statements there, and then comes
back to pick up where it left off.
Note: When you read a program, don’t read from top to bottom. Instead, follow the flow of execution. This
means that you will read the def statements as you are scanning from top to bottom, but you should skip the
statements of the function definition until you reach a point where that function is called.
Function Prototypes:
i. Function without arguments and without return type
ii. Function with arguments and without return type
iii. Function without arguments and with return type
iv. Function with arguments and with return type
i) Function without arguments and without return type
o In this type no argument is passed through the function call and no output is return to main
function
o The sub function will read the input values perform the operation and print the result in the
same block
ii) Function with arguments and without return type
o Arguments are passed through the function call but output is not return to the main function
iii) Function without arguments and with return type
o In this type no argument is passed through the function call but output is return to the main
function.
iv) Function with arguments and with return type
o In this type arguments are passed through the function call and output is return to the main
function
Without Return Type
Without argument With argument
def add(): def add(a,b):
a=int(input("enter a")) c=a+b
b=int(input("enter b")) print(c)
c=a+b a=int(input("enter a"))
print(c) b=int(input("enter b"))
add() add(a,b)
OUTPUT: OUTPUT:
enter a5 enter enter a5
b 10 enter b 10
15 15
OUTPUT: OUTPUT:
enter a5 enter a5
enter b 10 enter b 10
15 15
Parameters And Arguments:
Parameters:
Parameters are the value(s) provided in the parenthesis when we write function header.
These are the values required by function to work.
If there is more than one value required, all of them will be listed in parameter list separated by
comma.
Example: defmy_add(a,b):
Arguments :
Arguments are the value(s) provided in function call/invoke statement.
List of arguments should be supplied in same way as parameters are listed.
Bounding of parameters to arguments is done 1:1, and so there should be same number and type of
arguments as mentioned in parameter list.
Example:my_add(x,y)
RETURN STATEMENT:
The return statement is used to exit a function and go back to the place from where it was called.
If the return statement has no arguments, then it will not return any values. But exits from function.
Syntax:
return[expression]
Example:
def my_add(a,b):
c=a+b
return c
x=5
y=4
print(my_add(x,y))
Output:
9
ARGUMENT TYPES:
1. Required Arguments
2. Keyword Arguments
3. Default Arguments
4. Variable length Arguments
Required Arguments :The number of arguments in the function call should match exactly withthe function
definition.
DefaultArguments:
Assumes a default value if a value is not provided in the function call for that argument.
defmy_details( name, age=40 ):
print("Name: ", name)
print("Age ", age) return
my_details(name="george")
Output:
Name:
georgeAge40
Variable lengthArguments
If we want to specify more arguments than specified while defining the function, variable length
arguments are used. It is denoted by * symbol before parameter.
def my_details(*name ):
print(*name)
my_details("rajan","rahul","micheal", ärjun")
Output:
rajanrahulmichealärjun
Return values:
return keywords are used to return the values from the function.
example:
return a – return 1 variable
return a,b– return 2 variables
return a+b– return expression
return 8– return value
Global Scope
The scope of a variable refers to the places that you can see or access a variable.
A variable with global scope can be used anywhere in the program.
It can be created by defining a variable outside the function.
Example output
a=50
def add():
Global Variable
b=20 70
c=a+b
print© Local Variable
def sub():
b=30
c=a-b 20
print©
print(a) 50
Local Scope A variable with local scope can be used only within the function .
Example output
def add():
b=20
c=a+b 70
Local Variable
print©
def sub():
b=30 20
c=a-b
Local Variable
print©
print(a) error
print(b) error
Function Composition:
Function Composition is the ability to call one function from within another function
It is a way of combining functions such that the result of each function is passed as the argument of
the next function.
In other words the output of one function is given as the input of another function is known as
function composition.
Recursion
A function calling itself till it reaches the base value - stop point of function call. Example:
factorial of a given number using recursion
Factorial of n Output
def fact(n): enter no. to find fact:5
if(n==1): Fact is 120
return 1
else:
return n*fact(n-1)
Examples:
1. sum of n numbers using recursion
2. exponential of a number using recursion
Sum of n numbers Output
def sum(n): enter no. to find sum:10
if(n==1): Fact is 55
return 1
else:
return n*sum(n-1)
sum=sum(n)
print("Fact is",sum)
STRINGS
String is defined as sequence of characters represented in quotation marks (either single quotes (‘) or double
quotes (“).
An individual character in a string is accessed using a index.
The index should always be an integer (positive or
negative).A index starts from 0 to n-1.
Strings are immutable i.e. the contents of the string cannot be changed after it is created.
Python will get the input at run time by default as a string.
Python does not support character data type. A string of size 1 can be treated as characters.
3. single quotes (' ')
4. double quotes (" ")
5. triple quotes(“”” “”””)
Operations on string:
1. Indexing
2. Slicing
3. Concatenation
4. Repetitions
5. Member ship
klnklnkln
Immutability:
Python strings are “immutable” as they cannot be changed after they are created.
Therefore [ ] operator cannot be used on the left side of an assignment.
operations Example output
element assignment a="PYTHON" TypeError: 'str' object does
a[0]='x' not support element
assignment
Stringname.method()
a=”happy birthday”
here, a is the string name.
syntax example description
1 a.capitalize() >>> a.capitalize() capitalize only the first letter
' Happy birthday’ in a string
2 a.upper() >>> a.upper() change string to upper case
'HAPPY BIRTHDAY’
3 a.lower() >>> a.lower() change string to lower case
' happy birthday’
4 a.title() >>> a.title() change string to title case i.e.
' Happy Birthday ' first characters of all the
words are capitalized.
5 a.swapcase() >>> a.swapcase() change lowercase characters
'HAPPY BIRTHDAY' to uppercase and vice versa
6 a.split() >>> a.split() returns a list of words
['happy', 'birthday'] separated by space
7 a.center(width,”fillchar >>>a.center(19,”*”) pads the string with the
”) '***happy birthday***' specified “fillchar” till the
length is equal to “width”
8 a.count(substring) >>> a.count('happy') returns the number of
1 occurences of substring
9 a.replace(old,new) >>>a.replace('happy', replace all old substrings
'wishyou happy') with new substrings
'wishyou happy
birthday'
10 a.join(b) >>> b="happy" returns a string concatenated
>>> a="-" with the elements of an
>>> a.join(b) iterable. (Here “a” is the
'h-a-p-p-y' iterable)
11 a.isupper() >>> a.isupper() checks whether all the case-
False based characters (letters) of
the string are uppercase.
12 a.islower() >>> a.islower() checks whether all the case-
True based characters (letters) of
the string are lowercase.
13 a.isalpha() >>> a.isalpha() checks whether the string
False consists of alphabetic
characters only.
String modules:
A module is a file containing Python definitions, functions, statements.
Standard library of Python is extended as modules.
To use these modules in a program, programmer needs to import the module.
Once we import a module, we can reference or use to any of its functions or variables in our code.
There is large number of standard modules also available in python.
Standard modules can be imported the same way as we import our user-defined modules.
Syntax:
import module_name
Example output
import string
print(string.punctuation) !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
print(string.digits) 0123456789
print(string.printable) 0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJ
print(string.capwords("happ KLMNOPQRSTUVWXYZ!"#$%&'()*+,-
y birthday")) ./:;<=>?@[\]^_`{|}~
print(string.hexdigits) Happy Birthday
print(string.octdigits) 0123456789abcdefABCDEF
01234567
ILLUSTRATIVE PROGRAMS
Creating a list :
The simplest way to create a new list is to enclose the elements in square brackets ([])
[10,20,30,40]
[100, "python" , 8.02]
LIST OPERATIONS:
1. Concatenation of list
2. Repetition of list
a= [5,10,50,100]
b=a
b[0] = 80
print ("original list", a) = [5,10,50,100]
print ("Aliasing list", b) =
[80,5,10,50,100]
Here both a & b refers to the same list. Thus, any change made with one object will affect
other,since they are mutable objects.
in general, it is safer to avoid aliasing when we are working with mutable objects
Cloning:
Cloning creates a new list with same values under another name. Taking any slice of list
createnew list.
Any change made with one object will not affect others. the easiest way to clone a new list is
touse "slice operators"
a = [5,10,50,100]
b= a[ : ]
b[0] = 80
Print (" original list", a) = [5,10,50,100]
Print (" cloning list", b) = [5,10,50,100]
LIST METHODS:
Python provides methods that operate on lists.
Example:
1. append adds a new element to the end of a list.
>>>t=[‘a’,’b’,’c’,’d’]
>>>t.append(‘e’)
>>>t
Output:
[‘a’,’b’,’c’,’d’,’e’]
2. extend takes a list as an argument and appends all the elements.
>>>t1=[‘a’,’b’]
>>>t2=[‘c’,’d’]
>>>t1.extend(t2)
>>>t1
Output:
[‘a’,’b’,’c’,’d’]
t2 will be unmodified.
List parameter:
List can be passed as arguments to functions the list arguments are always passed by
referenceonly.
Hence, if the functions modifies the list the caller also
changes.Eq: def head ():
del t[ 0 ]
>>> letters = ['a','b','c']
>>> head (letters)
>>> letters
['b','c']
In above,
The parameters 't' and the variable 'letters' or aliases for the same
objectsAn alternative way to write a function that creates and return a
new list Eq: def tail (t):
return t [1:]
>>> letters = ['a','b','c']
>>> result = tail (letters)
>>> result
['b','c']
In above,
The function leaves the original list unmodified and returns all element in list except first element
MUTABILITY:
Lists are mutable. Mutable means, we can change the content without changing the identity.
Mutability is the ability for certain types of data to be changed without entirely recreating it.Using
mutable data types can allow programs to operate quickly and efficiently.
Example 1:
>>>numbers=[42,123]
>>>numbers[1]=5
>>>numbers[42,5]
Figure 4.1 shows the state diagram for cheeses, numbers and empty:
Lists are represented by boxes with the word “list” outside and the elements of the list
inside. cheeses refers to a list with three elements indexed 0, 1 and 2.
has been reassigned from 123 to 5. empty refers to a list with no elements.
The in operator also works on lists.
>>> cheeses = ['Cheddar', 'Edam', 'Gouda']
>>> 'Edam' in
cheesesTrue
>>> 'Brie' in
cheesesFalse
TUPLES:
A tuple is a sequence of value which can be of any type and they are indexed by integers.
Values in tuple are enclosed in parentheses and separated by comma. The elements in the tuple cannot
be modified as in list (i.e) tuple are immutable objects
Creating tuple:
Tuple can be created by enclosing the element in parentheses separated by
commat = ('a','b','c','d')
To create a tuple with a single element we have to include a final comma
>>> t = 'a',
DICTIONARIES
Dictionaries have a method called items that returns a sequence of tuples, where eachtuple is a
key-value pair.
OPERATIONS AND METHODS
Example:
>>> d = {'a':0, 'b':1, 'c':2}
>>> t = d.items()
>>> t
Output:
dict_items([('c', 2), ('a', 0), ('b', 1)])
The result is a dict_items object, which is an iterator that iterates the key-value pairs. We
can use it in a for loop like this:
Example:
>>> for key, value in d.items():
... print(key, value)
Output:
c2
a0
b1
As we should expect from a dictionary, the items are in no particular order.
Going in the other direction, we can use a list of tuples to initialize a new dictionary:
Example:
>>> t = [('a', 0), ('c', 2), ('b', 1)]
>>> d = dict(t)
>>> d
Output:
{'a': 0, 'c': 2, 'b': 1}
Combining dict with zip yields a concise way to create a dictionary:
Example:
>>> d = dict(zip('abc', range(3)))
>>> d
Output:
{'a': 0, 'c': 2, 'b': 1}
The dictionary method update also takes a list of tuples and adds them, as key-value
pairs, to an existing dictionary. It is common to use tuples as keys in dictionaries (primarily
because we can’t use
lists). For example, a telephone directory might map from last-name, first- name pairs
to telephone numbers. Assuming that we have defined last, first and number, we could write:
directory [last, first] = number
The expression in brackets is a tuple. We could use tuple assignment to traverse this
dictionary. For last, first in directory:
print(first, last, directory[last,first])
This loop traverses the keys in directory, which are tuples. It assigns the elements of
eachtuple to last and first, then prints the name and corresponding telephone number.
There are two ways to represent tuples in a state diagram. The more detailed version
shows the indices and elements just as they appear in a list. For example, the tuple('Cleese',
'John') would appear as in Figure 4.4.But in a larger diagram we might want to leave out the
details. For example, a diagram of the telephone directory might appear as in Figure 4.5.
Here the tuples are shown using Python syntax as a graphical shorthand. The telephone
number in the diagram is the complaints line for the BBC, so please don’t call it.