Python UNIT 1
Python UNIT 1
INTRODUCTION
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 a
correct 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
1. 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
2
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
3
3. Read b
4. If a>b then
Print a is greater
else
Print b is greater
5. Stop
Function
A function is a block of organized, reusable code that is used to perform a single, related
action. 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
4
Step2:Geta,bValues
Step 3: add c=a+b
Step 4: Printc
Step 5: Return
2. NOTATIONS OF AN ALGORITHM
Algorithm can be expressed in many different notations, including Natural Language,
Pseudo code, flowcharts and programming languages. Natural language tends to be verbose
and 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
READ num1,num2
sum=num1+num2
PRINT sum
Basic rules to write pseudocode:
1. Only one statement per line.
Statements represents single action is written on same line. For example to read the
input, all the inputs must be read using single statement.
2. Capitalized initial keywords
The keywords should be written in capital letters. Eg: READ, WRITE, IF, ELSE,
ENDIF, WHILE, REPEAT, UNTIL
Example:
Pseudocode: Find the total and average of three subjects
RAED name, department, mark1, mark2, mark3
Total=mark1+mark2+mark3
Average=Total/3
WRITE name, department,mark1, mark2, mark3
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:
5
Pseudocode: Find greatest of two numbers
READ a, b
IF a>b then
PRINT a is greater
ELSE
PRINT b 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 with
flowchart
Disadvantages of Pseudocode
• It is not visual
• There is no standardized style or format
Flowchart
A graphical representation of an algorithm. Flowcharts is a diagram made up of boxes,
diamonds, and other shapes, connected by arrows.
Each shape represents a step in process and arrows show the order in which they occur.
Table 1: Flowchart Symbols
S.No Name of Symbol Type Description
symbol
1. Terminal Oval Represent the start and
Symbol stop of the program.
6
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.
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 conjun ctio n with terminal symbol.
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 various
purposes.
Efficient Coding
7
The flowcharts act as a guide or blue print during the system analysis and program
development 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 flowchart
becomes 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 becomes
problematic.
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
8
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.
Process 1 No
Process 2
Example
READ a
READ b Start
IF a>b THEN
PRINT a is greater a=10,b=20
Yes if (a>b )
Print a is greater No
Stop
IF… ELSE
IF…THEN…ELSE is the structure used to specify, if the condition is true, then execute Process1,
else, that is condition is false then execute Process2
Process 2
Example
9
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 g reater
Stop
Yes
Body of the loop
Example
• DO…WHILE is exit checked loop, so the loop will be executed at least once.
10
INITIALIZE a=1 Start
Yes
Stop
Print a
a=a+1
Programming Language
• A programming language is a vocabulary and set of grammatical rules for instructing a computer
or computing device to perform specific tasks. In other word it is set of instructions for the
computer to solve the problem.
• Programming Language is a formal language with set of instruction, to the computer to solve a
problem. The program will accept the data to perform computation.
Program= Algorithm +Data
Need for Programming Languages
• Programming languages are also used to organize the computation
• Using Programming language we can solve different problems
• To improve the efficiency of the programs.
Types of Programming Language
In general Programming languages are classified into three types. They are
• Low – level or Machine Language
• Intermediate or Assembly Language
• High – level Programming language
Machine Language:
Machine language is the lowest-level programming language (except for computers that utilize
programmable microcode). Machine languages are the only languages understood by computers. It is also
called as low level language.
Example code:100110011
111001100
Assembly Language:
An assembly language contains the same instructions as a machine language, but the instructions
and variables have names instead of being just numbers. An assembler language consists of mnemonics,
mnemonics that corresponds unique machine instruction.
Example code: start
addx,y
subx,y
11
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.
g
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
If the instructions are executed one after another, it is called sequential algorithm
• Programming language can be fed into an electronic computer directly. Instead, it needs to be
converted into a computer program written in a particular computer language. We can look at such
a program as yet another way of specifying the algorithm, although it is preferable to consider it as
the algorithm’s implementation.
• Once an algorithm has been specified, you have to prove its correctness. That is, you have to
prove that the algorithm yields a required result for every legitimate input in a finite amount of
time.
• It might be worth mentioning that although tracing the algorithm’s performance for a few specific
inputs can be a very worthwhile activity, it cannot prove the algorithm’s correctness conclusively.
But in order to show that an algorithm is incorrect, you need just one instance of its input for
which the algorithm fails.
Analyzing an Algorithm
1. Efficiency.
Time efficiency: indicating how fast the algorithm runs,
Space efficiency: indicating how much extra memory it uses
14
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.
Coding an Algorithm
▪ Most algorithms are destined to be ultimately implemented as computer programs.
Programming an algorithm presents both a peril and an opportunity.
▪ A working program provides an additional opportunity in allowing an empirical analysis
of the underlying algorithm. Such an analysis is based on timing the program on several
inputs and then analyzing the results obtained.
15
Recursions:
❖ A function that calls itself is known as recursion.
❖ Recursion is a process by which a function calls itself repeatedly until some specified condition has
beensatisfied.
Main function:
Step1: Start
Step2: Get n
Step3: call factorial(n)
Step4: print fact
Step5: Stop
16
FLOW CHART
Main function:
BEGIN
GET n
CALL
factorial(n)
PRINT fact
BIN
IF(n==1) THEN
fact=1
RETURN fact
ELSE
RETURN fact=n*factorial(n-1)
17
5. ILLUSTRATIVE PROBLEMS
1. Guess an integer in a range
Algorithm:
Step1: Start
Step 2: Declare n, guess
Step 3: Compute guess=input
Step 4: Read guess
Step 5: If guess>n, then
Print your guess is too high
Else
Step6:If guess<n, then
Print your guess is too low
Else
Step 7:If guess==n,then
Print Good job
Else
Nope
Step 6: Stop
Pseudocode:
BEGIN
COMPUTE guess=input
READ guess,
IF guess>n
PRINT Guess is high
ELSE
IF guess<n
PRINT Guess is low
ELSE
IF guess=n
PRINT Good job
ELSE
Nope
END
18
Flowchart:
Start
Read n
Read
Guess number
Guess=input
If Guess>n
If Guess<n
Good job
Stop
19
2. Find minimum in a list
Algorithm:
Step 1: Start
Step 2: Read n
Step 3:Initialize i=0
Step 4: If i<n, then goto step 4.1, 4.2 else goto step 5
Step4.1: Read a[i]
Step 4.2: i=i+1 goto step 4
Step 5: Compute min=a[0]
Step 6: Initialize i=1
Step 7: If i<n, then go to step 8 else goto step 10
Step 8: If a[i]<min, then goto step 8.1,8.2 else goto 8.2
Step 8.1: min=a[i]
Step 8.2: i=i+1 goto 7
Step 9: Print min
Step 10: Stop
Pseudocode:
BEGIN
READ n
FOR i=0 to n, then
READ a[i]
INCREMENT i
END FOR
COMPUTE min=a[0]
FOR i=1 to n, then
IF a[i]<min, then
CALCULATE min=a[i]
INCREMENT i
ELSE
INCREMENT i
END IF-ELSE
END FOR
PRINT min
END
20
Flowchart:
21
3. Insert a card in a list of sorted cards
Algorithm:
Step 1: Start
Step 2: Read n
Step 3:Initialize i=0
Step 4: If i<n, then goto step 4.1, 4.2 else goto step 5
Step4.1: Read a[i]
Step 4.2: i=i+1 goto step 4
Step 5: Read item
Step 6: Calculate i=n-1
Step 7: If i>=0 and item<a[i], then go to step 7.1, 7.2 else goto step 8
Step 7.1: a[i+1]=a[i]
Step 7.2: i=i-1 goto step 7
Step 8: Compute a[i+1]=item
Step 9: Compute n=n+1
Step 10: If i<n, then goto step 10.1, 10.2 else goto step 11
Step10.1: Print a[i]
Step10.2: i=i+1 goto step 10
Step 11: Stop
Pseudocode:
BEGIN
READ n
FOR i=0 to n, then
READ a[i]
INCREMENT i
END FOR
READ item
FOR i=n-1 to 0 and item<a[i], then
CALCULATE a[i+1]=a[i]
DECREMENT i
END FOR
COMPUTE a[i+1]=a[i]
COMPUTE n=n+1
FOR i=0 to n, then
PRINT a[i]
INCREMENT i
END FOR
END
22
Flowchart:
23
4. Tower of Hanoi
Tower of Hanoi, is a mathematical puzzle which consists of three towers (pegs) and more
than one rings.
Tower of Hanoi is one of the best example for recursive problem solving.
Pre-condition:
These rings are of different sizes and stacked upon in an ascending order, i.e. the smaller
one sits over the larger one. There are other variations of the puzzle where the number of disks
increase, but the tower count remains the same.
Post-condition:
All the disk should be moved to the last pole and placed only in ascending order as shown
below.
Rules
The mission is to move all the disks to some another tower without violating the sequence
of arrangement. A few rules to be followed for Tower of Hanoi are
• Only one disk can be moved among the towers at any given time.
• Only the "top" disk can be removed.
• No large disk can sit over a small disk.
Tower of Hanoi puzzle with n disks can be solved in minimum 2n−1 steps. This presentation
shows that a puzzle with 3 disks has taken 23 - 1 = 7 steps.
Algorithm
To write an algorithm for Tower of Hanoi, first we need to learn how to solve this problem with
lesser amount of disks, say → 1 or 2. We mark three towers with name, source, aux (only to help
moving the disks) and destination.
Input: one disk
If we have only one disk, then it can easily be moved from source to destination peg.
Input: two disks
If we have 2 disks −
• First, we move the smaller (top) disk to aux peg.
• Then, we move the larger (bottom) disk to destination peg.
• And finally, we move the smaller disk from aux to destination peg.
Input: more than two disks
• So now, we are in a position to design an algorithm for Tower of Hanoi with more than
two disks. We divide the stack of disks in two parts. The largest disk (nth disk) is in one
part and all other (n-1) disks are in the second part.
24
• Our ultimate aim is to move disk n from source to destination and then put all other (n1)
disks onto it. We can imagine to apply the same in a recursive way for all given set of
disks.
• The steps to follow are –
Step 1 − Move n-1 disks from source to aux
Step 2 − Move nth disk from source to dest
Step 3 − Move n-1 disks from aux to dest
25
FLOW CHART Start
Stop
If disk==1?
Return
26
5. Draw a flow chart to find greatest among three numbers.(AU 2018)
27
2 MARKS
1. What is an algorithm?
An algorithm is a finite number of clearly described, unambiguous do able steps that
can be systematically followed to produce a desired results for given input in the given amount
of time. In other word, an algorithm is a step by step procedure to solve a problem with finite
number of steps.
Algorithm Program
1. Systematic logical approach which is a It is exact code written for
well-defined, step-by-step procedure that problem following all the rules of the
allows a computer to solve a problem. programming language.
2. An algorithm is a finite number of clearly The program will accept the data to
described, unambiguous do able steps that perform computation.
can be systematically followed to produce
a desired results for given input in the Program=Algorithm + Data
given amount of time.
6. Write an algorithm to accept two numbers, compute the sum and print the result.
Step 1: Start
Step 2: Declare variables num1,num2 and sum,
Step 3: Read values num 1 and num2.
Step 4: Add and assign the result to sum.
Sum←num1+num2
Step 5: Display sum
28
7. Differentiate between iteration and recursion.
29
11. Draw a flow chart to find whether the given number is leap year or not.
Start
Read year
If
(year%4==0)
Stop
30
UNIT II
DATA, EXPRESSIONS, STATEMENTS
Python interpreter and interactive mode; values and types: int, float, boolean, string, and list; variables,
expressions, statements, tuple assignment, precedence of operators, comments; Modules and functions,
function definition and use, flow of execution, parameters and arguments; Illustrative programs: exchange
the values of two variables, circulate the values of n variables, distance between two points.
1. INTRODUCTION TO PYTHON:
• 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
31