Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Python Unit 1-4 Notes

Download as pdf or txt
Download as pdf or txt
You are on page 1of 87

K.L.

N COLLEGE OF ENGINEERING
(An Autonomous Institution, Affiliated to Anna University – Chennai)

DEPARTMENT OF ELECTRONICS AND COMMUNICATION


ENGINEERING

20GE101-PROBLEM SOLVING USING PYTHON


PROGRAMMING

REGULATION: R2020

STUDY MATERIAL

BRANCH: ECE YEAR/SEM: I/I

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.

UNIT - II DATA, EXPRESSIONS, CONTROL FLOW STATEMENTS 9


Python interpreter and interactive mode, values and types – int, float, boolean, string, and list, variables, expressions, statements,
tuple assignment, operators and precedence of operators, comments, Control Flow Statements – Conditionals – conditional (if),
alternative (if-else), chained conditional (if-elif-else), Iteration – state, while, for, break, continue, pass, Illustrative programs –
exchange the values with and without using temporary variables, circulate the values of n variables, distance between two points.

UNIT - III FUNCTIONS, STRINGS 9


Functions – function definition and use, flow of execution, parameters and arguments, function composition, Fruitful functions –
return values, parameters, local and global scope, recursion, Strings – string slices, immutability, string functions and methods,
string module, Illustrative programs – square root, GCD, exponentiation, Factorial of a number, linear search, binary search.

UNIT - IV LISTS, TUPLES, DICTIONARIES 9


Lists – list operations, list slices, list methods, list loop, mutability, aliasing, cloning lists, list parameters, Lists as arrays, Tuples –
tuple assignment, tuple as return value, Dictionaries – operations and methods, Advanced list processing –List comprehension,
Illustrative programs – selection sort, insertion sort, Matrix addition and subtraction, sum an array of numbers.

UNIT - V FILES, MODULES, PACKAGES 9


Files and exception – text files, reading and writing files, format operator, command line arguments, errors and exceptions,
handling exceptions, modules, packages – Math and Rand, Illustrative programs – word count, copy file, merge two files.

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.

Basic characteristics about computer are:

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

Types of Computers Computer sizes and power

Computers can be generally classified by size and power as follows,though there is considerable
overlap:

 Personal computer: A small, single-user computer based on amicroprocessor.


 Workstation: A powerful, single-user computer. A workstation is like a personal computer, but it
has a more powerful microprocessor and,in general, a higher-quality monitor.
 Minicomputer: A multi-user computer capable of supporting up to hundreds of users
simultaneously.
 Mainframe: A powerful multi-user computer capable of supporting many hundreds or thousands
of users simultaneously.
 Supercomputer: An extremely fast computer that can perform hundreds of millions of instructions
per second.

Supercomputer and Mainframe


Supercomputer is a broad term for one of the fastest computers currently available. Supercomputers are
very expensive and are employed for specialized applications that require immense amounts of mathematical
calculations (number crunching). For example, weather forecasting requires a supercomputer. Other uses of
supercomputers scientific simulations, (animated) graphics, fluid dynamic calculations, nuclear energy
research, electronic design, and analysis of geological data (e.g. in petrochemical prospecting). Perhaps the
best known supercomputermanufacturer is Cray Research.

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:

 Cache memory has limited capacity.

 It is very expensive.

Primary Memory (Main Memory)


Primary memory holds only those data and instructions on which computer is currently working. It has
limited capacity and data is lost when power is switched off. It is generally made up of semiconductor
device. These memories are not as fast as registers. The data and instruction required to be processed reside
in main memory. It is divided into two subcategories RAM and ROM.

RAM or Primary Memory

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.

Characteristic of Secondary Memory

 These are magnetic and optical memories


 It is known as backup memory.
 It is non-volatile memory.
 Data is permanently stored even if power is switched off.
 It is used for storage of data in a computer.
 Computer may run without secondary memory.
 Slower than primary memories

Peripheral and I/O Hardware

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.

PROBLEM SOLVING TECHNIQUES


Problem solving technique is a set of techniques that helps in providing logic for solving a
problem. Problem solving can be expressed in the form of
1. Algorithms.
2. Flowcharts.
3. Pseudo codes.
4. Programs
ALGORITHM

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

 Should be written in simple English


 Each and every instruction should be precise and unambiguous.
 Instructions in an algorithm should not be repeated infinitely.
 Algorithm should conclude after a finite number of steps.
 Should have an end point
 Derived results should be obtained only after the algorithm terminates.

Qualities of a good algorithm

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

Building Blocks of Algorithm


As algorithm is a part of the blue-print or plan for the computer program. An algorithm isconstructed
using following blocks.
 Statements
 States
 Control flow
 Function
Statements
Statements are simple sentences written in algorithm for specific purpose. Statements may
consists of assignment statements, input/output statements, comment statements
Example:
 Read the value of ‘a’ //This is input statement
 Calculate c=a+b //This is assignment statement
 Print the value of c // This is output statement
Comment statements are given after // symbol, which is used to tell the purpose of the line.
States
An algorithm is deterministic automation for accomplishing a goal which, given an initial state, will
terminate in a defined end-state. An algorithm will definitely have start state and end state.

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.

2. Input/ Output Parallelogram Denotes either input or


symbol output operation.

3. Process symbol Rectangle Denotes the process to be


carried

4. Decision symbol Diamond Represents decision


making and branching

5. Flow lines Arrow lines Represents the sequence


of steps and direction of
flow. Used to connect
symbols.

6. Connector Circle A connector symbol is


represented by a circle
and a letter or digit is
placed in the circle to
specify the link. This
symbol is used to
connect flowcharts.

Rules for drawing flowchart


1. In drawing a proper flowchart, all necessary requirements should be listed out in logicalorder.
2. The flow chart should be clear, neat and easy to follow. There should not be any roomfor ambiguity
in understanding the flowchart.
3. The usual directions of the flow of a procedure or system is from left to right or top tobottom.
Only one flow line should come out from a process symbol.
4. Only one flow line should enter a decision symbol, but two or three flow lines, one for each possible
answer, cap leave the decision symbol.

5. Only one flow line is used in conjunction with terminal symbol.

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.

Control Structures using flowcharts and Pseudocode

Sequence Structure

Pseudocode Flow Chart


General Structure
Process 1
…. Process 1
Process 2

Process 2
Process 3

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

Pseudocode Flow Chart


General Structure
IF condition THEN
Process 1 Yes if(condition)
ELSE
Process 2
ENDIF Process 1 No

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

Iteration or Looping Structure


 Looping is generally used with WHILE or DO...WHILE or FOR loop.
 WHILE and FOR is entry checked loop

Pseudocode Flow Chart


General Structure
WHILE condition
Body of the loop No
ENDWHILE if(condition)

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

WHILE a<10 THEN


PRINT a
a=1
a=a+1
ENDWHILE
No
if (a<10)

Yes
Stop

Print a

a=a+1

o In python DO…WHILE is not supported.


o If the loop condition is true then the loop gets into infinite loop, which may lead to system
crash

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.

Language Type Example


Interpreted Programming Language Python, BASIC, Lisp
Functional Programming Language Clean, Curry, F#
Compiled Programming Language C++,Java, Ada, ALGOL
Procedural Programming Language C,Matlab, CList
Scripting Programming Language PHP,Apple Script, Javascript
Markup Programming Language HTML,SGML,XML
Logical Programming Language Prolog, Fril
Concurrent Programming Language ABCL, Concurrent PASCAL
Object Oriented Programming Language C++,Ada, Java, Python

Interpreted Programming Language:


Interpreter is a program that executes instructions written in a high-level language.
An interpreter reads the source code one instruction or one line at a time, converts this line into
machine code and executes it.

Figure : Interpreter

Compiled Programming Languages


Compile is to transform a program written in a high-level programming language from source
code into object code. This can be done by using a tool called compiler.
A compiler reads the whole source code and translates it into a complete machine code program to
perform the required tasks which is output as a new file.

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

ALGORITHMIC PROBLEM SOLVING:


Algorithmic problem solving is solving problem that requirethe formulation of an
algorithm for the solution.

Understanding the Problem


 It is the process of finding the input of the problem that the algorithm solves.
 It is very important to specify exactly the set of inputs the algorith m needs to handle.
 A correct algorithm is not one that works most of the time, but one that works
Correctly for all legitimate inputs.
Ascertaining the Capabilities of the Computational Device

If the instructions are executed one after another, it is called sequential algorithm

Choosing between Exact and Approximate Problem Solving


 The next principal decision is to choose between solving the problem exactly or solving it
approximately.
 Based on this, the algorithms are classified as exact algorithm and approximation
algorithm.
 Data structure plays a vital role in designing and analysis the algorithms.
 Some of the algorithm design techniques also depend on the structuring data specifying a
problem’s instance
 Algorithm+ Data structure=programs.

Algorithm Design Techniques


 An algorithm design technique (or “strategy” or “paradigm”) is a general approach to solving
problems algorithmically that is applicable to a variety of problems from different areas of
computing.
 Learning these techniques is of utmost importance for the following reasons.
 First, they provide guidance for designing algorithms for new problems,
Second, algorithms are the cornerstone of computer science.

Methods of Specifying an Algorithm


 Pseudocode is a mixture of a natural language and programming language-like constructs.
Pseudocode is usually more precise than natural language, and its usage often yields more succinct
algorithm descriptions.In the earlier days of computing, the dominant vehicle for specifying
algorithms was a flowchart, a method of expressing an algorithm by a collection of connected
geometric shapes containing descriptions of the algorithm’s steps.

 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.

 A common technique for proving correctness is to use mathematical induction because an


algorithm’s iterations provide a natural sequence of steps needed for such proofs.

 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:

1. Odd or even number

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

3. Biggest of three numbers

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

4. Square root of a number

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

10. Bubble Sort

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

11. Linear Search.

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:

Python is a general-purpose interpreted, interactive, object-oriented, and high-levelprogramming


language. It was created by Guido van Rossum during 1985- 1990. Python got its name from “Monty
Python’s flying circus”. Python was released in the year 2000.
 Python is interpreted: Python is processed at runtime by the interpreter. You do not need to
compile your program before executing it.
 Python is Interactive: You can actually sit at a Python prompt and interact with the interpreter
directly to write your programs.
 Python is Object-Oriented: Python supports Object-Oriented style or technique of programming
that encapsulates code within objects.
 Python is a Beginner's Language: Python is a great language for the beginner-
Level programmers and supports the development of a wide range of applications.
Python Features:
 Easy-to-learn: Python is clearly defined and easily readable. The structure of the program is very
simple. It uses few keywords.
 Easy-to-maintain: Python's source code is fairly easy-to-maintain.
 Portable: Python can run on a wide variety of hardware platforms and has the same interface on all
platforms.
 Interpreted: Python is processed at runtime by the interpreter. So, there is no need to compile a
program before executing it. You can simply run the program.
 Extensible: Programmers can embed python within their C,C++,JavaScript
, ActiveX, etc.
 Free and Open Source: Anyone can freely distribute it, read the source code, and edit it.
 High Level Language: When writing programs, programmers concentrate on solutions of the
current problem, no need to worry about the low level details.
 Scalable: Python provides a better structure and support for large programs than shell scripting.
Applications:
 Bit Torrent file sharing
 Google search engine, YouTube
 Intel, Cisco, HP,IBM
 i–Robot
 NASA
 Face book, Drop box
Python interpreter:

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

No Intermediate is Object Code


Intermediate Object Code is Generated
Generated
Conditional Control Statements areExecutes Conditional Control Statements are
faster Executes slower
Memory Requirement is More(Since ObjectCode Memory Requirement is Less
is Generated)
Program need not be compiled every time Every time higher level program is
converted into lower level program
Errors are displayed after entire program is checked Errors are displayed for every instruction
interpreted (if any)
Example : C Compiler Example : PYTHON

Modes of python interpreter:


Python Interpreter is a program that reads and executes Python code. It uses 2 modes of Execution.
1. Interactive mode
2. Script mode
Interactive mode:
 Interactive Mode, as the name suggests, allows us to interact with OS.
 When we type Python statement, interpreter displays the result(s) immediately.
Advantages:
 Python, in interactive mode, is good enough to learn, experiment or explore.
 Working in interactive mode is convenient for beginners and for testing small pieces of code.
Drawback:
 We cannot save the statements and have to retype all the statements once again to re-run them.
In interactive mode, you type Python programs and the interpreter displays the result:
>>> 1 + 1
2
The chevron, >>>, is the prompt the interpreter uses to indicate that it is ready for you to enter code. If you
type 1 + 1, the interpreter replies 2.
>>> print ('Hello, World!')
Hello, World!
This is an example of a print statement. It displays a result on the screen. In this case, the result is the words.

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.

Interactive mode Script mode


A way of using the Python interpreter by A way of using the Python interpreter to read and
typing commands and expressions at the prompt. execute statements in a 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.

Integrated Development Learning Environment(IDLE):


Is a graphical user interface which is completely written in Python.
It is bundled with the default implementation of the python language and also comes with optional
part of the Python packaging.
Features of IDLE:
Multi-window text editor with syntax highlighting.
Auto completion with smart indentation.
Python shell to display output with syntax highlighting.

2. VALUES AND DATATYPES

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

Concatenation >>>print(s+"friends") -Adding and printing the


good morning friends characters of two strings.

Repetition >>>print(s*2) Creates new strings,


good morning concatenating multiple copies of
the same string
good morning
in, not in (membership >>> s="good morning" Using membership operators to check a
operator) >>>"m" in s True particular character is in string or not.
>>> "a" not in s Returns true if present.
True

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

Slicing( ending >>>print(list1[1:3]) - Displaying items from 1st


position -1) [7.79, 101] till2nd.
Slice operator is used >>>print(list1[1:]) [7.79, 101, - Displaying items from 1st
to extract part of a 'hello'] position till last.
string, or some part of a
list
Python

Concatenation >>>print( list1+list2) -Adding and printing the


['python', 7.79, 101, 'hello', 'god', items of two lists.
6.78, 9]
Repetition >>>list2*3 Creates new strings, concatenating
['god', 6.78, 9, 'god', 6.78, 9, 'god', multiple
6.78, 9] copies of the same string
Updating the list >>>list1[2]=45 Updating the list using index value
>>>print( list1)
[‘python’, 7.79, 45, ‘hello’]
Inserting an element >>>list1.insert(2,"program") Inserting an element in 2ndposition
>>> print(list1)
['python', 7.79, 'program', 45,
'hello']
Removing an element >>>list1.remove(45) Removing an element by
>>> print(list1) giving the element directly
['python', 7.79, 'program', 'hello']

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

Slicing( ending >>>print(t[1:3])  Displaying items from1st


position -1) (7.79, 101) till2nd.

Concatenation >>>t+("ram", 67)  Adding tuple elements at


('python', 7.79, 101, 'hello', 'ram', the end of another tuple elements
67)

Repetition >>>print(t*2)  Creates new strings,


('python', 7.79, 101, 'hello', concatenating multiple copies of the
'python', 7.79, 101, 'hello')
same string

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'

Data type Compile time Run time


int a=10 a=int(input(“enter a”))
float a=10.5 a=float(input(“enter a”))
string a=”kln” a=input(“enter a string”)
list a=[20,30,40,50] a=list(input(“enter a list”))
tuple a=(20,30,40,50) a=tuple(input(“enter a tuple”))

3.Variables,Keywords Expressions, Statements, Comments, Docstring ,Lines And Indentation,


Quotation In Python, Tuple Assignment:

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

Valid declarations Invalid declarations


Num Number 1
Num num1
Num1 addition of program
_NUM 1Num
NUM_temp2 Num.no
IF if
Else else

STATEMENTS AND EXPRESSIONS:


Statements:
-Instructions that a Python interpreter can executes are called statements.
-A statement is a unit of code like creating a variable or displaying avalue.
34
>>> n = 17
>>>print (n)

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 AND OUTPUT

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.

OUTPUT: Output can be displayed to the user using Print statement .


Syntax:
print (expression/constant/variable)
Example:
>>> print ("Hello")
Hello

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

LINES AND INDENTATION:


Most of the programming languages like C, C++, Java use braces { } to define a block of code. But,
python uses indentation.
Blocks of code are denoted by line indentation.
It is a space given to the block of codes for class and function definitions or flow control.
Example:
a=3
b=1
if a>b:
print("a is greater")
else:
print("b is greater")

QUOTATION INPYTHON:
Python accepts single ('), double (") and triple (''' or """) quotes to denote string literals. Anything that is
represented using quotations are considered as string.

Single quotes(' ') Eg, 'This a string in single quotes'


double quotes(" ") Eg, "'This a string in double quotes'"
triple quotes(""" """) Eg, This is a paragraph. It is made up of multiple lines and
sentences."""

TUPLE ASSIGNMENT

An assignment to all of the elements in a tuple using a single assignment statement.


Python has a very powerful tuple assignment feature that allows a tuple of variables on the left of an
assignment to be assigned values from a tuple on the right of the assignment.
The left side is a tuple of variables; the right side is a tuple of values.
Each value is assigned to its respective variable.
All the expressions on the right side are evaluated before any of the assignments. This feature makes
tuple assignment quite versatile.
Naturally, the number of variables on the left and the number of values on the right have to be the
same.
>>>(a, b, c, d) = (1, 2, 3)
ValueError: need more than 3 values to unpack

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:

Swap two numbers Output:


a=2;b=3
print(a,b) (2, 3)
temp = a (3, 2)
a=b >>>
b = temp
print(a,b)
-Tuple assignment solves this problem neatly:

(a, b) = (b, a)

-One way to think of tuple assignment is as tuple packing/unpacking.


In tuple packing, the values on the left are ‘packed’ together in a tuple:

>>>b = ("George",25,"20000") # tuplepacking

-In tuple unpacking, the values in a tuple on the right are ‘unpacked ‘into the variables/names on theright:

>>>b = ("George", 25, "20000") # tuple packing


>>>(name, age, salary)=b # tupleunpacking
>>>name
'George'
>>>age
25
>>>salary
'20000'

-The right side can be any kind of sequence (string, list,tuple)


Example:
-To split an email address in to user name and a domain
>>>mailid='god@abc.org'
>>>name,domain=mailid.split('@')
>>>print name god
>>> print (domain) abc.org

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

Operator Description Example

+ Addition Adds values on either side of the operator. a + b = 30

- Subtraction Subtracts right hand operand from left hand a – b = -10


operand.

* Multiplication Multiplies values on either side of the operator a * b = 200

/ Division Divides left hand operand by right hand operand b/a=2

% Modulus Divides left hand operand by right hand operand and returns b%a=0
remainder

** Exponent Performs exponential (power) calculation on a**b =10 to the


operators power 20

// 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 the values of two operands are equal, then the condition (a == b) is

becomes true. not true.

!= 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

**= Exponent Performs exponential (power) calculation on c **= a is


AND operators and assign value to the left 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

** Exponentiation (raise to the power)

~+- Complement, unary plus and minus (method names for the
last two are +@ and -@)

* / % // Multiply, divide, modulo and floor division

+- Addition and subtraction

>><< Right and left bitwise shift

& Bitwise 'AND'

^| Bitwise exclusive `OR' and regular `OR'

<= <>>= Comparison operators

<> == != Equality operators

= %= /= //= -= += *= **= Assignment operators

is is not Identity operators

in not in Membership operators

not or and Logical operators

-For mathematical operators, Python follows mathematical convention.


-The acronym PEMDAS (Parentheses, Exponentiation, Multiplication, Division, Addition, Subtraction) is a
useful way to remember the rules:
• Parentheses have the highest precedence and can be used to force an expression to evaluate in the
order you want. Since expressions in parentheses are evaluated first, 2 * (3-1)is 4, and (1+1)**(5-2)
is8.
• You can also use parentheses to make an expression easier to read,asin(minute
* 100) / 60, even if it doesn’t change the result.
• Exponentiation has the next highest precedence, so 1 + 2**3 is 9, not 27, and2
*3**2 is 18, not 36.
• Multiplication and Division have higher precedence than Addition and Subtraction. So 2*3-1 is 5,
not 4, and 6+4/2 is 8, not5.
• Operators with the same precedence are evaluated from left to right (except exponentiation).

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:

Program to provide bonus mark if the category is output


sports
m=eval(input(“enter ur mark out of 100”)) enter ur mark out of 100
c=input(“enter ur categery G/S”) 85
if(c==”S”): enter ur categery G/S
m=m+5 S
print(“mark is”,m) mark is 90

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

Odd or even number Output


n=eval(input("enter a number")) enter a number4
if(n%2==0): even number
print("even number")
else:
print("odd number")
positive or negative number Output
n=eval(input("enter a number")) enter a number8
if(n>=0): positive number
print("positive number")
else:
print("negative number")
leap year or not Output
y=eval(input("enter a year")) enter a year2000
if(y%4==0): leap year
print("leap year")
else:
print("not leap year")

62
Chained conditionals (if-elif-else)

 The elif is short for else if.


 This is used to check more than one condition.

 If the condition1 is False, it checks the condition2 of the elif block. If all the conditions are
False, then the else part is executed.

 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

student mark system Output


mark=eval(input("enter ur mark:")) enter ur mark:78
if(mark>=90): grade:B
print("grade:S")
elif(mark>=80):
print("grade:A")
elif(mark>=70):
print("grade:B")
elif(mark>=50):
print("grade:C")
else:
print("fail")
traffic light system Output
colour=input("enter colour of light:") enter colour of light:green
if(colour=="green"): GO
print("GO")
elif(colour=="yellow"):
print("GET READY")
else:
print("STOP")

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):

print(“the greatest no is”,b)

else:
print(“the greatest no is”,c)

positive negative or zero output


n=eval(input("enter the value of n:")) enter the value of n:-9
if(n==0): the number is negative
print("the number is zero")
else:
if(n>0):
print("the number is positive")
65
else:
print("the number is negative")

2.Iteration Or Control Statements.


 state
 while
 for
 break
 continue
 pass

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:

Sum of digits of a number: output


n=eval(input("enter a number")) enter a number
sum=0 123
while(n>0): 6
a=n%10
sum=sum+a
n=n//10
print(sum)

Sum of n numbers: output


n=eval(input("enter n")) enter n
i=1 10
sum=0 55
while(i<=n):
sum=sum+i
i=i+1
print(sum)

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.

Sequence can be a list, strings or tuples

s.no sequences example output


R
1. For loop in string for i in "Ramu": A
print(i) M
U

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.")

3. Loop Control Structures


BREAK
 Break statements can alter the flow of a loop.
 It terminates the current
 loop and executes the remaining statement outside the loop.
 If the loop has else statement, that will also gets terminated and come out of the loop completely.
Syntax:
break

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

Difference between break and continue

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

for i in "welcome": for i in "welcome":


if(i=="c"): if(i=="c"):
break continue
print(i) print(i)

w w
e e
l l
o
m
e

else statement in loops:

else in for loop:


 If else statement is used in for loop, the else statement is executed when the loop has reached the
limit.

The statements inside for loop and statements inside else will also execute.

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

else in while loop:


If else statement is used within while loop , the else part will be executed when the condition become
false.
The statements inside for loop and statements inside else will also execute.
Program output
i=1 1
while(i<=5): 2
print(i) 3
i=i+1 4
else: 5
print("the number greater than 5") the number greater than 5

ILLUSTRATIVE PROGRAMS

Program for SWAPPING(Exchanging )of Output


values
a = int(input("Enter a value ")) Enter a value 5
b = int(input("Enter b value")) Enter b value 8
c=a a=8
a=b b=5
b =c
print("a=",a,"b=",b,)

Program to find distance between twopoints Output

import math enter x17


x1=int(input("enter x1")) enter y16
y1=int(input("enter y1"))
enter x25
x2=int(input("enter x2"))
y2=int(input("enter y2")) enter y27
distance =math.sqrt((x2-x1)**2)+((y2- y1)**2) 2.5
print(distance)
Program to circulate n numbers Output:
a=list(input("enter the list")) enter the list '1234'

print(a) ['1', '2', '3', '4']


for i in range(1,len(a),1): ['2', '3', '4', '1']
print(a[i:]+a[:i]) ['3', '4', '1', '2']
['4', '1', '2', '3']
UNIT III FUNCTIONS, STRINGS
 Function is a sub program which consists of set of instructions used to perform a specific task.
A large program is divided into basic building blocks called function.
Need For Function:
• When the program is too complex and large they are divided into parts. Each part is separately
coded and combined into single program. Each subprogram is called as function.
• Debugging, Testing and maintenance becomes easy when the program is divided into
subprograms.
• Functions are used to avoid rewriting same code again and again in a program.
• Function provides code re-usability
• The length of the program is reduced.
Types of function:
Functions can be classified into two categories:
i) user defined function
ii) Built in function
i) Built in functions
• Built in functions are the functions that are already created and stored inpython.
• These built in functions are always available for usage and accessed by a programmer. It cannot be
modified.
Built in function Description

>>>max(3,4) 4 # returns largest element

>>>min(3,4) 3 # returns smallest element

>>>len("hello") 5 #returns length of an object

>>>range(2,8,1) [2, #returns range of given values


3, 4, 5, 6, 7]
>>>round(7.8) 8.0 #returns rounded integer of the given number

>>>chr(5) #returns a character (a string) from an integer


\x05'
>>>float(5)5.0 #returns float number from string or integer

>>>int(5.0) 5 # returns integer from string or float

>>>pow(3,5) 243 #returns power of given number

>>>type( 5.6) #returns data type of object to which it belongs


<type 'float'>
>>>t=tuple([4,6.0,7]) # to create tuple of items from list
(4, 6.0, 7)
>>>print("good morning") # displays the given object
Good morning
>>>input("enter name:") # reads and returns the given string
enter name : George
ii) User Defined Functions:
• User defined functions are the functions that programmers create for their requirement anduse.
• These functions can then be combined to form module which can be used in other programs by
importing them.
• Advantages of user defined functions:
 Programmers working on large project can divide the workload by making different functions.
 If repeated code occurs in a program, function can be used to include those codes and execute
when needed by calling that function.

Function definition: (Sub program)


• def keyword is used to define a function.
• Give the function name after def keyword followed by parentheses in which arguments are given.
• End with colon (:)
• Inside the function add the program statements to be executed
• End with or without return statement
Syntax:
def fun_name(Parameter1,Parameter2…Parameter n): statement1
statement2…
statement n return[expression]

Example:
def my_add(a,b):
c=a+b
return c

Function Calling: (Main Function)


 Once we have defined a function, we can call it from another function, program or even the
Pythonprompt.
 To call a function we simply type the function name with appropriate arguments.
Example:
x=5
y=4
my_add(x,y)

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

With return type


Without argument With argument
def add(): def add(a,b):
a=int(input("enter a")) c=a+b
b=int(input("enterb")) return c
a=int(input("enter a"))
c=a+b
b=int(input("enter b"))
return c c=add(a,b)
c=add() print(c)
print(c)

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.

defmy_details( name, age ):


print("Name: ", name)
print("Age ", age)
return
my_details("george",56)
Output:
Name:
georgeAge56
Keyword Arguments:
Python interpreter is able to use the keywords provided to match the values with parameters even though
if they are arranged in out of order.

def my_details( name, age ):


print("Name: ", name)
print("Age ", age)
return
my_details(age=56,name="george")
Output:
Name:
georgeAge56

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

Fruitful Function A function that returns a value is called fruitful function.


Example:
Root=sqrt (25)
Example:
def add():
a=10
b=20
c=a+b
return c
c=add()
print(c)
Void Function
A function that perform action but don’t return any value.
Example:
print(“Hello”)
Example:
def add():
a=10
b=20
c=a+b
print(c)
add()

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

Local and Global Scope

Global Scope

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

def add():
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.

find sum and average using function output


composition
def sum(a,b): enter a:4
sum=a+b enter b:8
return sum the avg is 6.0
def avg(sum):
avg=sum/2
return avg
a=eval(input("enter a:"))
b=eval(input("enter b:"))
sum=sum(a,b)
avg=avg(sum)
print("the avg is",avg)

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)

n=eval(input("enter no. to find


fact:"))
fact=fact(n)
print("Fact is",fact)
Explanation

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)

n=eval(input("enter no. to find sum: "))

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

>>>a=”HELLO” Positive indexing helps in accessing


indexing >>>print(a[0]) the string from the beginning

>>>H Negative subscript helps in accessing


>>>print(a[-1]) the string from the end.
>>>O
Print[0:4] – HELL The Slice[start : stop] operator extracts
Slicing: Print[ :3] – HEL sub string from the strings.
Print[0: ]- HELLO A segment of a string is called a slice.
a=”save” The + operator joins the text on both
Concatenation b=”earth” sides of the operator.
>>>print(a+b)
Save earth
a=”kln ” The * operator repeats the string on the
Repetitions: >>>print(3*a) left hand side times the value on right hand side.

klnklnkln

Membership: >>> s="good morning" Using membership operators to check a


>>>"m" in s particular character is in string or not.
True Returns true if present

>>> "a" not in s


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

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

element deletion a=”PYTHON” TypeError: 'str' object


del a[0] doesn't support element
deletion
delete a string a=”PYTHON” NameError: name 'my_string'
del a
print(a)
is not defined
string built in functions and methods:
A method is a function that “belongs to” an object.

Syntax to access the method

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

Escape sequences in string


Escape Description example
Sequence
\n new line >>> print("hai \nhello")
hai
hello
\\ prints Backslash (\) >>> print("hai\\hello")
hai\hello
\' prints Single quote (') >>> print("'")
'
\" prints Double quote >>>print("\"")
(") "
\t prints tab sapace >>>print(“hai\thello”)
hai hello
\a ASCII Bell (BEL) >>>print(“\a”)

ILLUSTRATIVE PROGRAMS

Square root using newtons method: Output:


def newtonsqrt(n): enter number to find Sqrt: 9
root=n/2 3.0
for i in range(10):
root=(root+n/root)/2
print(root)
n=eval(input("enter number to find Sqrt: "))
newtonsqrt(n)
GCD of two numbers output
n1=int(input("Enter a number1:")) Enter a number1:8
n2=int(input("Enter a number2:")) Enter a number2:24
for i in range(1,n1+1): 8
if(n1%i==0 and n2%i==0):
gcd=i
print(gcd)
Exponent of number Output:
def power(base,exp):
if(exp==1): Enter base: 2
return(base) Enter exponential value:3
else: Result: 8
return(base*power(base,exp-1))
base=int(input("Enter base: "))
exp=int(input("Enter exponential value:"))
result=power(base,exp)
print("Result:",result)
sum of array elements: output:
a=[2,3,4,5,6,7,8]
sum=0 the sum is 35
for i in a:
sum=sum+i
print("the sum is",sum)
Linear search output
a=[20,30,40,50,60,70,89]
print(a)
search=eval(input("enter a element to search:")) [20, 30, 40, 50, 60, 70, 89]
for i in range(0,len(a),1): enter a element to search:30
if(search==a[i]): element found at 2
print("element found at",i+1)
break
else:
print("not found")

Factorial of a numbers: output

n=eval(input("enter n")) enter n


i=1 5
fact=1 120
while(i<=n):
fact=fact*i
i=i+1
print(fact)

Binary search output


a=[20, 30, 40, 50, 60, 70, 89] [20, 30, 40, 50, 60, 70, 89]
print(a) enter a element to search:30
search=eval(input("enter a element to search:")) element found at 2
start=0
stop=len(a)-1
while(start<=stop):
mid=(start+stop)//2
if(search==a[mid]):
print("element found at",mid+1)
break
elif(search<a[mid]):
stop=mid-1
else:
start=mid+1
else:
print("not found")
UNIT IV - LISTS, TUPLES, DICTIONARIES
LIST
o List is a sequence of values, which can be of different types. The values in list are
called"elements" or ''items''
o Each elements in list is assigned a number called "position" or "index"
o A list that contains no elements is called an empty list. They are created with
emptybrackets[]
o A list within another list is nested list

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

Concatenation: the '+' operator concatenate list


>>> a = [1,2,3]
>>> b = [4,5,6]
>>> c = a+b
>>> Print (a*2) => [1,2,3,1,2,3]

Repetition: the '*' operator repeats a list a given number of times


>>> a = [1,2,3]
>>> b = [4,5,6]
>>> print (a*2)= [1,2,3,1,2,3]

List looping: (traversing a list)


Looping in a list is used to access every element in list
"for loop" is used to traverse the elements in list
eg: mylist = ["python","problem",100,6.28]
for i in range (len (mylist)):
print (mylist [i])
LIST SLICES:
List slicing is a computationally fast way to methodically access parts of given data.
Syntax:
Listname[start:end:step]where :end represents the first value that is not in the selected slice. The
differencebetween end and start is the numbe of elements selected (if step is 1, the default).The start and
end may be a negative number. For negative numbers, the count starts from the end of the array instead of
the beginning.
Example:
>>>t=[‘a’,’b’,’c’,’d’,’e’,’f’]
Lists are mutable, so it is useful to make a copy before performing operations that modify this.
A slice operator on the left side of an assignment can update multiple elements.
Example:
>>>t[1:3]=[‘x’,’y’]
>>>t
Output:
[‘a’,’x’,’y’,’d’,’e’,’f’]
Aliasing:
 when more than one variables refers to the same objects or list, then it is called aliasing.

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 for mutable data types are:


List, Set and Dictionary

Example 1:
>>>numbers=[42,123]
>>>numbers[1]=5
>>>numbers[42,5]

Here, the second element which was 123 is now turned to be 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',

>>> type (t)


< class 'tuple'>
Alternative way to create a tuple is the built-in function tuple which mean, it creates an empty tuple
>>> t = tuple ()
>>> t
>>> ( )
Accessing element in tuple:
If the argument in sequence, the result is a tuple with the elements of sequence.
>>>t= tuple('python')
>>> t
('p','y','t','h','o','n')
t=
('a','b',100,8.02)
print (t[0]) = 'a'
print (t[1:3]) = ('b', 100 , 8.02)

Deleting and updating tuple:


Tuple are immutable, hence the elements in tuple cannot be updated / modified
But we can delete the entire tuple by using keyword 'del'
Eg 1: a = (' programming', 200, 16.54, 'c', 'd')
#Try changing an element.
a[ 0 ] = 'python' < --------- Error,modifying not possible
print (a [0])
Eg: # Deletion of
tuplea =
('a','b','c','d')
del (a) ---------- delete entire tuple
del a [1] < ---------- error,deleting one element in tuple not possible
Eg: # replacing one tuple with
anothera = ('a','b','c','d')
t = ('A',) + a[1: ]
print (t) < ------ ('a','b','c','d')
Tuple Assignment:
 Tuple assignment is often useful to swap any number of values
 the number of variables in left and right of assignment operators must be equal
 A single assignment to paralleling assign value to all elements of tuple is the major benefit
oftuple assignment
Eg: Tuple swapping in python
A= 100
B= 345
C= 450
print (" A & B:", A,"&",B) # Tuple assignments for two variables A,B = B,A
print (" A&B after tuple assignment : ",A,"&",B) # Tuple assignment can be done for no of variables
A,B,C = C,A,B
print (" Tuple assignment for more variables:",A,"&",B,"&",C)
Output
A & B: 100 & 345
A&B after tuple assignment : 345 & 100
Tuple assignment for more variables: 450 & 345 & 100

Tuple as return value:


 Generally, function can only return one value but if the value is tuple the same as returning
themultiple value
 Function can return tuple as return value
Eg: # the value of quotient & remainder are returned as tuple
def mod_div(x,y):
quotient= x/y
remainder= x%y
return quotient, remainder
# Input the seconds & get the hours minutes &second sec
4234
minutes,seconds= mod_div
(sec,60)
hours,minutes=mod_div(minut
es, 60)
print("%d seconds=%d hrs:: %d min:: %d sec"%(sec,hours,minutes,seconds))
Output:
4234seconds=1 hrs:: 10 min:: 34 sec

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.

4.3 State Diagram


4.4 State Diagram
ADVANCED LIST PROCESSING
List processing is a list of programming codes, including abstract data structure, used to calculate
specified variables in a certain order. A value may repeat more than once.
LIST COMPREHENSION
The function shown below takes a list of strings, maps the string method capitalize to the
elements, and returns a new list of strings:
def capitalize_all(t):
res = []
for s in t:
res.append(s.capitalize())
return res
We can write this more concisely using a list comprehension:
def capitalize_all(t):
return [s.capitalize() for s in t]
The bracket operators indicate that we are constructing a new list. The expression inside the
brackets specifies the elements of the list, and the ‘for’ clause indicates what sequence we are
traversing.The syntax of a list comprehension is a little awkward because the loop variable, s in this
example, appears in the expression before we get to the definition.
List comprehensions can also be used for filtering. For example, this function selects only the
elements of t that are upper case, and returns a new list:
def only_upper(t):
res = []
for s in t:
if s.isupper():
res.append(s)
return res
We can rewrite it using a list comprehension
def only_upper(t):
return [s for s in t if s.isupper()]
List comprehensions are concise and easy to read, at least for simple expressions. And they are
usually faster than the equivalent for loops, sometimes much faster.
But, list comprehensions are harder to debug because we can’t put a print statement inside the
loop. We can use them only if the computation is simple enough that we are likely to get it right the first
time.
ILLUSTRATIVE PROGRAMS
SELECTION SORT
Selection sort is one of the simplest sorting algorithms. It is similar to the hand picking where we
take the smallest element and put it in the first position and the second smallest at the second position and
so on. It is also similar. We first check for smallest element in the list and swap it with the first element of
the list. Again, we check for the smallest number in a sub list, excluding the first element of the list as it
is where it should be (at the first position) and put it in the second position of the list. We continue
repeating this process until the list gets sorted.
ALGORITHM:
1. Start from the first element in the list and search for the smallest element in the list.
2. Swap the first element with the smallest element of the list.
3. Take a sub list (excluding the first element of the list as it is at its place) and
search for the smallest number in the sub list (second smallest number of the entire list)and
swap it with the first element of the list (second element of the entire list).
4. Repeat the steps 2 and 3 with new subsets until the list gets sorted.
PROGRAM:
a = [16, 19, 11, 15, 10, 12, 14]
i=0
while i<len(a):
#smallest element in the sublist
smallest = min(a[i:])
#index of smallest element
index_of_smallest = a.index(smallest)
#swapping
a[i],a[index_of_smallest] = a[index_of_smallest],a[i]
i=i+1
print (a)
Output
>>>
[10, 11, 12, 14, 15, 16, 19]
INSERTION SORT
Insertion sort is similar to arranging the documents of a bunch of students in order of their
ascending roll number. Starting from the second element, we compare it with the first element and swap it
if it is not in order. Similarly, we take the third element in the next iteration and place it at the right place
in the sub list of the first and second elements (as the sub list containing the first and second elements is
already sorted). We repeat this step with the fourth element of the list in the next iteration and place it at
the right position in the sub list containing the first, second and the third elements. We repeat this process
until our list gets sorted.
ALGORITHM:
1. Compare the current element in the iteration (say A) with the previous adjacent elementto it. If
it is in order then continue the iteration else, go to step 2.
2. Swap the two elements (the current element in the iteration (A) and the previous adjacentelement
to it).
3. Compare A with its new previous adjacent element. If they are not in order, then proceedto step
4.
4. Swap if they are not in order and repeat steps 3 and 4.
5. Continue the iteration.
PROGRAM:
a = [16, 19, 11, 15, 10, 12, 14]
#iterating over a
for i in a:
j = a.index(i)
#i is not the first element
while j>0:
#not in order if
a[j-1] > a[j]:
#swap
a[j-1],a[j] = a[j],a[j-1]
else:
#in order
break
j = j-1
print (a)
Output
>>>
[10, 11, 12, 14, 15, 16, 19]

Matrix Addition and Subtraction:

#Matrix Addition(Run Time Input)


n=int(input("Enter no. of rows in matrix: "))
m=int(input("Enter no. of columns in matrix: "))
print("Enter ",n*m," Elements for First Matrix: ")
Matrix1=[]
for i in range(n):
Matrix1.append([])
for j in range(m):
Matrix1[i].append(int(input()))
Matrix2 = []
print("Enter ",n*m," Elements for Second Matrix: ")
for i in range(n):
Matrix2.append([])
for j in range(m):
Matrix2[i].append(int(input()))
Matrix3 = []
print("Addition of Two Given Matrices:")
for i in range(n):
Matrix3.append([])
for j in range(m):
Add = Matrix1[i][j] + Matrix2[i][j] #for subtraction Sub= Matrix1[i][j] - Matrix2[i][j]
Matrix3[i].append(Add)
print(Matrix3[i][j], end=" ")
print()

Sum of Array of numbers:

sum of array elements: output:


a=[2,3,4,5,6,7,8]
sum=0 the sum is 35
for i in a:
sum=sum+i
print("the sum is",sum)

You might also like