Python Notes
Python Notes
PROGRAMMING
Algorithmic Problem Solving 1.1
Unit I
ALGORITHMICPROBLEM SOLVING
Algorithms, building blocks of algorithms (statements, state, control
flow, functions), notation (pseudo code, flow chart, programming
language), algorithmic problem solving, simple strategies for
developing algorithms (iteration, recursion). Illustrative problems:
find minimum in a list, insert a card in a list of sorted cards, guess an
integer number in a range, Towers of Hanoi.
1.1 ALGORITHMS
What is algorithm?
An algorithm is a finite number of clearly described, unambiguous ―”doable”
steps that can be systematically followed to produce a desired result for given input in
a finite amount of time . Algorithms are the initial stage of problem solving. Algorithms
can be simply stated as a sequence of actions or computation methods to be done for
solving a particular problem. An algorithm should eventually terminate and used to
solve general problems and not specific problems.
Al-Khwarizmi
Lets discuss about the conversation,tom wants brush his teeth, so he asks chitti
to bring brush,what happens chitti returns cleaning brush.
Why this was happened ?
Because the statement given by tom was not well defined and it is ambiguous
statement so chitti get confused and bring some brush to [Link] is what happen if
the user gives ambiguity statement to the [Link] an algorithm should be
simple and well defined.
How an algorithm should be?
It should be in simple English, what a programmer wants to say. It has a start, a
middle and an end. Probably an algorithm should have,
Start
1. In the middle it should have set of tasks that computer wants to do and
it should be in simple English and clear.
2. To avoid ambiguous should give no for each step.
Stop
Start
Create a variable to get the user’s email address clear the variable, incase
its not empty.
Ask the user for an email address.
Store the response in the variable.
Check the stored response to see if it is a valid email address Not valid?
Go back
Stop
Step1: Start
Step2: Create a variable to get the user’s email address
Step3: Clear the variable, incase its not empty.
Step4: Ask the user for an email address.
Step5: Store the response in the variable.
Step6: Check the stored response to see if it is a valid email address
Step7: Not valid? Go back
Step8: Stop
Step1: Start
Step 2: Get two numbers as input and store it in to a and b
Step 3: Set c = a+b
Step 4: Print c
Step 5: Stop.
Algorithmic Problem Solving 1.7
Action 1 Action 2
Repetition
While Statement:
The WHILE construct is used to specify a loop with a test at the top. The beginning
and ending of the loop are indicated by two keywords WHILE and ENDWHILE.
The general form is:
WHILE condition
Sequence
END WHILE
FOR loop:
This loop is a specialized construct 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 bounds
Sequence
END FOR
Repetition (loop) may be defined as a smaller program the can be executed several
times in a main program. Repeat a block of statements while a condition is true.
Example 1.10 Algorithm for Washing Dishes
Step1: Stack dishes by sink.
Step 2: Fill sink with hot soapy water.
Step 3: While moreDishes
1.12 Problem Solving and Python Programming
Step 4: Get dish from counter,Wash dish
Step 5: Put dish in drain rack.
Step 6: End While
Step 7: Wipe off counter.
Step 8: Rinse out sink.
Example 1.11 Algorithm to calculate factorial no:
Step1: Start
Step 2: Read the number num.
Step 3: Initialize i is equal to 1 and fact is equal to 1
Step 4: Repeat step4 through 6 until I is equal to num
Step 5: fact = fact * i
Step 6: i = i+1
Step 7: Print fact
Step 8: Stop
Example 1.12 Algorithm to find the factorial of a number
Step 1. Read the value of n.
Step 2. i = 1 , F =1
Step 3. if ( i > n ) go to 7
Step 4. F = F * i
Step 5. i = i + 1
Step 6. go to 3
Step 7. Display the value of S
Step 8. Stop
Example 1.13 Algorithm to print numbers from 1 to 10
Step 1: Set i=1, n=10
Step 2: Repeat steps 3 and 4 while i<=n
Step 3: Print i
Step 4: Set i=i+1
[End of loop]
Step 5: End
Algorithmic Problem Solving 1.13
Recursion
Recursion is a technique of solving a problem by breaking it down into smaller
and smaller sub problems until you get to a small enough problem that it can be easily
solved. Usually, recursion involves a function calling itself until a specified a specified
condition is met.
Example 1.14 Algorithm for factorial using recursion
Step 1 : Start
Step 2 : Input number as n
Step 3 : Call factorial(n)
Step 4 : End
Factorial(n)
Step 1 : Set f=1
Step 2: IF n==1 then return 1
ELSE
Set f=n*factorial(n-1)
Step 3 : print f
Algorithm
Output List
Pseudocode
Flowchart
Programming
Language
1.3.1 Pseudocode
Pseudo code consists of short, readable and formally styled English languages
used for explain an algorithm.
It does not include details like variable declaration, subroutines.
It is easier to understand for the programmer or non programmer to
understand the general working of the program, because it is not based on
any programming language.
It gives us the sketch of the program before actual coding.
It is not a machine readable
Pseudo code can’t be compiled and executed.
Algorithmic Problem Solving 1.15
Selection Logic
It is used for making decisions and for selecting the proper path out of two
or more alternative paths in program logic.
It is also known as decision logic.
Selection logic is depicted as either an IF..THEN or an IF…THEN..ELSE
Structure.
Example 1.16 Pseudocode to Find Biggest of two numbers:
START
READ a and b
IF a>b THEN
PRINT “A is big”
ELSE
PRINT “B is big”
ENDIF
STOP
1.18 Problem Solving and Python Programming
Repetition Logic
It is used to produce loops when one or more instructions may be executed
several times depending on some conditions.
It uses structures called DO_WHILE,FOR and REPEAT__UNTIL
Example 1.17 Pseudocode to print first 10 natural numbers
START
INITIALIZE a?0
WHILE a<10
PRINT a
ENDWHILE
STOP
Suggested Link to refer :
[Link]
1.3.2 Flowchart
A flowchart is a visual representation of the sequence of steps and decision needed
to perform a process.
Flow chart is defined as graphical representation of the logic for problem solving.
The purpose of flowchart is making the logic of the program clear in a visual
representation.
Flowchart symbols
Here are some of the common flowchart symbols.
Name Symbol Use in flowchart
4. Only one flow line should enter a decision symbol. However, two or three flow
lines may leave the decision symbol.
NO
YES
Below is an example set of instructions to add two numbers and display the
answer.
total = firstNumber +
secondNumber
Selection Logic
Selection is used in a computer program or algorithm to determine which
particular step or set of steps is to be executed. This is also referred to as a ‘decision’.
A selection statement can be used to choose a specific path dependent on a
condition.
There are two types of selection:
binary selection (two possible pathways)
multi-way selection (many possible pathways)
Following is the example flowchart to find biggest among two numbers
Start
Read A, B
Yes No
Is A > B
Print B
Print A
End
1.22 Problem Solving and Python Programming
Example 1.18 Flow chart for biggest of three numbers
start
Read
A, B, C
No Is Yes
A>B
Yes Is No No Is Yes
B>C A> C
stop
Start
Read N
Sum = sum + n
No
is N = 0? N=N-1
Yes
Display Sum
End
Algorithmic Problem Solving 1.23
Start
Calculate discriminant
D b - 4ac
True is False
D > 0?
x1 rp + j ip
x1 rp - j ip
Display r1 and r2
Stop
Repetition Logic
Repetition allows for a portion of an algorithm or computer program to be
executed any number of times dependent on some condition being met.
An occurrence of repetition is usually known as a loop.
The termination condition can be checked or tested at the beginning or end of
the loop, and is known as a pre-test or post-test, respectively.
Iteration & Recursion
Iteration and recursion are key Computer Science techniques used in creating
algorithms and developing software.
1.24 Problem Solving and Python Programming
In simple terms, an iterative function is one that loops to repeat some part of the
code, and a recursive function is one that calls itself again to repeat the code.
Example 1.21 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
Process
False
Condition
True
Condition
False
Process
True
Algorithmic Problem Solving 1.25
Computer Languages
Decide on:
computational means,
exact vs. approximate solving,
algorithm design technique
Design an algorithm
Prove correctness
Data structure plays a vital role in designing and analysis the algorithms.
First, they provide guidance for designing algorithms for new problems,
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.
1.30 Problem Solving and Python Programming
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.
4. Analysing 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.
5. Coding an Algorithm
Most algorithms are destined to be ultimately implemented as computer
programs. Programming an algorit hm 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 analysing the results obtained.
1. for loop
2. While loop
Syntax for For: Example: Print n natural numbers
FOR (start-value to end-value)DO BEGIN
statement GET n
.... INITIALIZE i=1
ENDFOR FOR (i<=n) DO
PRINT i
i=i+1
ENDFOR
END
Syntax for While: Example: Print n natural numbers
WHILE (condition) DO BEGIN
GET n
statement
INITIALIZE i=1
... WHILE (i<=n) DO
ENDWHILE PRINT i
i=i+1
ENDWHILE
END
Start
get n
i=1
no yes
is
i <= n
stop print i
i=i+1
1.32 Problem Solving and Python Programming
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.
Example 1.22 Algorithm for factorial of n numbers using recursion:
Main function:
Step1: Start
Step2: Get n
Step3: call factorial(n)
Step4: print fact
Step5: Stop
Sub function factorial(n):
Step1: if(n==1) then fact=1 return fact
Step2: else fact=n*factorial(n-1) and return fact
Start factorial(n)
Get n
Yes
if(n = 1)
fact = 1
call factorial(n)
No
Stop
Algorithmic Problem Solving 1.33
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)
The sorting recursively been done until the cards are fully sorted. The final sorted
cards are
Algorithm:
1. Start
2. Ask for value to insert
3. Find the correct position to insert, If position cannot be found ,then
insert at the end.
4. Move each element from the backup to one position, until you get
position to insert.
5. Insert a value into the required position
6. Increase array counter
7. Stop
The following table shows the sample scenario of the range 1-10 that asks a
series of questions, reducing the problem size by about half each time.
Number First guess Second guess Third guess
1 Is it 6? Is it 3? Is it 1?
Too high Too high You win
2 Is it 5? Is it 2?
Too high You win
3 Is it 5? Is it 2? Is it 3?
Too high Too high You win
4 Is it 5? Is it 2? Is it 3?
Too high Too low Too low, so it must be 4.
5 Is it 5?
You Win
6 Is it 5? Is it 8? Is it 6?
Too Too High You Win
7 Is it 5? Is it 8? Is it 6?
Too low Too low Too low, so it must be 7
8 Is it 5? Is it 8?
Too low You win
Algorithmic Problem Solving 1.39
9 Is it 5? Is it 8? Is it 9?
Too low Too low You win
10 Is it 5? Is it 8? Is it 9?
Too low Too low Too low, so it must be 10
A B C
In this example we are
considering 3 disks.
They are placed in
decreasing size
from bottom to top
Problem Analysis:
We will first attempt to solve this problem for three disks to gain some insight
into the problem, and then develop a general solution for any number of disks. Thus,
we will solve the simple problem of moving three disks from peg A to peg C as shown
in Figure
1.40 Problem Solving and Python Programming
1
2
3
A B C
3 2 1
A B C
After Move 1 and Move 2
Move 3:
We can place the disk currently on peg B back on peg A, but that will be undoing
what we just did in the last step. So in order to make progress, we move the smallest
disk on peg C somewhere.
We can move it on either peg A or peg B, since in each case it would be placed
on a larger disk. Let’s assume that we move the smallest disk currently on peg C on
top of the second smallest disk on peg B. This move results are shown in the figure.
1
3 2
A B C
After Move 3
Algorithmic Problem Solving 1.41
Move 4:
We can move the largest disk currently on peg A to peg C.
Then we can move the smallest disk from peg B to peg A, then move the second
smallest disk from peg B to peg C, and finally move the smallest disk from peg A to
peg C, thereby solving the problem.
4
1
2 3 2
3
A 1 B C
After Move 4
Step 1: View the stack as two stacks, one on top of the other. Call the top
stack Stack1, and the bottom stack Stack2.
Step 2: Recursively move Stack1 from peg A to peg B.
Step 3: Recursively move (the exposed) Stack2 from peg A to peg C.
Step 4: Recursively move Stack1 from peg B to peg C.
Repeat moving a stack of disks from one peg to another. It does not matter that
the stacks being moved are different, or are being moved between different pegs. Each
of the sub problems can be recursively solved in a similar way, and thus we can assume
that they can be solved without explicitly specifying how. How to break down a stack
of disks into two separate (sub) stacks?
1. Start
2. Move disk1 from pegA to pegC
3. Move disk2 from pegA to pegB
4. Move disk3 from pegC to pegB
1.42 Problem Solving and Python Programming
5. Move disk1 from pegA to pegC
6. Move disk1 from pegB to pegA
7. Move disk2 from pegB to pegC
8. Move disk1 from pegA to peg C
Stop
Suggested Link to Refer :
Reference Link 1: [Link]
Link 2 : [Link]
Assignments :
Try the following with Algorithm, flowchart and pseudo code.
1. Find the area of triangle
2. Area and circumference of a circle
3. Calculating simple interest
4. Calculating engineering cutoff
5. Greatest of two numbers
6. Greatest of three numbers
7. Check leap year or not
8. Check the number is odd or even
9. Check the number is positive or negative
10. Print all the prime numbers upto N
11. Print square and cube of a number
12. Print sum of N numbers
13. Find the factorial of a number
14. Convert Temperature from Fahrenheit (°F) to Celsius (°C)
Algorithmic Problem Solving 1.43
PART – B QUESTIONS
1. Explain in detail about the Algorithmic problem solving
2. Detail on the building blocks of algorithm
3. Analyze the following problems:
a. Find minimum in a list
b. Insert a card in a list of sorted cards
c. Guess a number in a range
4. Discuss about Tower of Hanoi Problem
5. Write an algorithm, pseudo code and flowchart for finding the minimum number
in a list.
6. Write an algorithm, pseudo code and flow chart to find the factorial of a given
number.
7. Write an algorithm, pseudo code and flow chart for Fibonacci series.
8. Write an algorithm, pseudo code and flow chart to find whether a number is
prime or not.
Data, Expressions, Statements 2.1
Unit II
2.1 INTRODUCTION
What is a program?
A computer program is a collection of instructions that perform a speciûc task
when executed by a computer.” - Process of writing a program is called programming.
Computer programs are written to solve speciûc problems.
What is logic?
Steps involved in solving a problem is known as [Link] can be multiple
logic to solve the same problem. Algorithm is a widely used form of representing
Logic.
No. of teachers available= Total no. of teachers– No. of teachers busy in other
classes in 4th lecture – No. of teachers on leaveTop of Form.
Python programming language
Python is an example of a high level language; other high-level languages
you might have heard of are C++, PHP, Pascal, C#, and Java.
There are also low-level languages, sometimes referred to as machine
languages or assembly languages.
Computers can only execute programs written in low-level languages.
Thus programs written in the high level language have to be translated into
something more suitable before they can run.
2.2 Problem Solving and Python Programming
It is easier to program high level languages.
These high level languages are executed in different computers.
Python features
Python is a High Level, Interpreted, Interactive and Object Oriented Programming
Language
Beginners Language
Extensive Standard Library
Cross Platform Compatibility
Interactive Mode
Portable and Extendable
Databases and GUI Programming
Scalable and Dynamic Semantics
Automatic Garbage Collection
High level languages – Only humans can understand
Interpreter / Compiler – Translate the high level language to machine language
and vice ersa Low level language – Only machine can understand (0s and 1s)
The engine that translates and runs Python is called the Python Interpreter:
There are two ways to use it:
1. Immediate mode or interactive mode and
2. Script mode.
Python interpreter and interactive mode
An interpreter is a computer program which executes other programs. Python
interpreter carries out instructions in your program. This interpreter can be used
interactively to test out instructions on the fly.
Python interpreters
Python interpreters are available for many operating systems, allowing Python
code to run on a wide variety of systems.
Data, Expressions, Statements 2.3
.pyc Module
import
Two Parts
1. 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.
2. 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.
2. Script Mode
In script mode, we type Python program in a file and then use interpreter to
execute the content of the file. Working in interactive mode is convenient for beginners
and for testing small pieces of code, as one can test them immediately.
But for coding of more than few lines, we should always save our code so that it
can be modified and reused.
Python, in interactive mode, is good enough to learn, experiment or explore, but
its only drawback is that we cannot save the statements and have to retype all the
statements once again to re-run them.
Example: Input any two numbers and to find Quotient and Remainder.
Code:
a = input (“Enter first number”)
b = input (“Enter second number”)
print “Quotient”, a/b
print “Remainder”, a%b
Enter first number10
Enter second number3
Quotient 3
2.3.1 VALUES
A value is one of the basic things a program. There are different values integers, float
and strings. The numbers with a decimal point belong to a type called float. The values
written in quotes will be considered as string, even it’s an integer. If type of value is
not known it can be interpreted as
Example:
>>> type(‘Hello, World!’)
<type ‘str’>
>>> type(17)
<type ‘int’>
2.6 Problem Solving and Python Programming
>>> type(‘17’)
<type ‘str’>
>>> type(‘3.2’)
<type ‘str’>
Every object has:
An Identity,
A type, and
A value.
2.3.2 Identifier
Identifier is the name given to entities like class, functions, variables etc. in
Python. It helps differentiating one entity from another.
Rules
1. 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 (_). Names like myClass, var_1
and print_this_to_screen, all are valid example.
2. An identifier cannot start with a digit.
3. Keywords cannot be used as identifiers.
4. We cannot use special symbols like !, @, #, $, % etc. in our identifier.
5. Identifier can be of any length.
Data Types
Dictionary
Integer Floating Complex Strings Tuple List
Point
Boolean
Data, Expressions, Statements 2.7
It is a set of values, and the allowable operations on those values. It can be one
of the following:
Python allows you to use a lowercase l with long, but it is recommended that
you use only an uppercase L to avoid confusion with the number 1. Python displays
long integers with an uppercase L.
A complex number consists of an ordered pair of real floating-point numbers
denoted by x + yj, where x and y are the real numbers and j is the imaginary unit.
The built in numeric types supports the following operations:
x+y sum of x and y
x–y difference of x and y
x*y product of x and y
x/y quotent of x and y
x//y (floored) quotient of x and y
x%y remainder of x/y
–x x negated
+ x unchanged
abs(x) absolute value of magnitude of x
int(x) x converted to integer
long(x) x converted to long integer
Data, Expressions, Statements 2.9
[Link] Boolean
A Boolean value is either true or false. It is named after the British mathematician,
George Boole, who first formulated Boolean algebra.
In Python, the two Boolean values are True and False (the capitalization must be
exactly as shown), and the Python type is bool.
>>> type(True)
<class ‘bool‘>
>>> type(true)
Traceback (most recent call last):
File “<interactive input>”, line 1, in <module>
NameError: name ‘true‘ is not defined
Example:
>>> 5 == (3 + 2) # Is five equal 5 to the result of 3 + 2?
True
>>> 5 == 6
False
>>> j = “hel”
>>> j + “lo” == “hello”
True
2.10 Problem Solving and Python Programming
2.3.4 String
A String in Python consists of a series or sequence of characters - letters, numbers,
and special characters.
Strings are marked by quotes:
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.”””
Individual character in a string is accessed using a subscript (index).
Characters can be accessed using indexing and slicing operations
Example
str = ‘Hello World!’
print str # Prints complete string
print str[0] # Prints first character of the string
print str[2:5] # Prints characters starting from 3rd to 5th
print str[2:] # Prints string starting from 3rd character
print str * 2 # Prints string two times
print str + “TEST” # Prints concatenated string
Output
Hello World!
H
lo
llo World!
Hello World!Hello World!
Hello World!TEST
Data, Expressions, Statements 2.11
Strings in Python can be enclosed in either single quotes (‘) or double quotes
(“), or three of each ( ‘ or “””)
>>>type(‘This is a string.‘) <class ‘str‘>
>>> type(“And so is this.”)
<class ‘str‘>
>>>type(“””and this.”””)
<class ‘str‘>
>>>type(‘‘‘and even this...‘‘‘)
<class ‘str‘>
Double quoted strings can contain single quotes inside them.
(“Alice‘s Cup”)
Single quoted strings can contain double quotes inside them
(‘Alice said ,”Hello”’)
Strings enclosed with three occurrences of either quote symbol are called triple
quoted strings. They can contain either single or double quotes:
>>>print(‘‘‘“Oh no”, she exclaimed, “Ben‘s bike is broken!”‘‘‘) “Oh no”,
she exclaimed, “Ben‘s bike is broken!”
>>>Triple quoted strings can even span multiple lines:
>>>message = “””This message will
... span several
... lines.”””
>>>print(message)
This message will span several lines.
2.3.5 Lists
List is also a sequence of values of any type. Values in the list are called elements
/items. These are mutable and indexed/ordered. List is enclosed in square
brackets ([]).
2.12 Problem Solving and Python Programming
Example
list = [ ‘abcd’, 786 , 2.23, ‘john’, 70.2 ]
tinylist = [123, ‘john’]
print list # Prints complete list
print list[0] # Prints first element of the list
print list[1:3] # Prints elements starting from 2nd till 3rd
print list[2:] # Prints elements starting from 3rd element
print tinylist * 2 # Prints list two times
print list + tinylist # Prints concatenated lists
Output
[‘abcd’, 786, 2.23, ‘john’, 70.200000000000003]
abcd
[786, 2.23]
[2.23, ‘john’, 70.200000000000003]
[123, ‘john’, 123, ‘john’]
[‘abcd’, 786, 2.23, ‘john’, 70.200000000000003, 123, ‘john’]
2.3.6 Variable
One of the most powerful features of a programming language is the ability to
manipulate variables. A variable is a name that refers to a value.
The assignment statement creates new variables and gives them values:
>>> message = “What’s up, Doc?”
>>> n = 17
>>> pi = 3.14159
This example makes three assignments. The first assigns the string “What’s up,
Doc?” to a new variable named message. The second gives the integer 17 to n, and the
third gives the floating-point number 3.14159 to pi.
The print statement also works with variables.
Data, Expressions, Statements 2.13
2.3.7 Keywords
Keywords define the language‘s rules and structure, and they cannot be used as
variable names. Python has thirty-one keywords:
2.14 Problem Solving and Python Programming
Output:
Area is 10
Perimeter is 14
Data, Expressions, Statements 2.15
Statements
A statement is an instruction that the Python interpreter can execute. We have
seen two kinds of statements: print and assignment. When you type a statement on the
command line, Python executes it and displays the result, if there is one. The result of
a print statement is a value. Assignment statements don‘t produce a result. A script
usually contains a sequence of statements. If there is more than one statement, the
results appear one at a time as the statements execute.
Example
print 1
x=2
print x
It produces the following output
1
2
‘Bob‘
>>>age
19
>>>studies
‘CS’
Swapping in tuple assignment:
(a, b) = (b, a)
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.
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)
Value Error: need more than 3 values to unpack
2.3.11 Operators
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
Data, Expressions, Statements 2.19
Arithmetic operators:
Arithmetic operators are used to perform mathematical operations like addition,
subtraction, multiplication etc.
Arithmetic operators in Python
Operator Meaning Example
+ Add two operands or unary plus x+y
– Subtract right operand from the left or
unary minus x-y
* Multiply two operands x*y
/ Divide left operand by the right one (always
results into float) x/y
% Modulus - remainder of the division of left
operand by the right x%y
// x//y
** Exponent - left operand raised to the power
of right x**y(x to the power y)
Examples
a=10
b=5
print(“a+b=”,a+b)
print(“a-b=”,a-b)
print(“a*b=”,a*b)
print(“a/b=”,a/b)
print(“a%b=”,a%b)
print(“a//b=”,a//b)
print(“a**b=”,a**b)
2.20 Problem Solving and Python Programming
Output
a+b= 15
a-b= 5
a*b= 50
a/b= 2.0
a%b= 0
a//b= 2
a**b= 100000
Example
a=10
b=5
print(“a>b=>”,a>b)
print(“a>b=>”,a<b)
print(“a==b=>”,a==b)
print(“a!=b=>”,a!=b)
print(“a>=b=>”,a<=b)
print(“a>=b=>”,a>=b)
Output:
a>b=> True
a>b=> False
a==b=> False
a!=b=> True
a>=b=> False
a>=b=> True
Assignment Operators
Assignment Operator combines the effect of arithmetic and assignment operator
Operator Name Example Equivalent
+= Addition assignment 1+=8 i=i+8
–= Subtraction assignment i –=8 i=i–8
*= Multiplication assignment 1*=8 1=1*8
/= Float division assignment i/=8 i=i/8
//= Integer division assignment i //=8 i = i // 8
%= Remainder assignment i %=8 i \ i %8
**= Exponent assignment i **=8 i = i ** 8
2.22 Problem Solving and Python Programming
Example
a = 21
b = 10
c=0
c=a+b
print(“Line 1 - Value of c is “, c)
c += a
print(“Line 2 - Value of c is “, c)
c *= a
print(“Line 3 - Value of c is “, c)
c /= a
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)
Output
Line 1 - Value of c is 31
Line 2 - Value of c is 52
Line 3 - Value of c is 1092
Line 4 - Value of c is 52.0
Line 5 - Value of c is 2
Line 6 - Value of c is 2097152
Line 7 - Value of c is 99864
Data, Expressions, Statements 2.23
Logical Operators
Symbol Description
or If any one of the operand is true, then the condition becomes true.
and If both the operands are true, then the condition becomes true.
not Reverses the state of operand/condition.
Example
a = True
b = False
print(‘a and b is’,a and b)
print(‘a or b is’,a or b)
print(‘not a is’,not a)
Output
x and y is False
x or y is True
not x is False
Bitwise Operators:
A bitwise operation operates on one or more bit patterns at the level of individual
bits.
2.24 Problem Solving and Python Programming
Example:
a = 60 # 60 = 0011 1100
b = 13 # 13 = 0000 1101
c=0
c = a | b; # 61 = 0011 1101
print “Line 2 - Value of c is “, c
c = a ^ b; # 49 = 0011 0001
print “Line 3 - Value of c is “, c
Example:
a. in
This checks if a value is a member of a sequence. In our example, we see that the
string ‘fox’ does not belong to the list pets. But the string ‘cat’ belongs to it, so it
returns True. Also, the string ‘me’ is a substring to the string ‘disappointment’.
Therefore, it returns true.
>>> pets=[‘dog’,’cat’,’ferret’]
2.26 Problem Solving and Python Programming
>>> ‘fox’ in pets
False
>>> ‘cat’ in pets
True
>>> ‘me’ in ‘disappointment’
True
b. not in
Unlike ‘in’, ‘not in’ checks if a value is not a member of a sequence.
>>> ‘pot’ not in ‘disappointment’
True
Identity Operator
Let us proceed towards identity Python Operator.
These operators test if the two operands share an identity. We have two identity
operators- ‘is’ and ‘is not’.
a. is
If two operands have the same identity, it returns True. Otherwise, it returns
False. Here, 2 is not the same as 20, so it returns False. Also, ‘2’ and “2” are the same.
The difference in quotes does not make them different. So, it returns True.
>>> 2 is 20
False
>>> ‘2’ is “2”
True
b. is not
2 is a number, and ‘2’ is a string. So, it returns a True to that.
>>> 2 is not ‘2’
True
Data, Expressions, Statements 2.27
Comments
As programs get bigger and more complicated, they get more difficult to read. It
is a good idea to add notes to your programs to explain in natural language what the
program is doing.
A comment in a computer program is text that is intended only for the human
reader — it is completely ignored by the interpreter.
There are two types of comments in python:
Single line comments
Multi line comments
Single Line Comments
In Python, the # token starts a comment..
Example
print(“Not a comment”)
#print(“Am a comment”)
Result
Not a comment
Multiple Line Comments
Multiple line comments are slightly different. Simply use 3 single quotes before
and after the part you want commented.
Example
’’
print(“We are in a comment”)
print (“We are still in a comment”)
’’
print(“We are out of the comment”)
Result
We are out of the comment
2.28 Problem Solving and Python Programming
Suggested links to refer
What can you do with Python?
[Link] (Duration: 3:56).
Python Variables and Data Types
[Link] (Duration: 16:45)
[Link]
Food for Thought :What are the diûerent variables and data types used in the
video?
[Link]
OPERATORS
[Link]
Assignment Operators:
[Link] 7:06)
Arithmetic Operators:
[Link] 10:40)
Relational Operators:
[Link] 13:05)
Logical Operators
[Link] 8:54)
What can you do with Python?
[Link] (Duration: 3:56).
2.4.1 Modules
Python has a way to put related code in a ûle and use that ûle in other Python
ûles. It is called a module. It allows logical organization of code. It can be
used to deûne variables, functions and classes.
Grouping related code into module makes it easier to understand and use.
Data, Expressions, Statements 2.29
Module must be imported before using it’s functions in any other module/
python file.
import <<modulename>>
Example
1. Math functions:
This statement creates a module object named math. If you print the module
object, you get some information about it:
The module object contains the functions and variables defined in the module.
To access one of the functions, you have to specify the name of the module and
the name of the function, separated by a dot (also known as a period). This format is
called dot notation.
import math
Eg:
>>> [Link](2)
2.0 0.707106781187
2.30 Problem Solving and Python Programming
There are four ways to import a module in our program, they are
Import: It is simplest and most common from import: It is used to get a specific
way to use modules in our code function in the code instead of complete
file.
Example :
import math Example :
x = math pi from math import pi
print(“The value of pi is”, x) x = pi
Output: The value of pi is print(“The value of pi is”, x)
3.141592653589793 Output: The value of pi is
3.141592653589793
import with renaming: import all:
We can import a module by renaming the We can import all names(definitions)
module as our wish. gotm s mofulr udinh*
Example : Example :
import math as m from math import*
x = [Link] x = pi
print(“The value of pi is”, x) print(“The value of pi is”, x)
Output: The value of pi is Output: The value of pi is
3.141592653589793 3.141592653589793
2. Calendar functions :
Python has a cal module that provides calendar functions.
>>> import cal
Example:
import cal
x=[Link](5,4)
print(x)
3. Random functions :
Python offers random module that can generate random numbers.
These are pseudo-random number as the sequence of number generated depends
on the seed.
Data, Expressions, Statements 2.31
1. Randint
Example : Randint accepts two parameters: a lowest and a highest number.
import random
print( [Link](0, 5))
2. Random
Example : If you want a larger number, you can multiply it.
import random
print([Link]() * 100)
3. Choice
Example: Generate a random value from the sequence sequence.
import random
print([Link]( [‘red’, ‘black’, ‘green’] ))z
4. Shuffle
Example :The shuffle function, shuffles the elements in list in place, so
they are in a random order.
from random import shuffle
x = [[i] for i in range(10)]
shuffle(x)
print(x)
5. Randrange
Example :Generate a randomly selected element from range(start, stop, step)
import random
for i in range(3):
print [Link](0, 101, 5)
2.4.2 Function
In Python, function is a group of related statements that perform a specific task.
Functions help break our program into smaller and modular chunks. As our program
grows larger and larger, functions make it more organized and manageable.
2.32 Problem Solving and Python Programming
Need of function
Provide better modularity and high degree of reusability.
Python supports:
1. Built-in functions e.g. print()
2. User-deûned functions
i) Built in functions
Built in functions are the functions that are already created and stored in python.
These built in functions are always available for usage and accessed by a
programmer. It cannot be modified. Some examples are below :
abs ( ) divmod ( ) input ( )
all ( ) enumerate ( ) int ( )
any ( ) eval ( ) ininstance ( )
basestring ( ) execfile ( ) issubclass ( )
bin ( ) file ( ) iter ( )
bool ( ) filter ( ) len ( )
bytearray ( ) float ( ) list ( )
callable ( ) format ( ) locals ( )
chr ( ) frozenset ( ) long ( )
classmethod ( ) getattr ( ) map ( )
cmp ( ) globals ( ) max ( )
compile ( ) hasattr ( ) memoryview ( )
complex ( ) hash ( ) min ( )
delattr ( ) help ( ) next ( )
dict ( ) hex ( ) object ( )
dir ( ) id ( ) oct ( )
Data, Expressions, Statements 2.33
def functionName() :
functionName() ;
Example
# Function definition is here
def printme( str ):
“This prints a passed string into this function”
print (str)
return;
# Now you can call printme function
printme(“I’m first call to user defined function!”)
printme(“Again second call to the same function”)
//Scope of a variable
def my_func():
x = 10
print(“Value inside function:”,x)
x = 20
my_func()
print(“Value outside function:”,x)
Output
Value inside function: 10
Value outside function: 20
Data, Expressions, Statements 2.35
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.
Example
def f1():
print(“Moe”)
def f2():
f4()
print(“Meeny”)
def f3():
f2()
print(“Miny”)
f1()
def f4():
print(“Eeny”)
f3()
Output
Eeny
Meeny
Miny
Moe
2.36 Problem Solving and Python Programming
2.4.3 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: def my_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)
Pass by value
In pass-by-value, the function receives a copy of the argument objects passed to
it by the caller, stored in a new location in memory.
Data, Expressions, Statements 2.37
Pass By reference
All parameters (arguments) in the Python language are passed by reference. It
means if you change what a parameter refers to within a function, the change also
reflects back in the calling function. For example:
Output:
Name: george
Age 40
Variable length Arguments:
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.
Example :
def my_details(*name ):
print(*name)
my_details(“rajan”,”rahul”,”micheal”,ärjun”)
Output:
rajan rahul micheal ärjun
Variable max is defi ned outside func1 and func2 and therefore “global” to
each
Suggested Link to Refer:
Built-in Functions in Python
[Link] (Duration: 10:40)
[Link]
Defining Functions
[Link] 10:27)
Pass-by-Value vs. Pass-by-Reference
[Link] (Duration: 2:52)
Types of function arguments
[Link] (Duration: 11:38)
[Link]
2.42 Problem Solving and Python Programming
ILLUSTRATIVE EXAMPLES
1. Python Program to swap or exchange the values of two variables
Method 1
a = 10
b = 20
print(“before swapping\na=”, a, “ b=”, b)
temp = a
a=b
b = temp
print(“\nafter swapping\na=”, a, “ b=”, b)
Method 2
a = 30
b = 20
print(“\nBefore swap a = %d and b = %d” %(a, b))
a, b = b, a
print(“\nAfter swaping a = %d and b = %d” %(a, b))
2. Circulate the values of n Variables
l=[1,2,3,4,5]
print(l[::-1])
3. Python Program to test the year is leap or not
year=int(input(“Enter year to be checked:”))
if(year%4==0 and year%100!=0 or year%400==0):
print(“The year is a leap year!)
else:
print(“The year isn’t a leap year!)
Data, Expressions, Statements 2.43
ASSIGNMENT QUESTIONS
1. Program variables have data types such as: Integer; Float and String. After the
execution of the following snippet of code what are the data type of the three
variables var_one, var_two and var_three?
var_one = 57
var_two = 9.81
var_three = ‘What have the Romans ever done for us?’
2. The Data type of a variable defines the way in which the variable can be processed.
With this in mind what will happen when the following snippet of code is
executed.
var_one = ‘What have the Romans ever done for us?’
var_two = ‘He is not the messiah he is a very naughty boy!’
var_three = var_one * var_two
3. Write a Python program that accepts an integer (n) and computes the value of
n+nn+nnn
4. Write a program that calculates and prints the value according to the given
formula:
Q = Square root of [(2 * C * D)/H]
Following are the fixed values of C and H:
C is 50. H is 30.
D is the variable whose values should be input to your program in a comma-
separated sequence.
Example
Let us assume the following comma separated input sequence is given
to the program:
100,150,180
The output of the program should be:
18, 22, 24
5. A circular swimming pool is x metres in diameter. What volume of water does it
contain if the pool is the same depth at all points?
2.44 Problem Solving and Python Programming
PROGRAM EXERCISES
1. Write a Python program to compute Greatest Common Divisor of two numbers
using function.
2. Write a Python program to swap two numbers using function.
3. Code a python program to accept two numbers m and n, find the quotient,
remainder and print the result.
4. Write a python program to merge a two list.
5. Write a python program to swap variables without using third variable.
6. Write a python program to add two numbers
7. Write a python program to find the area of a triangle
8. Write a python program to convert Celsius to Farenheit.
9. Write a python program to concatenate two strings
10. Write a python program to solve a quadratic equation
STATEMENTS
return [expression]
23. How will you call a function?
A function call is used to call the function which substitutes the entire definition
of the function.
Eg:
def mul():
a=4
b=8
c=a*b
print(c)
mul() # function call
24. Define parameters.
Function calls contain the name of the function being executed followed by a
list of values, called arguments, which are assigned to the parameters in the
function definition.
Eg: def mul(a,b)
25. Define call by value and call by reference.
There are two ways to pass value or data to function, call by value and reference.
Original value is not modified in call by value but it is modified in call by
reference.
26. What is mean by local and global variables?
Variables that are defined inside a function body are called as local scope
variables.
Variables that are defined outside a function body are called as global scope variables.
Eg:
total = 0; # This is global variable.
def sum( arg1, arg2 ):
total = arg1 + arg2; # Here total is local variable.
2.50 Problem Solving and Python Programming
27. Give the different types of function argument.
The four types of function arguments are:
1. Required arguments
2. Keyword arguments
3. Default arguments
4. Variable-length arguments
PART – B QUESTIONS
1. Discuss about the various operators in python.
2. Discuss about operator precedence in python with eg.
3. Explain in detail about functions and parameters.
4. Explain about the various arguments with eg.
5. What is the use of comments and modules. Explain
6. Write a program to
a. exchange the values of variables
b. circulate the value of n variables
c. find distance between two points
Control Flow, Functions 3.1
Unit III
Example Program3.5:
Program 1:
n=88
if n%2 ==0 or n%3==0:
print(“yes”)
Output:
yes
Program 2:
n=6
if n%2==0 or n%3==0:
print(“yes”)
Output:
yes
The not operator negates a boolean expression, so not (x > y) is True if x > y is
False, that is, if x is less than or equal to y.
The expression on the left of the or operator is evaluated first: if the result is
True, Python does not evaluate the expression on the right — this is called short-
circuit evaluation.
Similarly, for the ―and operator, if the expression on the left yields False, Python
does not evaluate the expression on the right. So there are no unnecessary evaluations.
Python is not very strict. Any nonzero number is interpreted as True:
>>> 42 and True
True
Recommended online video tutorial link: Boolean values and operators
[Link]
1. Sequential structure (if) – Instructions are executed in an order that they are
written
2. Selection Structure/Branching/Decision Making – Instructions are being
executed selectively based on conditions
if statement
If..else statement
If..elif..else statement
3. Repetition structure/Looping/Iterative – Instructions are repeatedly executed
while
For
Unconditional Structure
Break
Continue
Pass
condition condition
True False
True False
loop
[Link] IF Statement
Conditional statement checks conditions and change the behavior of the program
accordingly.
The simplest form is the if statement:
>>>if x > 0:
print(‘x is positive’)
The boolean expression after ―if is called the condition. If it is true, the indented
statement runs. If not, nothing happens.
The syntax of ‘if’ statement:
if <test_expression>:
<body>
Test False
Expression
True
Body of if
Compound statements
Syntax for Compound statements
Header
Body of if
if condition:
Statements
3.6 Problem Solving and Python Programming
Statements like this are called compound statements. At least one statement must
be there inside the statement and there is no limit for the number of statements.
Occasionally, it is useful to have a body with no statements. In that case, we can use
the pass statement, which does nothing.
Example:
if x < 0:
pass
if grade>=70:
print ( First class‘)
The if..else statement evaluates test expression and will execute body of if only
when test condition is True. If the condition is False, body of else is executed.
Indentation is used to separate the blocks.
The syntax of ‘if..else’ statement:
if test condition:
Body of if
else:
Body of else
Test False
Expression
True
Example:
if x % 2 == 0:
print(‘x is even’)
else:
print(‘x is odd’)
If the remainder when x is divided by 2 is 0, then we know that x is even, and the
program displays an appropriate message. If the condition is false, the second set of
statements runs. Since the condition must be true or false, exactly one of the alternatives
will run. The alternatives are called branches, because they are branches in the flow of
execution.
Sometimes there are more than two possibilities and we need more than
two branches.
The elif is short for else if. It allows us to check for multiple expressions.
If the condition for if is False, it checks the condition of the next elif block
and so on.
If all the conditions are False, body of else is executed.
Only one block among the several if...elif...else blocks is executed according
to the condition.
The if block can have only one else block. But it can have multiple elif
blocks.
3.8 Problem Solving and Python Programming
The syntax of ‘if..elif..else’ statement:
if condition:
Body of if
elif condition:
Body of elif
else:
Body of else
Test False
Expression
of if
True
Test False
Expression
Body of if of elif
True
Example 1:
if x < y:
print(‘x is less than y’)
elif x > y:
print(‘x is greater than y’)
else:
print(‘x and y are equal’)
elif is an abbreviation of ―else if . Again, exactly one branch will run. There is
no limit on the number of elif statements. If there is an else clause, it has to be at the
end, but there doesn‘t have to be one.
Control Flow, Functions 3.9
Example 2:
if choice == ‘a’:
draw_a()
elif choice == ‘b’:
draw_b()
elif choice == ‘c’:
draw_c()
Each condition is checked in order. If the first is false, the next is checked, and
so on. If one of them is true, the corresponding branch runs and the statement ends.
3.2 ITERATION
Iteration is repeating a set of instructions and controlling their execution for a
particular number of times. Iteration statements are also called as loops.
3.2.1 State
A new assignment makes an existing variable refer to a new value (and stop
referring to the old value).
>>> x = 5
>>> x
5
>>> x = 7
>>> x
7
The first time we display x, its value is 5; the second time, its value is 7. Python
uses the equal sign (=) for assignment. First, equality is a symmetric relationship and
assignment is not.
For example, in mathematics, if a = 7 then 7 = a. But in Python, the statement a
= 7 is legal and 7 = a is not. Also, in mathematics, a proposition of equality is either
true or false for all time. If a =b now, then a will always equal b. In Python, an
assignment statement can make two variables equal.
>>> a=5
>>> b = a # a and b are now equal
3.10 Problem Solving and Python Programming
>>> a = 3 # a and b are no longer equal
>>> b
5
The third line changes the value of ―a but does not change the value of ―b , so
they are no longer equal. A common kind of reassignment is an update, where the
new value of the variable depends on the old.
>>> x = x + 1
This means ―get the current value of x, add one, and then update x with the
new value. If we try to update a variable that doesn‘t exist, you get an error, because
Python evaluates the right side before it assigns a value to x:
>>> x = x + 1
NameError: name ‘x’ is not defined, Before you can update a variable, you have
to initialize it, usually with a simple assignment:
>>> x = 0
>>> x = x + 1
Updating a variable by adding 1 is called an increment; subtracting 1 is called a
decrement.
The above while statement prints the value of n a number of times until n is
greater than zero.
The flow of execution for a while statement:
1. Determine whether the condition is true or false.
2. If false, exit the while statement and continue execution at the next statement.
3. If the condition is true, run the body and then go back to step 1
Test False
Expression
True
Body of
while
Exit loop
The body of the loop should change the value of one or more variables so that
the condition becomes false eventually and the loop terminates. Otherwise the loop
will repeat forever, which is called an infinite loop. In the case of countdown, we can
prove that the loop terminates: if n is zero or negative, the loop never runs. Otherwise,
n gets smaller each time through the loop, so eventually we have to get to 0. For some
other loops, it is not so easy to tell.
3.12 Problem Solving and Python Programming
Example: Python while Loop
# Program to add natural numbers up to sum = 1+2+3+...+n
# To take input from the user
n = 10
# initialize sum and counter
sum = 0
i=1
while i <= n:
sum = sum + i
i = i+1 # update counter
print(“The sum is”, sum) # print the sum
Output:
The sum is 55
In the above program, the test condition will be True as long as our counter
variable i is less than or equal to n. We need to increase the value of counter variable
in the body of the loop. This is very important (and mostly forgotten). Failing to do so
will result in an infinite loop (never ending loop). Finally the result is displayed.
While loop with else
We can have an optional else block with while loop as well. The else part is
executed if the condition in the while loop evaluates to False. The while loop can be
terminated with a break statement. In such case, the else part is ignored. Hence, a
while loop’s else part runs if no break occurs and the condition is false.
Example
# Program to illustrate the use of else statement with the while loop
counter = 0
while counter < 3:
print(“Inside loop”)
counter = counter + 1
else:
print(“Inside else”)
Control Flow, Functions 3.13
Output
Inside loop
Inside loop
Inside loop
Inside else
Here, we use a counter variable to print the string Inside loop three times. On the
forth iteration, the condition in while becomes False. Hence, the else part is executed.
Last Yes
item
reached?
No
Body of for
Exit loop
Fig: operation of for loop
The values in the generated sequence include the starting value, up to but not
including the ending value. For example, range(1, 11) generates the sequence [1, 2, 3,
4, 5, 6, 7, 8,9, 10].
The range function is convenient when long sequences of integers are needed.
Actually, range does not create a sequence of integers. It creates a generator function
able to produce each next item of the sequence when needed.
for i in range(4):
print(‘Hello!’)
for loop with else
A for loop can have an optional else block as well. The else part is executed if
the items in the sequence used in for loop exhausts. break statement can be used to
stop a for loop. In such case, the else part is ignored. Hence, a for loop’s else part runs
if no break occurs.
Example:
digits = [0, 1, 5]
for i in digits:
print(i)
else:
print(“No items left.”)
Output:
0
1
5
No items left.
Here, the for loop prints items of the list until the loop exhausts. When the for
loop exhausts, it executes the block of code in the else and prints No items left.
3.2.4 Break
Break statement is used to break the loop. For example, suppose you want to
take input from the user until they type done.
3.16 Problem Solving and Python Programming
Enter loop
True
Yes
break?
No
Exit loop
Remaining body
of loop
This way of writing while loops is common because you can check the condition
anywhere in the loop (not just at the top) and you can express the stop condition
affirmatively (―stop when this happens ) rather than negatively (―keep going until
that happens ).
Enter loop
False
test expression
of loop
True
Yes
continue?
No
Exit loop
Remaining body
of loop
3.2.6 Pass
It is used when a statement is required syntactically but you do not want any
command or code to execute. The pass statement is a null operation; nothing happens
when it executes. The pass is also useful in places where your code will eventually
go, but has not been written yet.
We generally use it as a placeholder.
Suppose we have a loop or a function that is not implemented yet, but we want
to implement it in the future. They cannot have an empty body. The interpreter would
complain. So, we use the pass statement to construct a body that does nothing.
Example:
for letter in ‘Python’:
if letter == ‘h’:
pass
print ‘This is pass block’
print ‘Current Letter :’, letter
print “Good bye!”
Control Flow, Functions 3.19
Output:
Current Letter : P
Current Letter : y
Current Letter : t
This is pass block
Current Letter : h
Current Letter : o
Current Letter : n
Good bye!
Difference between various iterations Pass Continue Break
Pass
Statement simply means ‘do nothing’
When the python interpreter encounters the pass statement, it simply
continues with its execution
Continue
Continue with the loop
resume execution at the top of the loop or goes to next iteration
Break
Breaks the loop
When a break statement is encountered, it terminates the block and gets the
control out of the loop
While
Indefinite Loops
The exit condition will be evaluated again, and execution resumes from the
top.
For
Definite Loop
The item being iterated over will move to its next element.
3.20 Problem Solving and Python Programming
3.3 FRUITFUL FUNCTIONS
subsequent statements. Another way to write the above function is to leave out the
else and just follow the if condition by the second return statement.
def absolute_value(x):
if x < 0:
return -x
return x
Think about this version and convince yourself it works the same as the first
one. Code that appears after a return statement, or any other place the flow of execution
can never reach, is called dead code.
In a fruitful function, it is a good idea to ensure that every possible path through
the program hits a return statement. The following version of absolute value fails to
do this:
def absolute_value(x):
if x < 0:
return -x
elif x > 0:
return x
This version is not correct because if x happens to be 0, neither condition is true,
and the function ends without hitting a return statement. In this case, the return value
is a special value called None:
>>> print
absolute_value(0)
None
None is the unique value of a type called the NoneType:
>>> type(None)
All Python functions return None whenever they do not return another value.
The scope of an identifier is the region of program code in which the identifier can be
accessed, or used.
3.22 Problem Solving and Python Programming
3.3.2 Scope
There are three important scopes in Python:
Local scope refers to identifiers declared within a function. These identifiers
are kept in the namespace that belongs to the function, and each function
has its own namespace.
Global scope refers to all the identifiers declared within the current module,
or file.
Built-in scope refers to all the identifiers built into Python—those like range
and min that can be used without having to import anything, and are (almost)
always available.
Python (like most other computer languages) uses precedence rules: the same
name could occur in more than one of these scopes, but the innermost, or local scope,
will always take precedence over the global scope, and the global scope always gets
used in preference to the built-in scope.
Let‘s start with a simple example:
def range(n):
return 123*n
print(range(10))
Using the scope lookup rules determines this: our own range function, not the
built-in one, is called, because our function range is in the global namespace, which
takes precedence over the built in names. So although names likes range and min are
built-in, they can be ―hidden from your use if you choose to define your own variables
or functions that reuse those names.
n = 10
2m=3
def f(n):
m=7
return 2*n+m
print(f(5), n, m)
This prints 17 10 3. The reason is that the two variables m and n in lines 1 and 2
are outside the function in the global namespace. Inside the function, new variables
called n and m are created just for the duration of the execution of f. These are created
Control Flow, Functions 3.23
in the local namespace of function f. Within the body of f, the scope lookup rules
determine that we use the local variables m and n. By contrast, after we‘ve returned
from f, the n and m arguments to the print function refer to the original variables on
lines 1 and 2, and these have not been changed in any way by executing function f.
Notice too that the def puts name f into the global namespace here. So it can be called
on line 7. What is the scope of the variable n on line 1? Its scope—the region in which
it is visible—is lines 1, 2, 6, 7. It is hidden from view in lines 3, 4, 5 because of the
local variable n.
3.3.3 Composition
You can call one function from within another. This ability is called composition.
Example:
Write a function that takes two points, the center of the circle and a point on the
perimeter, and computes the area of the circle. Assume that the center point is stored
in the variables xc and yc, and the perimeter point is in xp and yp. The first step is to
find the radius of the circle, which is the distance between the two points.
radius = distance(xc, yc, xp, yp)
The second step is to find the area of a circle with that radius and return it. Again
we will useone of our earlier functions:
result = area(radius)
return result
#Wrapping that up in a function, we get:
def area2(xc, yc, xp, yp):
radius = distance(xc, yc, xp, yp)
result = area(radius)
return result
We called this function area2 to distinguish it from the area function defined earlier.
The temporary variables radius and result are useful for development, debugging, and
single-stepping through the code to inspect what is happening, but once the program is
working, we can make it more concise by composing the function calls:
def area2(xc, yc, xp, yp):
return area(distance(xc, yc, xp, yp))
3.24 Problem Solving and Python Programming
3.3.4 Recursion
Recursion is the process of calling the function that is currently executing. It is
legal for one function to call another; it is also legal for a function to call itself. An
example of recursive function to find the factorial of an integer.
Example:
0! = 1
n! = n(n - 1)!
This definition says that the factorial of 0 is 1, and the factorial of any other
value, n, is n multiplied by the factorial of n - 1.
So 3! is 3 times 2!, which is 2 times 1!, which is 1 times 0!. Putting it all together,
3! equals 3 times 2 times 1 times 1, which is 6.
The flow of execution for this program is similar to the flow of countdown. If
we call factorial with the value 3:
Since 3 is not 0, we take the second branch and calculate the factorial of n-1...
Since 2 is not 0, we take the second branch and calculate the factorial of n-1...
Since 1 is not 0, we take the second branch and calculate the factorial of n-1...
Since 0 equals 0, we take the first branch and return 1 without making any
more recursive calls.
The return value, 1, is multiplied by n, which is 1, and the result is returned.
The return value, 1, is multiplied by n, which is 2, and the result is returned.
The return value (2) is multiplied by n, which is 3, and the result, 6, becomes
the return value of the function call that started the whole process.
The return values are shown being passed back up the stack. In each frame,
the return value is the value of result, which is the product of n and recurse.
In the last frame, the local variables recurse and result do not exist, because
the branch that creates them does not run.
Control Flow, Functions 3.25
__main__
6
factorial n 3 recurse 2 result 6
2
factorial n 2 recurse 1 result 2
1
factorial n 1 recurse 1 result 1
1
factorial n 0
Example:
# An example of a recursive function to find the factorial of a number
def factorial(x):
“””This is a recursive functionto find the factorial of an integer”””
if x == 1:
return 1
else:
return (x * factorial(x-1))
num = 3
print(“The factorial of”, num, “is”, factorial(num))
Output:
The factorial of 3 is 6
3.4 STRINGS
A string is a sequence of characters. You can access the characters one at a time
with the bracket operator:
>>> fruit = ‘banana’
letter = fruit[1]
The second statement selects character number 1 from fruit and assigns it to
letter. The expression in brackets is called an index. The index indicates which character
in the sequence you want (hence the name).But you might not get what you expect:
>>> letter
‘a’
For most people, the first letter of ‘banana’ is b, not a. But for computer scientists,
the index is an offset from the beginning of the string, and the offset of the first letter
is zero.
>>> letter = fruit[0]
>>> letter
‘b’
So b is the 0th letter (―zero-eth ) of ‘banana’, a is the 1th letter (―one-eth ),
and n is the 2th letter (―two-eth ). As an index you can use an expression that contains
variables and operators:
Control Flow, Functions 3.27
>>> i=1
>>> fruit[i]
‘a’
But the value of the index has to be an integer. Otherwise you get:
>>> letter = fruit[1.5]
TypeError: string indices must be integers
3.4.2 Immutability
It is tempting to use the [] operator on the left side of an assignment, with the
intention of changing a character in a string.
For example:
>>> greeting = ‘Hello, world!’
>>> greeting[0] = ‘J’
TypeError: ‘str’ object does not support item assignment
The ―object in this case is the string and the ―item is the character you tried to
assign. The reason for the error is that strings are immutable, which means you can‘t
change an existing string. The best you can do is create a new string that is a variation
on the original:
>>> greeting = ‘Hello, world!’
>>> new_greeting = ‘J’ + greeting[1:]
>>> new_greeting
‘Jello, world!’
This example concatenates a new first letter onto a slice of greeting. It has no
effect on the original string.
Length
The len function, when applied to a string, returns the number of characters in a
string:
>>> fruit = “banana”
>>> len(fruit)
6
The index starts counting form zero. In the above string, the index value in from
0 to 5.
To get the last character, we have to subtract 1 from the length of fruit:
Control Flow, Functions 3.29
size = len(fruit)
last = fruit[size-1]
Alternatively, we can use negative indices, which count backward from the end
of the string.
The expression fruit[-1] yields the last letter, fruit[-2] yields the second to last,
and so on.
Output:
His name is Arthur!
I am Alice and I am 10 years old.
The template string contains place holders, ... {0} ... {1} ... {2} ... etc. The
format method substitutes its arguments into the place holders. The numbers in the
place holders are indexes that determine which argument gets substituted. Each of the
replacement fields can also contain a format specification — it is always introduced
by the : symbol . This modifies how the substitutions are made into the template, and
can control things like: whether the field is aligned to the left <, center ^, or right > the
width allocated to the field within the result string (a number like 10) the type of
conversion if the type conversion is a float, you can also specify how many decimal
places are wanted.
print(“Pi to three decimal places is {0:.3f}”.format(3.1415926))
ASSIGNMENT:
Write python program for the following:
1. Display all even numbers between 50 and 80 (both inclusive) using “for”
loop.
2. Add natural numbers up to n where n is taken as an input from user. Print
the sum.
3. Prompt the user to enter a number. Print whether the number is prime or
not.
4. Print Fibonacci series till nth term where n is taken as an input from user.
Hint – Fibonacci series is a series of numbers in which each number is the
sum of the two preceding numbers. Series start from 1 and goes like : 1, 1,
2, 3, 5, 8, 13 ….
5. Find the first N prime Numbers.
6. Program that reads a positive integer and then prints out all the positive
divisors of that integer.
Hint – The positive divisor of positive integer 36 are 36,18,12,9,6,4,3,2
and 1.
3.38 Problem Solving and Python Programming
7. Program that reads a character and prints out whether or not it is a vowel or
consonant.
8. Program to print the first ‘n’ numbers divisible by 7
5. What is iteration?
Iteration is repeating a set of instructions and controlling their execution for a
particular number of times. Iteration statements are also called as loops.
6. Specify the use of range function in for loop.
The range function is generator and able to produce next item of the sequence
when needed.
It is used in a for loop.
Eg: for val in values: print(val)
7. Differentiate break and continue statement with example
The continue statement rejects all the remaining statements in the current iteration
of the loop and moves the control back to the top of the loop.
Break statement is used to break the loop.
Eg:
for number in range(1,5):
if(number==3):
continue
print(number)
Output:
1
2
4
for number in range(1,5):
if(number==3):
break
print(number)
Output:
1
2
3
3.40 Problem Solving and Python Programming
8. What is the use of pass statement in python?
It is used when a statement is required syntactically but you do not want any
command or code to execute. The pass statement is a null operation; nothing
happens when it executes.
Eg:
for letter in ‘Python’:
if letter == ‘h’:
pass
9. Describe about dead code.
Code that ppears after a return statement, or any other place the flow of execution
can never reach, is called dead code.
def absolute_value(x):
if x < 0:
return -x
return x
10. What refers to local and global scope?
Local scope refers to identifiers declared within a function. These identifiers are
kept in the namespace that belongs to the function, and each function has its
own namespace.
Global scope refers to all the identifiers declared within the current module, or
file.
Built-in scope refers to all the identifiers built into Python
11. Which function is called composition?
A function calls one function with another is called composition.
Eg:
def val():
result = area(radius)
return result
Control Flow, Functions 3.41
PART B QUESTIONS
1. Discuss about the iteration statements(state, while, for, break, continue, pass)
2. Discuss about the conditional statements(if, if-else, if-elif)
3. Explain about the function composition and recursion with eg.
4. Discuss about the fruitful functions with eg.
5. Explain about the string operations with programs.
6. Write a program to
a. Find the square root of a number
b. Calculate gcd of two numbers
c. Find the exponent of a number
d. Find the sum of array of numbers
7. Write a program to
a. Perform binary search
b. Linear search
LIsts, Tuples, Dictionaries 4.1
Unit IV
4.1 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 data types.
Example:
ps = [10, 20, 30, 40]
qs = [“spam”, “bungee”, “swallow”]
The first example is a list of four integers. The second is a list of three strings.
The elements of a list don t have to be the same type. The following list contains a
string, a float, an integer, and another list: zs = [“hello”, 2.0, 5, [10, 20]]
A list within another list is said to be nested. Finally, a list with no elements is
called an empty list, and is denoted [].
A list of Integers : [1951,1952,1953,1958,1957]
A list of Strings : [„orange , blue , yellow ]
An empty list : []
4.2 Problem Solving and Python Programming
4.1.1 List Operations:
Operations Examples Description
create a list >>> a=[2,3,4,5,6,7,8,9,10] in this way we can create alist
>>> print(a) at compile time
[2, 3, 4, 5, 6, 7, 8, 9, 10]
Indexing >>> print(a[0]) Accessing the item in the
2 position 0
>>> print(a[8]) Accessing the item in the
10 position 8
>>> print(a[-1]) Accessing a last elementusing
10 negative indexing.
Slicing >>> print(a[0:3]) Printing a part of the list.
[2, 3, 4]
>>> print(a[0:])
[2, 3, 4, 5, 6, 7, 8, 9, 10]
Concatenation >>>b=[20,30] Adding and printing theitems of
>>> print(a+b) two lists.q
[2, 3, 4, 5, 6, 7, 8, 9, 10, 20, 30]
Repetition >>> print(b*3) Create a multiple copies ofthe
[20, 30, 20, 30, 20, 30] same list.
Updating >>> print(a[2]) Updating the list using index
4>>> a[2]=100 value.
>>> print(a)
[2, 3, 100, 5, 6, 7, 8, 9, 10]
Membership >>> a=[2,3,4,5,6,7,8,9,10] Returns True if element ispresent
>>> 5 in a in list. Otherwisereturns false.
True
>>> 100 in a
False
>>> 2 not in a
False
Comparison >>> a=[2,3,4,5,6,7,8,9,10] Returns True if all elementsin both
>>>b=[2,3,4] elements are [Link]
>>> a==b returns false
False
>>> a!=b
True
LIsts, Tuples, Dictionaries 4.3
append():
Example 1:
animal = [‘cat’, ‘dog’, ‘rabbit’]
[Link](‘goat’)
print(‘Updated animal list: ‘, animal)
Output:
Updated animal list: [‘cat’, ‘dog’, ‘rabbit’, ‘goat’]
4.6 Problem Solving and Python Programming
Example 2:
animal = [‘cat’, ‘dog’, ‘rabbit’]
wild_animal = [‘tiger’, ‘fox’]
[Link](wild_animal)
print(‘Updated animal list: ‘, animal)
Output:
Updated animal list: [‘cat’, ‘dog’, ‘rabbit’, [‘tiger’, ‘fox’]]
insert():
Example:
vowel = [‘a’, ‘e’, ‘i’, ‘u’]
[Link](3, ‘o’)
print(‘Updated List: ‘, vowel)
Output:
Updated List: [‘a’, ‘e’, ‘i’, ‘u’, ‘o’]
extend():
Example:
language = [‘French’, ‘English’, ‘German’]
language1 = [‘Spanish’, ‘Portuguese’]
[Link](language1)
print(‘Language List: ‘, language)
Output:
Language List: [‘French’, ‘English’, ‘German’, ‘Spanish’, ‘Portuguese’]
Index():
Example 1:
vowels = [‘a’, ‘e’, ‘i’, ‘o’, ‘i’, ‘u’]
index = [Link](‘e’)
print(‘The index of e:’, index)
index = [Link](‘i’)
print(‘The index of i:’, index)
LIsts, Tuples, Dictionaries 4.7
Output:
The index of e: 1
The index of e: 2
Example 2:
vowels = [‘a’, ‘e’, ‘i’, ‘o’, ‘u’]
index = [Link](‘p’)
print(‘The index of p:’, index)
Output:
ValueError: ‘p’ is not in list
remove():
Example:
animal = [‘cat’, ‘dog’, ‘rabbit’]
[Link](‘rabbit’)
print(‘Updated animal list: ‘, animal)
Output:
Updated animal list: [‘cat’, ‘dog’]
clear():
Example:
list = [{1, 2}, (‘a’), [‘1.1’, ‘2.2’]]
[Link]()
print(‘List:’, list)
Output: List: []
Sort():
Example 1:
vowels = [‘e’, ‘a’, ‘u’, ‘o’, ‘i’]
[Link]()
print(‘Sorted list:’, vowels)
4.8 Problem Solving and Python Programming
Output:
Sorted list: [‘a’, ‘e’, ‘i’, ‘o’, ‘u’]
Example 2:
vowels = [‘e’, ‘a’, ‘u’, ‘o’, ‘i’]
[Link](reverse=True)
print(‘Sorted list (in Descending):’, vowels)
Output:
Updated List: [‘a’, ‘e’, ‘i’, ‘u’, ‘o’]
reverse():
Example:
os = [‘Windows’, ‘macOS’, ‘Linux’]
print(‘Original List:’, os)
[Link]()
print(‘Updated List:’, os)
Output:
Original List: [‘Windows’, ‘macOS’, ‘Linux’]
Updated List: [‘Linux’, ‘macOS’, ‘Windows’]
Example:
os = [‘Windows’, ‘macOS’, ‘Linux’]
print(‘Original List:’, os)
reversed_list = os[::-1]
print(‘Updated List:’, reversed_list)
Output:
Original List: [‘Windows’, ‘macOS’, ‘Linux’]
Updated List: [‘Linux’, ‘macOS’, ‘Windows’]
Pop():
Example:
language = [‘Python’, ‘Java’, ‘C++’, ‘French’, ‘C’]
LIsts, Tuples, Dictionaries 4.9
return_value = [Link](3)
print(‘Return Value: ‘, return_value)
print(‘Updated List: ‘, language)
Output:
Return Value: French
Updated List: [‘Python’, ‘Java’, ‘C++’, ‘C’]
Example:
language = [‘Python’, ‘Java’, ‘C++’, ‘Ruby’, ‘C’]
print(‘When index is not passed:’)
print(‘Return Value: ‘, [Link]())
print(‘Updated List: ‘, language)
print(‘\nWhen -1 is passed:’)
print(‘Return Value: ‘, [Link](-1))
print(‘Updated List: ‘, language)
print(‘\nWhen -3 is passed:’)
print(‘Return Value: ‘, [Link](-3))
print(‘Updated List: ‘, language)
Output:
When index is not passed:
Return Value: C
Updated List: [‘Python’, ‘Java’, ‘C++’, ‘Ruby’]
When -1 is passed:
Return Value: Ruby
Updated List: [‘Python’, ‘Java’, ‘C++’]
When -3 is passed:
Return Value: Python
Updated List: [‘Java’, ‘C++’]
4.10 Problem Solving and Python Programming
4.1.4 List loop
Python’s for statement provides a convenient means of iterating over lists.
For loop:
A for statement is an iterative control statement that iterates once for each element
in a specified sequence of elements. Thus, for loops are used to construct definite
loops.
Syntax:
for val in sequence:
Example1:
a=[10,20,30,40,50]
for i in a:
print(i)
Output :
1
2
3
4
5
Example 2 :
a=[10,20,30,40,50]
for i in range(0,len(a),1):
print(i)
Output :
0
1
2
3
4
LIsts, Tuples, Dictionaries 4.11
Example 3 :
a=[10,20,30,40,50]
for i in range(0,len(a),1):
print(a[i])
Output ;
10
20
30
40
50
While loop:
The while loop in Python is used to iterate over a block of code as long as the
test expression (condition) is [Link] the condition is tested and the result is false,
the loop body will be skipped and the first statement after the while loop will be
executed.
Syntax:
while (condition):
body of while
Example : Sum of Elements in a List
a=[1,2,3,4,5]
i=0
sum=0
while i<len(a):
sum=sum+a[i]
i=i+1
print(sum)
print (b)
a is b
b[2]=35 10 20 30 40
a
print(a) a = [10, 20, 30]
print(b) 0 1 2 3
Output :
[10,20,30,40] b
True
0 1 2 3
[10,20,30,40]
b = [10, 20, 30] 10 20 30 40
[10,20,35,40] a
0 1 2 3
0 1 2 3
b [2] = 35
10 20 30 40
a
0 1 2 3
In this a single list object is created and modified using the subscript operator.
When the first element of the list named “a” is replaced, the first element of the list
named “b” is also replaced. This type of change is what is known as a side effect. This
happens because after the assignment b=a, the variables a and b refer to the exact
same list object.
They are aliases for the same object. This phenomenon is known as aliasing. To
prevent aliasing, a new object can be created and the contents of the original can be
copied which is called cloning.
4.2 TUPLES
A tuple is an immutable linear data structure. Thus, in contrast to lists, once a
tuple is defined, it cannot be altered. Otherwise, tuples and lists are essentially the
same. To distinguish tuples from lists, tuples are denoted by parentheses instead of
square brackets.
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.
An empty tuple is represented by a set of empty parentheses, ().The elements
of tuples are accessed the same as lists, with square brackets, Any attempt to alter a
tuple is invalid. Thus, delete, update, insert, and append operations are not defined
on tuples.
LIsts, Tuples, Dictionaries 4.17
max(tuple)
>>> max(a)
5
del(tuple)
>>> del(a)
4.3 DICTIONARIES
A dictionary organizes information by association, not position.
Example: when you use a dictionary to look up the definition of “mammal,”
you don t start at page 1; instead, you turn directly to the words beginning with “M.”
Phone books, address books, encyclopedias, and other reference sources also organize
information by association. In Python, a dictionary associates a set of keys with data
values. A Python dictionary is written as a sequence of key/value pairs separated by
commas. These pairs are sometimes called entries. The entire sequence of entries is
enclosed in curly braces ({ and }). A colon (:) separates a key and its value.
Note : Elements in Dictionaries are accessed via keys and not by their position.
Here are some example dictionaries:
dict = {‘Name’: ‘Zara’, ‘Age’: 7, ‘Class’: ‘First’}
print “dict[‘Name’]: “, dict[‘Name’]
print “dict[‘Age’]: “, dict[‘Age’]
Output:
dict[‘Name’]: Zara
dict[‘Age’]: 7
4.22 Problem Solving and Python Programming
If we attempt to access a data item with a key, which is not part of the dictionary,
we get an error. We can even create an empty dictionary—that is, a dictionary that
contains no entries. We would create an empty dictionary in a program that builds a
dictionary from scratch.
Membership
a={1: ‘ONE’, 2: ‘two’, 3: ‘three’}
>>> 1 in a
True
>>> 3 not in a
False
Example 2 :
>>>[x for x in range(1,10) if x%2==0]
Output :
[2, 4, 6, 8]
Example 3 :
>>>[x+3 for x in [1,2,3]]
Output :
[4, 5, 6]
Example 4 :
>>> [x*x for x in range(5)]
Output :
[0, 1, 4, 9, 16]
2. Nested list:
List inside another list is called nested list.
Example:
>>> a=[56,34,5,[34,57]]
>>> a[0]
56
>>> a[3]
[34, 57]
>>> a[3][0]
34
>>> a[3][1]
57
4.26 Problem Solving and Python Programming
Reference Links :
List :
NPTEL : [Link]
[Link]
Youtube : [Link]
Tuples
NPTEL : [Link]
Youtube : [Link]
Courseera : [Link]
list-and-tuples-bUWEy
Dictionaries:
NPTEL : [Link]
Youtube : [Link]
ILLUSTRATIVE PROGRAMS
1. Program for matrix addition
X = [[12,7,3],
[4 ,5,6],
[7 ,8,9]]
Y = [[5,8,1],
[6,7,3],
[4,5,9]]
result = [[0,0,0],
[0,0,0],
[0,0,0]]
for r in result:
print(r)
2. Program for matrix subtraction
X = [[12,7,3],
[4 ,5,6],
[7 ,8,9]]
Y = [[5,8,1],
[6,7,3],
[4,5,9]]
result = [[0,0,0],
[0,0,0],
[0,0,0]]
# iterate through rows
for i in range(len(X)):
# iterate through columns
for j in range(len(X[0])):
result[i][j] = X[i][j] - Y[i][j]
for r in result:
print(r)
3. Program for matrix Multiplication
X = [[12,7,3],
[4 ,5,6],
[7 ,8,9]]
4.28 Problem Solving and Python Programming
# 3x4 matrix
Y = [[5,8,1,2],
[6,7,3,0],
[4,5,9,1]]
# result is 3x4
result = [[0,0,0,0],
[0,0,0,0],
[0,0,0,0]]
# iterate through rows of X
for i in range(len(X)):
# iterate through columns of Y
for j in range(len(Y[0])):
# iterate through rows of Y
for k in range(len(Y)):
result[i][j] += X[i][k] * Y[k][j]
for r in result:
print(r)
4. Program for 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.
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 sublist, 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.
LIsts, Tuples, Dictionaries 4.29
23 78 45 8 32 56 Original list
Unsorted
8 78 45 23 32 56 After pass 1
Unsorted
8 23 45 78 32 56 56 After pass 2
Unsorted
8 23 32 78 45 56 After pass 3
Sorted Unsorted
8 23 32 45 78 56 After pass 4
Sorted
8 23 32 45 56 78 After pass 5
Sorted
3 1 4 1 5 9 2 6 5 4
3 1 4 1 5 9 2 6 5 4
3 1 4 1 5 9 2 6 5 4
3 1 4 1 5 9 2 6 5 4
1 3 1 5 2 9 5 4
1 5 4 5
1 4 5 4 5 6
1 1 3 4 5 2 4 5 6 9
1 1 2 3 4 4 5 5 6 9
Python Code
def mergeSort(nlist):
print(“Splitting “,nlist)
if len(nlist)>1:
mid = len(nlist)//2
LIsts, Tuples, Dictionaries 4.33
lefthalf = nlist[:mid]
righthalf = nlist[mid:]
mergeSort(lefthalf)
mergeSort(righthalf)
i=j=k=0
while i < len(lefthalf) and j < len(righthalf):
if lefthalf[i] < righthalf[j]:
nlist[k]=lefthalf[i]
i=i+1
else:
nlist[k]=righthalf[j]
j=j+1
k=k+1
def mergeSort(nlist)
print(”Splitting”, nlist)
len(nlist)>1?
Yes
mid = len(nlist)//2
lefthalf = nlist[:mid]
righthalf = nlist[mid:]
mergeSort(lefthalf)
mergeSort(righthalf)
i=j=k=0
Yes No No
lefthalf[i] <
i < len(lefthalf) ?
righthalf[j]?
Yes No Yes No
Yes No
nlist[k] = righthalf[j]
K=K+1 j=j+1 print(”Merging”, nlist)
k=k+1
End
LIsts, Tuples, Dictionaries 4.35
PRACTICE PROBLEMS
1. Write a python Program to calculate the average of numbers in a list
2. Write a python Program to find the maximum and minimum number in a list
3. Write a python Program to list even and odd numbers of a list
4. Write a Python program
i. To add new elements to the end of the list
ii. To reverse elements in the list
iii. To display same list elements multiple times.
iv. To concatenate two list.
v. To sort the elements in the list in ascending order.
5. Write a Python program for cloning the list and aliasing the list.
6. Write a Python program: “tuple1 = (10,50,20,40,30)”
i. To display the elements 10 and 50 from tuple1
ii. To display length of a tuple1.
iii. To find the minimum element from tuple1.
iv. To add all elements in the tuple1.
v. To display same tuple1 multiple times
LIsts, Tuples, Dictionaries 4.37
ASSIGNMENT QUESTIONS
1. With a given integral number n, write a program to generate a dictionary that
contains (i, i*i) such that is an integral number between 1 and n (both included).
and then the program should print the dictionary.
Suppose the following input is supplied to the program:
8
Then, the output should be:
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64}
Hints:
In case of input data being supplied to the question, it should be assumed to be a
console input.
Consider use dict()
2. Define a function which can print a dictionary where the keys are numbers
between 1 and 3 (both included) and the values are square of keys.
4.38 Problem Solving and Python Programming
Hints:
Use dict[key]=value pattern to put entry into a dictionary.
Use ** operator to get power of a number.
3. Define a function which can print a dictionary where the keys are numbers
between 1 and 20 (both included) and the values are square of keys.
Hints:
Use dict[key]=value pattern to put entry into a dictionary.
Use ** operator to get power of a number.
Use range() for loops.
4. Define a function which can generate and print a list where the values are square
of numbers between 1 and 20 (both included).
Hints:
Use ** operator to get power of a number.
Use range() for loops.
Use [Link]() to add values into a list.
5. With a given tuple (1,2,3,4,5,6,7,8,9,10), write a program to print the first half
values in one line and the last half values in one line.
Hints: Use [n1:n2] notation to get a slice from a tuple.
6. By using list comprehension, please write a program to print the list after
removing the 0th, 2nd, 4th,6th numbers in [12,24,35,70,88,120,155].
Hints:
Use list comprehension to delete a bunch of element from a list.
Use enumerate() to get (index, value) tuple.
7. With a given list [12,24,35,24,88,120,155,88,120,155], write a program to print
this list after removing all duplicate values with original order reserved.
Hints:
Use set() to store a number of values without duplicate.
LIsts, Tuples, Dictionaries 4.39
8. Define the variables x and y as lists of numbers, and z as a tuple.
x=[1, 2, 3, 4, 5]
y=[11, 12, 13, 14, 15]
z=(21, 22, 23, 24, 25)
(a) What is the value of 3*x?
(b) What is the value of x+y?
(c) What is the value of x-y?
(d) What is the value of x[1]?
(e) What is the value of x[0]?
(f) What is the value of x[-1]?
(g) What is the value of x[:]?
(h) What is the value of x[2:4]?
(i) What is the value of x[1:4:2]?
(j) What is the value of x[:2]?
(k) What is the value of x[::2]?
(l) What is the result of the following two expressions?
x[3]=8
print x
(m) What is the result of the above pair of expressions if the list x were
replaced with the tuple z?
9. An assignment statement containing the expression a[m:n] on the left side and a
list on the right side can modify list a. Complete the following table by supplying
the m and n values in the slice assignment statement needed to produce the
indicated list from the given original list.
Original List Target List Slice indices
m n
[2, 4, 6, 8 , 10] [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
[2, 4, 6, 8 , 10] [–10, –8, –6, –4, –2, 0, 2, 4, 6, 8, 10]
[2, 4, 6, 8 , 10] [2, 3, 4, 5, 6, 7, 8, 10]
[2, 4, 6, 8 , 10] [2, 4, 6, ‘a’, ‘b’, ‘c’, 8, 10]
[2, 4, 6, 8 , 10] [2, 4, 6, 8, 10]
[2, 4, 6, 8 , 10] []
[2, 4, 6, 8 , 10] [10, 8, 6, 4, 2]
[2, 4, 6, 8 , 10] [2, 4, 6]
[2, 4, 6, 8 , 10] [6, 8, 10]
[2, 4, 6, 8 , 10] [2, 10]
[2, 4, 6, 8 , 10] [4, 6, 8]
4.40 Problem Solving and Python Programming
PART A QUESTION AND ANSWERS
1. Define python list.
The list is written as a sequence of data values separated by commas. There are
several ways to create a new list; the simplest is to enclose the elements in
square brackets ([ and ]): ps = [10, 20, 30, 40]
2. Write the different ways to create the list.
List1=[4,5,6].
List2=[]
List2[0]=4
List2[1]=5
List2[2]=6
3. Give an example for nest list
A list within the another list is called as nested list.
Eg: zs = [“hello”, 2.0, 5, [10, 20]]
4. Write the syntax for accessing the list elements.
The way to access list elements is index operator.
Eg: List1=[4,5,6]
List1[0]=4
List1[1]=5
List1[2]=6
5. List out the methods used in list.
Append, Extend, Insert, Index, sort, reverse, pop, remove, clear
6. Write a python program for reversing a list.
vowels = [‘e’, ‘a’, ‘u’, ‘o’, ‘i’] [Link](reverse=True)
print(‘Sorted list (in Descending):’, vowels)
7. Write a python program to add a single element to the end of the list.
vowels = [‘e’, ‘a’, ‘u’, ‘i’]
[Link](‘o’)
LIsts, Tuples, Dictionaries 4.41
8. Write a python program to print the list elements using for loop.
num=[10,22,33,44,50,66]
for k in num: print (k)
9. Is list is mutable? Justify your answer.
List elements can be changed once after initializing the list. This is called as
mutability.
>>> numbers = [42, 123]
>>> numbers[1] = 5
>>> numbers[42, 5]
10. Write difference between list aliasing and cloning.
An object with more than one reference has more than one name, the object is
aliased. If the aliased object is mutable, changes made with one alias affect the
other. Clone changes are not being affected the other copy of list.
11. How tuple is differ from list?
Tuples are created by using ( ).
Tuples are immutable.
List is created by using [ ].
List is mutable.
12. Explain how tuples are used as return values
A function can only return one value, but if the value is a tuple, the effect is the
same as returning multiple values.
>>> t = divmod(7, 3)
>>> t (2,1)
13. What is a dictionary? Give an example.
Python dictionary is written as a sequence of key/value pairs separated by
commas. These pairs are sometimes called entries. The entire sequence of entries
is enclosed in curly braces ({ and }). A colon (:) separates a key and its value.
Eg: dict = {‘Name’: ‘Zara’, ‘Age’: 7}
4.42 Problem Solving and Python Programming
14. List out the methods used in dictionary.
Get, fromkeys, clear, copy, items, pop,popitem, setdefault, update, etc. How do
we done the membership test in dictionary?
>>>C={1:1,2:2}
>>>2 in C True
15. Write a python program for iterating the dictionary elements.
squares = {1: 1, 3: 9, 5: 25, 7: 49}
for i in squares: print(squares[i])
16. What is called entries in dictionary?
Python dictionary is written as a sequence of key/value pairs separated by
commas. These pairs are sometimes called entries.
17. List out the built in functions of dictionary.
The functions in dictionary : len( ), any( ), all( ), comp( ), sorted( )
PART B QUESTIONS
1. Discuss about tuple in detail.
2. Define list. Mention the list operations with programs.
3. Explain about advanced list processing and list comprehension.
4. Discuss about Dictionaries, its operations and methods.
5. Code programs :
a. Insertion sort
b. Selection sort
c. Merge sort
d. Histogram
Files, Modules, Packages 5.1
Unit V
5.1 FILES
File is a named location on disk to store related information. It is used to
permanently store data in a non-volatile memory (e.g. hard disk).
Since, random access memory (RAM) is volatile which loses its data when
computer is turned off, we use files for future use of the data.
When we want to read from or write to a file we need to open it first. When we
are done, it needs to be closed, so that resources that are tied with the file are freed.
Hence, in Python, a file operation takes place in the following order.
1. Open a file
2. Read or write (perform operation)
3. Close the file
Examples
The following function copies a file, reading and writing up to fifty characters
at a time.
def copyFile(oldFile, newFile):
f1 = open(oldFile, “r”)
f2 = open(newFile, “w”)
while True:
text = [Link](50)
if text == “”:
break
[Link](text)
[Link]()
[Link]()
return
Simple Examples
To open a text file, use:
fh = open(“[Link]”, “r”)
To read a text file, use:
fh = open(“[Link]”,”r”)
print [Link]()
To read one line at a time, use:
fh = open(“hello”.txt”, “r”)
print [Link]()
To read a list of lines use:
fh = open(“[Link].”, “r”)
print [Link]()
5.6 Problem Solving and Python Programming
To write to a file, use:
fh = open(“[Link]”,”w”)
write(“Hello World”)
[Link]()
To write to a file, use:
fh = open(“[Link]”, “w”)
lines_of_text = [“a line of text”, “another line of text”, “a third line”]
[Link](lines_of_text)
[Link]()
To append to file, use:
fh = open(“[Link]”, “a”)
write(“Hello World again”)
[Link]
To close a file, use
fh = open(“[Link]”, “r”)
print [Link]()
[Link]()
Suggested Links to refer:
Link: [Link]
Link: [Link]
Link: [Link]
Link: [Link]
Files, Modules, Packages 5.7
Sys argv
You can get access to the command line parameters using the sys module.
len([Link]) contains the number of arguments. To print all of the arguments simply
execute str([Link])
#!/usr/bin/python
import sys
print(‘Arguments:’, len([Link]))
print(‘List:’, str([Link]))
Example:
$ python3 [Link] [Link] color
Arguments: 3
List: [‘[Link]’, ‘[Link]’, ‘color’]
Storing command line arguments
You can store the arguments given at the start of the program in [Link]
example, an image loader program may start like this:
#!/usr/bin/python
#!/usr/bin/python
import sys
print(‘Arguments:’, len([Link]))
print(‘List:’, str([Link]))
if [Link] < 2:
print(‘To few arguments, please specify a filename’)
filename = [Link][1]
print(‘Filename:’, filename)
Another example:
(‘Arguments:’, 2)
(‘List:’, “[‘[Link]’, ‘[Link]’]”)
(‘Filename:’, ‘[Link]’)
5.10 Problem Solving and Python Programming
Suggested Links to refer
Open, Read, Display a text file :
Link : [Link]
Create a Text File
Link : [Link]
Format Method
Link : [Link]
Command Line arguments
Link : [Link]
Link[Link]
python_from_command_line.asp
Example
>>> 10 * (1/0)
Traceback (most recent call last):
File “<stdin>”, line 1,
in <module> ZeroDivisionError:
division by zero
>>> 4 + spam*3
Traceback (most recent call last):
File “<stdin>”, line 1, in <module>
NameError: name ‘spam’ is not defined
>>> ‘2’ + 2
Traceback (most recent call last):
File “<stdin>”, line 1, in <module>
TypeError: Can’t convert ‘int’ object to str
implicitly
Why use Exceptions?
Exceptions are convenient in many ways for handling errors and special
conditions in a program. When you think that you have a code which can produce an
error then you can use exception handling.
Raising an Exception
You can raise an exception in your own program by using the raise exception
statement. Raising an exception breaks current code execution and returns the exception
back until it is handled.
5.12 Problem Solving and Python Programming
5.2.1 List of Standard Exceptions
Exception Name Description
Exception Base class for all exceptions
StopIteration Raised when the next() method of an iterator does not point
to any object.
SystemExit Raised by the [Link]() function.
StandardError Base class for all built-in exceptions except StopIteration
and SystemExit.
ArithmeticError Base class for all errors that occur for numeric calculation.
OverflowError Raised when a calculation exceeds maximum limit for a
numeric type.
FloatingPointError Raised when a floating point calculation fails.
ZeroDivisionError Raised when division or modulo by zero takes place for
all numeric types
AssertionError Raised in case of failure of the Assert statement.
AttributeError Raised in case o f failure of at tribute reference o r
assignment.
EOFError Raised when there is no input from either the raw_input()
or input()function and the end of file is reached.
ImportError Raised when an import statement fails.
KeyboardInterrupt Raised when the user interrupts program execution, usually
by pressing Ctrl+c.
LookupError Base class for all lookup errors.
IndexError Raised when an index is not found in a sequence.
KeyError Raised when t he specified key is not fo und in t he
dictionary.
NameError Raised when an identifier is not found in the local or global
namespace.
Files, Modules, Packages 5.13
finally:
this would always be executed
Example:
num=4
try:
res=num/0
print(res)
except:
print(“Zero division error”)
finally:
print(“inside finally”)
print(“Out of try except”)
The above code will prints the following output
Zero division error
inside finally
Out of try except
Suggested Links to refer
Link 1 : [Link]
Link 2 : [Link]
5.3 MODULES
A Python module is simply a Python source file, which can expose classes,
functions and global variables. When imported from another Python source file, the
file name is treated as a namespace. A module is a file containing Python definitions
and statements intended for use in other Python programs. There are many Python
modules that come with Python as part of the standard library.
Random numbers
Uses of Random numbers, To play a game of chance where the computer needs
to throw some dice, pick a number, or flip a coin,
To shuffle a deck of playing cards randomly,
5.18 Problem Solving and Python Programming
To allow/make an enemy spaceship appear at a random location and start
shooting at the player,
To simulate possible rainfall when we make a computerized model for
estimating the environmental impact of building a dam,
For encrypting banking sessions on the Internet Python provides a module
random that helps with tasks like this.
Example
import random
# Create a black box object that generates
random numbers rng = [Link]()
dice_throw = [Link](1,7) # Return an int, one of
1,2,3,4,5,6 delay_in_seconds = [Link]() * 5.0
Repeatability and Testing
Random number generators are based on a deterministic algorithm — repeatable
and predictable. So they re called pseudo-random generators — they are not genuinely
random. They start with a seed value. Each time you ask for another random number,
you ll get one based on the current seed attribute, and the state of the seed (which is
one of the attributes of the generator) will be updated.
The time module
This module provides a number of functions to deal with dates and the time
within a day. It s a thin layer on top of the C runtime library. A given date and time can
either be represented as a floating point value (the number of seconds since a reference
date, usually January 1st, 1970), or as a time tuple. The time module has a function
called clock that is recommended for this purpose. Whenever clock is called, it returns
a floating point number representing how many seconds have elapsed since your
program started running
Example :
import time; # This is required to include time module.
ticks = [Link]()
print “Number of ticks since 12:00am, January 1, 1970:”, ticks
Files, Modules, Packages 5.19
Output:
Number of ticks since 12:00am, January 1, 1970: 7186862.73399
Getting current time
import time;
localtime = [Link]( [Link]([Link]()) )
print “Local current time :”, localtime
Output:
(‘Local current time :’, ‘Mon Jul 09 21:32:29 2018’)
The math module
The math module contains the kinds of mathematical functions you d typically
find on your calculator (sin, cos, sqrt, asin, log, log10) and some mathematical constants
like pi and e:
Example:
import math
print([Link])
print(math.e)
print([Link](4.0))
print([Link](90))
print([Link]([Link](90)))
this would print the following results
3.141592653589793
2.718281828459045
2.0
1.5707963267948966
1.0
Creating your own modules
Python allows you to create our own modules is to save our script as a file with
a .py extension.
def remove_at(pos, seq):
return seq[:pos] + seq[pos+1:]
5.20 Problem Solving and Python Programming
We can now use our module, both in scripts we write, or in the interactive Python
interpreter.
To do so, we must first import the module.
import seqtools
s = “A string!”
seqtools.remove_at(4, s)
A sting!
Namespaces
A namespace is a collection of identifiers that belong to a module, or to a function,
(and as we will see soon, in classes too). Generally, we like a namespace to hold
“related” things, e.g. all the math functions, or all the typical things we d do with
random numbers. Each module has its own namespace, so we can use the same identifier
name in multiple modules without causing an identification problem.
# [Link]
question = “What is the meaning of Life, the Universe, and Everything?”
answer = 42
# [Link]
question = “What is your quest?”
answer = “To seek the holy grail.”
We can now import both modules and access question and answer in each:
import module1
import module2
print([Link])
print([Link])
print([Link])
print([Link])
Will output the following:
What is the meaning of Life, the Universe, and Everything?
What is your quest?
Files, Modules, Packages 5.21
42
To seek the holy grail.
Scope and lookup rules
The scope of an identifier is the region of program code in which the identifier
can be accessed, or used.
There are three important scopes in Python:
Local scope refers to identifiers declared within a function. These identifiers are
kept in the namespace that belongs to the function, and each function has its own
namespace.
Global scope refers to all the identifiers declared within the current module, or
file. Built-in scope refers to all the identifiers built into Python — those like range and
min that can be used without having to import anything, and are (almost) always
available.
Example
def range(n):
return 123*n
print(range(10))
this would print
1230
n = 10
m=3
def f(n):
m=7
return 2*n+m
print(f(5), n, m)
the above code will prints 17 10 3
Attributes and the dot operator
Variables defined inside a module are called attributes of the module. We ve
seen that objects have attributes too: for example, most objects have a __doc__ attribute,
some functions have a __annotations__ attribute. Attributes are accessed using the
dot operator (.). The question attribute of module1 and module2 is accessed using
[Link] and [Link].
5.22 Problem Solving and Python Programming
Modules contain functions as well as attributes, and the dot operator is used to
access them in the same way. seqtools.remove_at refers to the remove_at function in
the seqtools module. When we use a dotted name, we often refer to it as a fully qualified
name, because we re saying exactly which question attribute we mean.
Three import statement variants
Here are three different ways to import names into the current namespace, and
to use them:
1. import math x = sqrt(10)
2. from math import
cos, sin, sqrt x =
sqrt(10)
Link 1 : [Link]
Link2 : [Link]
Package
Game
Link 1: [Link]
Link2 : [Link]
Files, Modules, Packages 5.25
SAMPLE PROGRAMS
1. Program to count the no of words in a given sentence
while True:
print(“Enter ‘x’ for exit.”)
string = input(“Enter any string: “)
if string == ‘x’:
break
else:
word_length = len([Link]())
print(“Number of words =”,word_length,”\n”)
Output:
Enter ‘x’ for exit.
Enter any string: Prathyusha ENgineering College
Number of words = 3
2. To find the most frequent appearance of words in the text.
from string import punctuation
from operator import itemgetter
N = 10
words = {}
words_gen = ([Link](punctuation).lower()
for line in open(“[Link]”)
for word in [Link]())
for word in words_gen:
words[word] = [Link](word, 0) + 1
while True:
print(“Do you like to print the file ? (y/n): “)
check = input()
if check == ‘n’:
break
elif check == ‘y’:
file = open(target, “r”)
print(“\nHere follows the file content:\n”)
print([Link]())
[Link]()
print()
break
else:
continue
ASSIGNMENT QUESTIONS
1. Write a Python program to append text to a file and display the text.
2. Write a Python program to read a file line by line and store it into a list.
3. Write a python program to find the longest words in a file.
4. Write a Python program to assess if a file is closed or not.
5.28 Problem Solving and Python Programming
PART A QUESTION AND ANSWERS
1. Define a file
Files are collection of data. It is stored in computer memory and can be taken
any time we require it. Each file is identified by a unique name. In general a text
file is a file that contains printable characters and whitespace, organized into
lines separated by newline characters.
Eg: [Link]
2. List the two methods used for installing python pacakage.
There are two standard methods for installing a package.
pip install
The pip install script is available within our scientific Python installation.
python [Link] install
3. What python package refers to?
A Python package refers to a directory of Python module.
To import a package :
import [Link]
4. How do we import the packages in python? Give and example.
We can then import the package by:
import [Link]
or
from [Link] import myclass
5. What is the use of dot(.) operator?
Variables defined inside a module are called attributes of the module. Attributes
are accessed using the dot operator (.)
6. Define namespaces in python.
A namespace is a collection of identifiers that belong to a module, or to a function.
Each module has its own name space.
Files, Modules, Packages 5.29
PART B QUESTIONS
1. Explain about files with file operations.
2. Discuss on errors, exceptions and exception handling.
3. Discuss about modules and how will we create own modules.
4. Explain about packages and command line arguments.