PYTHON Notes Unit1&Unit2
PYTHON Notes Unit1&Unit2
PYTHON Notes Unit1&Unit2
REGULATION 2021
I YEAR - I SEMESTER
GE3151 - PROBLEM SOLVING AND PYTHON PROGRAMMING
GE3151 PROBLEM SOLVING AND PYTHON PROGRAMMING COURSE OBJECTIVES:
To understand the basics of algorithmic problem solving.
To learn to solve problems using Python conditionals and loops.
To define Python functions and use function calls to solve problems.
To use Python data structures – lists, tuples, dictionaries to represent complex data.
REFERENCES:
Paul Deitel and Harvey Deitel, “Python for Programmers”, Pearson Education, 1st Edition, 2021.
G Venkatesh and Madhavan Mukund, “Computational Thinking: A Primer for Programmers and Data
Scientists”, 1st Edition, Notion Press, 2021.
John V Guttag, "Introduction to Computation and Programming Using Python:
With Applications to Computational Modeling and Understanding Data„„, Third Edition, MIT Press
2021
Eric Matthes, “Python Crash Course, A Hands – on Project Based Introduction to Programming”, 2nd
Edition, No Starch Press, 2019.
https://www.python.org/
Martin C. Brown, “Python: The Complete Reference”, 4th Edition, Mc-Graw Hill, 2018.
UNIT I
ALGORITHMIC PROBLEM SOLVING
Computing
Computing is the process of using computer technology to complete a given goal-oriented
task. Computing encompasses the design and development of software and hardware
systems for a wide range of task namely structuring, processing and managing any kind of
information.
Computational Thinking
Computational thinking is the process of identifying a clear step-by-step solution to a
complex problem. It begins with breaking down a problem into smaller pieces, recognizing
patterns and eliminating extraneous, then creating a step-by-step solution can be replicated.
It includes
Identify the problem to be solved.
Understand the problem.
Develop possible and feasible solutions.
Present the solutions in a way that a computer, a human, or both, can understand.
Statements
State
Control flow
Functions
Statement:
Statement is a unit of code that instructs a computer to perform an action.
Statements may be an input statement or process statement or output statement.
Input statements carry the data to solve the problem.
Process statement perform operation on a given input
Output statement gives the processed result.
Further statements may be categorized into three types: expression statements, declaration
statements, and control flow statements
State:
State is the current condition of a program or part of a program. Transition from one
process to another process under specified condition with in a time is called state.
Control flow:
The process of executing the individual statements in a given order is called control flow.
The control can be executed in three ways
sequence
selection
iteration
Sequence
Sequence of actions that a program carries out one after another, unconditionally.
Selection
Control flow statements are able to make decisions based on the conditions.
Selection is the program construct that allows a program to choose between different
actions. Choose at most one action from several alternative conditions.
Entry
Action 1 Action 2
Repetition
Repetition means, repeating an action or set of statements until certain condition is attained.
Repetition will reduce the number lines of code in a program. It is helpful in cases where a
set of codes need to be executed multiple times.
Repetition statements may be of two forms
For
While
While Statement:
"While" Loop is used to repeat a specific block of code an unknown number of times, until
a condition is met.
The general form is:
while ( condition is true )
execute statements
end
For statement:
“For” loop is used for iterating a specific number of times, often called a “counting”
loop. Two keywords, FOR and ENDFOR are used.
The general form is:
FOR (iteration conditions)
Sequence
END
Example for Repetition : calculate factorial no:
Step1: Start
Step 2: Read the number to compute factorial.
Step 3: Initialize i is equal to 1 and fact is equal to 1
Step 4: Repeat step 4.1 through step 4.2 until „i' is equal
to num
Functions:
Functions are "self contained" modules of code that carry out a specific task. The problem
solving mechanism behind functions is to break larger problem into smaller manageable
pieces and solve the problem.
Uses of function
enable the code reusability
reducing code redundancy
enhance code readability
easy understanding and maintainability of the code
testing and debugging much easier
Generally a function has function name, function body, return value and l i s t o f
parameter
function_name( parameters )
body of the function
return [value/expression]
Recursion
Recursion is a function calling itself until a specified a specified condition is met.
Example for recursion function(factorial using recursion)
Step 1 : Start
Step 2 : Read the number to compute factorial.
Factorial(n)
Step 1 : fact is equal to 1
Step 2: IF n==1 then
return 1
ELSE
f=n*factorial(n-1)
Step 3 : print f
ALGORITHM NOTATIONS (EXPRESSING ALGORITHMS)
Algorithms can be expressed in many kinds of notation, including
Pseudocode
Pseudocode is a way to describe an algorithm or computer program in a readable, natural
language. Pseudocode is a blueprint for translating the logic of a program into a
programming language. It's not compiled or executed on computers, but is meant to be read
and understood by humans.
Guidelines for writing pseudo code
Write one statement per line
Indent to hierarchy
Keep statements language independent
Common keywords used in pseudo code
The following gives common keywords used in pseudo codes.
BEGIN,END: Represents beginning and end of code.
INPUT, GET, READ: to feed data.
COMPUTE, CALCULATE: to compute the given expression.
ADD, SUBTRACT, INITIALIZE to perform addition, subtraction and initialization.
OUTPUT, PRINT, DISPLAY: to display the output of the program.
IF, ELSE, ENDIF: decision making statements.
WHILE, ENDWHILE & FOR, ENDFOR: iterative statement.
Advantages:
Pseudo is independent of any language; it can be used by most programmers.
It is easy to translate pseudo code into a programming language.
Disadvantages:
It does not provide visual representation of the program‟s logic.
There are no accepted standards for writing pseudo codes.
It cannot be compiled nor executed.
For a beginner, It is more difficult to follow the logic or write pseudo code as
compared to flowchart.
Flowchart
A flowchart is a pictorial or visual representation of the sequence of steps to solve a problem.
Flow chart is defined as graphical representation of the logic for problem solving.
Flowchart symbols
Symbol Name Function
Process Indicates any type of internal
operation inside the Processor or
Memory
Input / Output Used for any Input / Output (I/O)
operation. Indicates that the
computer is to obtain data or
output results
Decision Used to ask a question that can be
answered in a binary format (Yes/
No, True/False)
Connector Allows the flowchart to be drawn
without intersecting lines or
without a reverse flow
Predefined Process Used to invoke a subroutine or an
Interrupt program
Terminal Indicates the starting or ending of the
program, process, or interrupt
program
Flow Lines Shows direction of flow
Rules for drawing a flowchart
The flowchart must have a logical start and finish.
Only one flow line should come out from a process symbol.
Only one flow line should enter a decision symbol. However, two or three flow
lines may leave the decision symbol.
NO
YES
Start
Read A, B
Yes No
Is A > B
Print B
Print A
End
start
Read
A, B, C
No Is Yes
A>B
Yes Is No No Is Yes
B>C A>C
stop
Roots of a quadratic equation ax2+bx+c=0
Start
Calculate discriminant
D b - 4ac
True is False
D > 0?
x1 rp + j ip
x1 rp - j ip
Display r1 and r2
Stop
Flowchart to find factorial of given no
START
Fact 1, Num 0
Read Num
No
IS Num
> 1? Print Fact
Yes Stop
Num Num-1
Programming Language
Programming:
Programming is the process of taking an algorithm and encoding it into a notation, a
programming language, so that it can be executed by a computer.
Programming language:
A programming language is a computer language that is used by programmers (developers)
to communicate with computers. It is a set of instructions written in any specific language (
C, C++, Java, Python) to perform a specific task.
Computer Languages
Design an algorithm
Prove correctness
Analyze the algorithm
Code the algorithm
Understanding the Problem
The first step in algorithmic problem-solving is to understand the problem statement. This is
important because a clear understanding of the problem will guide the rest of the process and
helps in the design an effective solution. It also defines the requirement, constrains, inputs
and outputs of the problem. Inputs are the data or information that the algorithm will use to
solve the problem. Outputs are the results or solutions that the algorithm will produce. A
clear understanding of the problem statement will avoid misunderstandings and ensures that
the solution addresses the objective.
Decide on: computational means, exact vs. approximate solving, algorithm design
technique
Computational means addresses how the problem can be solved by means of using a
computer.
The next vital decision is to decide whether we prefer an exact or approximate solution to
the problem.
The third decision is the selection of algorithm design technique.
Design an Algorithm
Design Approaches : There are two approaches for designing an algorithm.
Top-Down Approach
Bottom-up approach
Top-Down Approach: In the top-down approach, a large problem is divided into small
sub-problem.
Bottom-up approach: Complex program is solved using a programming language and
then this is combined into a complete program.
Common Algorithmic Strategies are Greedy Method, Divide and Conquer, Dynamic
Programming, Linear Programming, Reduction, Backtracking, Branch and Bound
Understand the problem
Decide on:
computational means,
exact vs. approximate solving,
algorithm design technique
Design an algorithm
Prove correctness
Iterations
Recursions
Iterations:
A set of instructions or structures are repeated in a sequence, a specified number of times
or until a condition is met. Iteration is implemented in programming
using FOR and WHILE statements. It avoids code redundancy.
\
Programmer use a count-controlled iteration if they are aware of the number of times of
execution of the block of code. „For‟ loop is count-controlled iteration statement.
Programmer use Conditional iterations when they don't know how many iterations they
need to achieve their desired results. In such case they use a while loop .
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 been satisfied.
Main function:
BEGIN
GET n
CALL factorial(n)
PRINT fact
BIN
Sub function factorial(n):
IF(n==1) THEN
fact=1
RETURN fact
ELSE
RETURN fact=n*factorial(n-1)
Interactive Mode
Portable and Extendable
Databases and GUI Programming
Scalable and Dynamic Semantics
.pyc Module
import
Two Parts
Python byte code compiler
The byte code compiler accepts human readable python expressions and statements
as input and produces machine readable python code as output.
A virtual Machine which executes python byte code.
The virtual machine accepts Python byte code as input. And executes the virtual machine
instructions represented by the byte code.
PYTHON MODES
Interactive mode
Interactive mode is a command line terminal without any additional options, a Python
prompt >>> appears and the Python interpreter works on the principle of REPL (Read,
Evaluate, Print, Loop). In interactive mode, interpreter displays the result(s) immediately.
That means, when we type Python expression / statement / command after the prompt
(>>>), the Python immediately responses with the output of it.
For Example:
>>> 5+10
15
>>> x=5
>>>y=6
>>> print x+y
11
Script Mode
For coding of more than few lines, we should always save the code with .py extension, so
that it can be modified and reused. Script mode is a way to run Python code by writing it in
a file and then executing it using the Python interpreter.
VALUES AND DATA TYPES
Identifier
Identifier is the name given to entities like class, functions, variables etc. in Python. It
helps differentiating one entity from another.
Rules for variable or identifier names
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 (_).
Data Type
Data Types
Python Numbers
Number data types are used to store numeric values. Number objects are created when a
value is assigned to a variable.
Python supports four different numerical types
int (signed integers)
long (long integers, can also be represented in octal and hexadecimal)
Ex: 56789436L (long), 0o123 (Octal), 0x123 (Hexa)
float (floating point real values)
Ex: –37.9, 37.3+e15, –32.74e100, 70.2–E15
complex (complex numbers)
Ex: z = 5+3j
print(z.real)5
print(z.imag) 3
Boolean
A Boolean value is a data type that can hold two values namely true or false. In Python
Boolean data type is represented by the keyword bool.
String
String data type stores of a series or sequence of characters - letters, numbers, and special
characters. Strings are marked by single quotes („ „) , double quotes (“ “) or triple
quotes(“”” “””). Multiline string can be assigned by using three quotes. It is an immutable
data type
Lists
Lists are used to store multiple items in a single variable. List items are ordered, indexed,
mutable (changeable), and allow duplicate values. List is enclosed in square brackets [ ].
Tuple:
A tuple is a built-in data structure that stores a collection of elements in a defined order that
cannot be changed ( immutable). Tuple items are ordered, indexed, immutable
(unchangeable) , and allow duplicate values. Tuples elements are written within parenthesis
( ).
Set
Sets are used to store multiple items in a single variable. A set is a collection which
is unordered, unique (elements cannot be duplicate) and unindexed. Sets are written with
curly braces{}, separated by commas.
Dictionary
A Python dictionary is a collection of items, each item in a dictionary is a key-value pair. A
dictionary can be created by placing key:value pairs inside curly brackets {}, separated by
commas.
Variable
A variable in Python is a named memory location that stores data values. Python doesn't
require a command to declare a variable. A variable is created when you first assign a value
to it.
Variable Names
Variable name can contain alpha-numeric characters and underscores (A-z, 0-9, and
_)
Keywords
Keyword is a reserved word with a specific meaning and function, and they cannot be used
as variable names.
Expressions And Statements
Expressions
An expression a combination of operands, constant and operators that produces a value
when executed.
Statements
A statement is a single line of code that performs a specific task.
Operators
An operator is a symbol that represents a specific mathematical or logical action or process
performed on operands.
Types of Operators:
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:
Arithmetic operators are used to perform basic arithmetic operations like addition,
subtraction, multiplication etc.
Arithmetic operators in Python
Assignment Operators
Assigns the value of the right-hand operand to the left-hand operand. The basic assignment
operator is „=‟.
Identity Operator
Compare two objects to determine whether they share the same memory and refer to the
same object type. Identity operators are „is‟ and „is not‟.
is:
If two objects have the same identity, it returns True. Otherwise, it returns False. is not:
The 'is not' operator returns True if both the objects do not share the same memory
location and returns true if both are not identical.
Precedence of Operators
Operator precedence determines the order in which operations are performed in an
expression. When more than one operator appears in an expression, the order of
evaluation depends on the rules of precedence.
Operator Description
() Parentheses
** Exponentiation
+x -x ~x Unary plus, unary
minus, and bitwise
NOT
* / // % Multiplication,
division, floor
division, and modulus
+ - Addition and
subtraction
<< >> Bitwise left and right
shifts
& Bitwise AND
^ Bitwise XOR
| Bitwise OR
== != > >= < <= is is- Comparisons,
not in not-in identity, and
membership operators
not Logical NOT
and AND
or OR
Comments
Comments are hints that we add to our code to make it easier to understand. It is intended
only for the human reader. Comments are ignored by the interpreter during the execution of
the program.
There are two types of comments in Python:
Single line Comments
Multiline Comments
Single Line Comments: Single-line comment starts with the hashtag symbol (#) and
useful for supplying short explanations.
Multiple Line Comments
Python does not provide the facility for multi-line comments. We can use these string
literals as Python Comments.
„ Python multiline comments‟
""" Python multiline comments"""