Python Python 1
Python Python 1
>>> 8 * 4
>>> 32
Output:
Keywords are reserved words and they cannot be used as names for
identifiers or programmer defined variables. The keywords are listed in
the keyword module can be printed with the example python program:
Keyword_Python.py
Output:
The variable str holds a string 'Hello!', whereas the variable sum
integer value 0 and the variable term holds a floating point value of
0.00025.
1.4 Comments
As programs evolve they tend to add more lines of code and naturally
become more complicated. Thus we can specify comments in natural
language that tell the user/reader what a section of code does. The
comments in Python begin with pound # symbol.
# compute the simple interest
Simple_interest = (p * t * r)/100
A good variable name minimizes the requirements for
comments.
Output:
1.6 Python Literals
Note: Boolean data type are subtypes of integers and when they are
used in context of arithmetic expressions they become 0 and 1
representing False and True.
Note: In the above list modulus operator can be applied to floating point
values also. The division operator/ in the version of Python 3.0 and
above will give floating-point results. The floor division operator // will
return rounded down results. The exponentition operation 40**20has
yielded an integer val and not a long value.
Output:
a/b.i.e., 1.0/2.0 produces a value of 0.5 and a//b, i.e., 1.0//2.0 produces
0. Thus 0.5 = 0 and the output of else part, i.e., "The operation values
are inequal", output is generated.
1.8.2 Assignment Operators
The following is the list of assignment operators supported in python.
Description Example
Operator
= Assignment operator >>> a = 20
>>> print (a)
20
+= Compound addition >>> a = 20
assignment operator
>>> a + = a
>>> print (a)
40
-= Compound >>> a = 20
subtraction
assignment operator >>> a - = a
>>> print (a)
0
*= Compound >>> a =20
multiplication
assignment operator >>> a*= a
>>> print (a)
400
/= Compound division >>> a = 20
assignment operator
>>> a / = 20
>>> print (a)
1.0
%= Compound modulus >>> a = 20
assignment operator
>>> a %= a
>>> print (a)
0
** == Compound >>> a = 20
exponentiation
assignment operator >>> a** = a
>>> print (a)
104857600000000
000000000
//== Compound floor >>> a = 20
division assignment
operator >>> a // = a
>>> print (a)
1
1.8.4 Python Bitwise Operators
a B a&b
0 0 0
1 0 0
0 1 0
1 1 1
22 1 0 1 1 0
20 1 0 1 0 0
Result (22 & 20) = 20 1 0 1 0 0
Output:
1.8.4.2 Bitwise OR(|)
a b a|b
0 0 0
1 0 1
0 1 1
1 1 1
If both the values are 0 then the result of bitwise OR is 0 otherwise the
result is 1.
22 1 0 1 1 0
20 1 0 1 0 0
Result(22|20)=22 1 0 1 1 0
Output:
Output:
If the values is 0 the result of bitwise NOT is 1 and if the value is1 the
result of bitwise NOT is 0.
5 1 0 1 1
Result 111111111111111111111111111111 1 0 1 0
(~) = 111111111111111111111111111111
-6
Output:
1.8.4.5 Right shift operator (>>)
This operator shifts the specified number of bits discarding the right
most bits.
-indicates the current value which has not yet been assigned to a
variable in python.
Here data is shifted to the left by the specified number of bits and the
trailing bits are replaced by zero.
Example: 1
Example: 2
Example: 2
Example:1
Example: 2
Example: 1
Example: 2
1.8.7 Type Conversion in Python
Example: 1
Example: 2
Example: 1
Example: 2
Example: 1
Example: 2
Example: 3
Example: 1
Example: 2
Example: 3
Example: 1
Example: 2
Example:3
Example:
Output:
Parenthesis has the highest precedence. For example, consider the
expression (2+3)*4. First 2 + 3 is evaluated and the answer is 5 then
5*4 is evaluated and the answer is 20.
Output:
Example 2:
Step 1: (2**3) = 8
Step 2: 4//7 = 0 (Integer division)
Step 3: 6*9 = 54
Step 4: 8 + 0 = 8
Step 5: 8 - 54 = - 46
Ans: = - 46
Exercises
1. Is python a Complier or Interpreter?
2. In Python version 3.1 how many keywords are there?
3. What is the difference between a Keyword and an Identifyer?
4. Write a Python program to demonstrate divide by zero error.
5. What is the difference between ( / ) and ( / / ) operator in Python?
Explain with an example.
6. Perform the right shift and left shift operations for the following
values:
23 >> 4
- 20 << 2
34 >> 1
- 12 << 5
Print the result in binary representation of the final shifted value.
7. Solve the following expressions:
True + 312 + 720 + 1.34
False + 312 + 840 + 2.30
2+ 3j + 42 + 723 + 1.24
2+ 3j + 4 + 5j - 2 + 1111 L
8. Evaluate the following Python expressions:
( 2+ 3 ) * 4 - 7 / / 8
3+ 4 / /7 - 8 * ( 2**2 )
23 >> 2 / / 2 + 1 + 1 ** 2
& 2 + 3 % 4 - 10
Chapter 2
Python Input and Output Statements
Most programs accept inputs from the user through the keyboard.
Python provides built-in function for the same.
2.1.1 Input ( ) Function
input ( ) prompts the user to enter a data and returns the output as a
string. It takes a string argument that gives the prompt for the user to
enter data.
Example: Write a python program to input a user name, age and city.
Output:
In the aforementioned program all the input variables like name, age
and city hold strings and are string variables.
Syntax
int ( x, base)
Example
10
25
Syntax
float ( x )
Example
1.23
2.0
Program:
Output:
2.2 Output Statements in Python
Output:
Output:
In the above program the space between the greeting, the name
and the punctuation mark is eliminated.
Example: Write a Python Program to print multiple argument like
name, age and salary of given employee without any space.
Output: Error
The above program generates an Error because + operator can be
used for concentration of strings and not for a string and integer. In the
above program the variable name holds a string and the variable age
holds an integer and thus cannot be concatenated in the print( )
function.
Output:
Output:
Example:
Output:
Output:
Type Meaning
Flowchart Symbols
Table 2.2 Different symbols of the flowchart along with their names
Alternate to normal
Alternate Process
Process
Input/Output(I/O) to or
Data
form a process
Pre defined Process previously
Process specified
Document A document
Preparation Set-Up-Process
Delay Wait
3 The user needs The user does not The user does not
knowledge to require the require the
write an knowledge of a knowledge of a
algorithm for a programming programming
task. language to draw language to write
or understand a or understand a
flowchart. Pseudocode.
2.3.1.3 Flowchart
start
Enter temperature in
Fahrenheit
Write "temperature in
Celsius", C
Write temperature in
Celsius, C
Enter "temperature in
Fahrenheit", F
Stop
2.3.1.4 Python program: TempConv.py
Output:
2.5.1 Theory
Simple Interest:
Simple Interest (SI) calculates the interest only on the original
principal and is not compounded by adding interest on the original
principal. Simple interest is calculated by the formula given in Equation
(2.3)
(P*t*r)
SI =
100
Where,
P is the original amount
t is the duration in year
r is the rate of interest per annum
Example: Imagine Mr. X has borrowed 1000 rupees at the rate of 10%
Simple Interest per annum from his friend Mr. Y. He proposes to pay
the amount borrowed with Interest after 5 years. Calculate the amount
Mr. X needs.
(1000*5*10)
SI = = 500 rupees
100
Actual amount (A) he needs to pay is (P) + SI = 1000 +
500= 1500 rupees.
Compound Interest: In case of Compound Interest (CI), the interest is
calculated not only on the original principal but also on the interest
added to the original principal in the subsequent years. The formula to
compute Compound Interest is given in Equation (2.4).
CI = P* [(1+r/100)t ] - 1
Where,
P is the original amount
t is the duration in years
r is the rate of interest per annum
2.5.2 Algorithm
Step 1: Start
Step 2: Read the value of P
Step 3: Read the value of r
Step 4: Read the value of t
Step 5: si (p*t*r)/100
Step 6: Write si
Step 7: ci p* (pow((1+r/100),t)-1
Step 8: Write ci
Step 9: Stop
Write si
ci = p*(pow((1+r/100),t)-1)
Write si
Stop
Output:
2.6 Write a Python Program to Swap Two Variables without using
a Third Variable
2.6.1 Theory
In computer programming, swapping means exchanging the values of
two variables. There are various ways to swap values of two variables.
Here we are going to discuss how to swap values of two variables
without using a third variable with the following logic.
2.6.2 Algorithm
Step 1: Start
Step 2: Read the values of m& n
Step 3: Write "The values before swapping", m,n
Step 4: m m + n
Step 5: n m - n
Step 6: m m - n
Step 7: Write "The values after swapping", m,n
Step 8: Stop
2.6.3 Flowchart
Start
Read the values of m,n
Write "The values before swapping" m,n
m=m+n
n=m-n
m=m-n
Write " The values after swapping" m,n
Stop
2.7 Write a Python Program to Print the Ones Place of any given
Integer Number
2.7.1 Theory
Example: Consider the number 12345678. The place value for the
given number is
1 2 3 4 5 6
Hundred- Ten - Thousands Hundreds Tens Ones
Thousands Thousands
12345
123456
10 123450
6
10 yields the ones place of number.
2.7.2 Algorithm
Step 1: Start
Step 2: Write "Enter an Integer Number"
Step 3: Read n
Step 4: Temp n
Step 5: unit-digit tempt%10
Step 6: Write "The unit digit is"' unit-digit
Step 7: Stop
2.7.3 Flowchart
Start
Write "Enter an Integer Number"
Read n
temp = n
unit digit = temp%10
Write "The unit digit is", unit digit
Stop
Output:
2.8 Write a Python Program to compute the Area of a Triangle
when the Three Sides are given
2.8.1 Theory
The area of triangle can be calculated if the three sides are known. This
formula was given by Heon also know as Hero of Alexandria, a Greek
Engineer and Mathematician, 10-70 AD. The formula is given in
Equation (2.5).
A = s(s - a) (s - b) (s - c )
Where, s = (a + b + c ) / 2
Example: Consider a = 4 b = 6 and c = 8
(4+6+8)
Now s = =9
2
A = 9 x ( 9 - 4 ) x ( 9 - 6 ) x ( 9 - 8)
= 11.61
2.8.2 Algorithm
Step 1: Start
Step 2: Enter the values of sides a, b and c
Step 3: s= ( a + b + c ) /2
Step 4: Area = Sqrt(s*(s - a)*(s-b)*(s-c))
Step 5: Write "The area of Triangle is", Area
Step 6: Stop
2.8.3 Flowchart
Start
Read a, b, c
s = (a + b +c) / 2
Area = sqrt(s*(s - a)*(s - b)*(s - c)
Write "The area of Triangle is", Area
Stop
2.8.4 Python Program: Area-Triangle.py
Output:
Exercises
1. Is the output of the program correct?
Output:
2. Write the output of the following Python program.
Output:
Chapter 3
Python Programs on Control Structures
3.1 Decision Making
3.2 if Statement
Syntax
if test_expresion:
True statement block
rest of program statements
Flowchart
False
if (test_expression):
True
True statements block
Rest of program
Statements
3.3 Write a Python Program to Evaluate Body Mass of a Person to
Determine his Weight Status
3.3.1 Theory
Adolphe Quetelet provided a formula to compute the Body Mass Index
(BMI). This formula is independent of men and women.
BMI = Wt / (Ht*Ht)
Where, Wt is in kilograms (kg)
Ht is in meters
The Body Mass Index in Table 3.1.
Value Category
> = 30 Obese
3.3.2 Algorithm
Step 1: Start
Step 2: Read " Enter your height in meters", height
Step 3:Read "Enter your weight in kilograms", weight
Step 4: bmiweight / ( height * height)
Step 5: if bmi < 18.5
Step 5.1: Write “Your BMI indicates you are underweight”, bmi
Step 6: if bmi > = 18.5 and bmi <25
Step 6.1: Write “ Your BMI indicates you are normal weight”,
bmi
Step 7: if bmi > = 25 and bmi <30
Step 7.1: Write “Your BMI indicates you are overweight”, bmi
Step 8: if bmi . = 30:
Step 8.1: Write “ Your BMI indicates you are obese”, bmi
Step 9: Stop
Start
Read “Enter your height in
meters”, height
Read “Enter your weight in kilograms”, weight
Bmi weight / (height * height)
True
if bmi < 18.5 Write “underweight”
False True
if bmi > = 18.5 and Write “normal
bmi < 25 weight”
False True
if bmi > = 25 and Write
bmi < 30 “overweight”
False True
if bmi > =30 Write “obese”
False
Stop
Output:
3.4 if-else Statement
Sometime you need to make a two-way decision. That is, if the test-
expression is True then execute the True block of statements or else
execute the not True (False) block of statements.
Syntax
if test_expression:
True block statements
else:
False block statements
rest of program statements.
Flow chart
False
if (test_expression):
True False block statements
3.5.1 Theory
A common year has 365 days but a Leap year has 366 days. The
additional day is in form of 29th of February.
Case(ii):
A given year is not a Leap if it is evenly divisible by 4 and also evenly
divisible by 100.
Example(b): Consider the year 1900
1900 / 4 = 475
1900 / 100 = 19
Case(iii):
A given year is a Leap year if it is divisible by 4, evenly divisible by
400.
Example(c): Consider the year 1600.
1600 / 4 = 400
1600 / 100 = 16
1600 / 400 = 43.52
3.5.2 Algorithm
Step 1: Start
Step 2: Read the given year, year
Step 3: If (((year mod 4 equals 0) AND (year mod 100 not equals 0 ))
OR (year mod 400 equals 0)).
Step 3.1 : Write “Given year is a Leap Year”
Step 3.2 : goto Step 5
Step 4: Else
Step 4.1 : Write “Given year is not a Leap Year”
Step 5: Stop
Flow chart
Start
Read value for year
False
If (((year%4 = = 0) and
(year % 100 ! = 0)) or Write year is
(year % 400 = = 0)) not a leap year
Write year is a
leap year
Stop
Output:
3.6.3 Flowchart
Start
False
If a!=0
True
Enter the coefficient a,b and c
disc=(b*b-4*a*c)
True root1= (-b + sqrt (disc))/(2*a)
False True
Root1=-b/(2*a)
If disc = = 0 Root2 = -b/(2*a)
Write “Roots are real
andEqual”
False True
Stop
3.6.4 Python Program: QuadRoot.py
Output:
Example:
mark = 25
if marks > 25;
print " Highest score"
Print " Well Done"
3.7.1 Flowchart
Start
Stop
3.7.4 Python Program: BigOfThree.py
Output:
Syntax
if test_expression:
If block statements
elif test_expression:
elif block statements
elif test_expression:
elif block statements
else:
else block statements
Rest of program statement
Flowchart
if test_expression:
< 35 Failure
3.9.2 Algorithm
Step 1: Start
Step 2: Read "Enter the total of 6 subjects",m
Step 3: Per (m* 100)/ 600
Step 4: Write "You have scored", per "% of marks"
Step 5: If per < 35
Step 5.1: Write "Failure"
Step 6: Else If per >=35 and per < 50
Step 6.1: Write " Passed"
Step 7: Else If per > = 50 and per < 60
Step 7.1: Write "Second division"
Step 8: Else If per > = 60 and per < 70
Step 8.1: Write "First Division"
Step 9: Else
Step 9.1: Write "First class with Distinction"
Step 10: Stop
3.9.3 Flowchart
Start
Read "Enter the total of 6 subjects",m
Per = (m*100)/600
Write "You have scored",per "% of marks"
A
Else if False Write" First class
Per>=60and with distinction"
per < 70
True A
Write"First Stop
Division"
Output:
Note: Python does not have a switch or case statement.
3.10 Repitition Statements
while loop
for loop
The while loop is an entry condition based loop. First the entry
condition is checked. If it is true then rest of the statements in the while
loop are executed else the rest of the program statements are executed.
Syntax
while condition
statement 1
statement 2
Statement N
Flowchart
False
while condition:
True
statement 1
statement 2
statement N
3.11.1 Theory
3.11.2 Algorithm
Step 1: Start
Step 2: Read the value of num
Step 3: Initialize the variables
fact ← 1, count ← 1
Step 4: if num < 0
Step 4.1: Write Factorial of negative number does
not exist
Step 4.2: Go to Step 8
Step 5: if num == 0
Step 5.1: Write Factorial is 1
Step 5.2: Go to Step 8
Step 6: while count ≤ num repeat the following steps
Step 6.1: fact ← fact * count
Step 6.2: count ← count + 1
Step 7: Write the Factorial is, fact
Step 8: Stop
3.11.3 Flowchart
Start
fact = 1
count = 1
True
False
If num == 0 Write "Factorial is 1"
False
while count < = num False
True
fact = fact*count
count = count + 1
Stop
Output:
3.12 Write a Program in Python to Test Whether a given Number
is Prime or not
3.12.1 Theory
A natural number is mathematically known as a prime number if it has
only two positive divisors, one is 1 and the other the number itself.
3.12.2 Algorithm
Step 1: Start
Step 2: Read the value of num
Step 3: Initialize the variables
divisor 2, prime True
Step 4: while divisor num/2 repeat the following steps
Step 4.1.1: Prime False
Step 4.1.2: Write "not a Prime Number", num
Step 4.1.3: break
Step 4.2: divisor divisor + 1
Step 5 : if prime
Write "The given number is Prime", num
Step 6: Stop
3.12.3 Flowchart
Start
Enter a number ( num)
divisor = 2
prime = True
False
while divisor
< = num/2
True
If num % False
divisor = = 0
True
prime = False
Write num, "is not
a prime number"
break
divisor + = 1
False
if prime
True
num, "is prime"
Stop
3.13.3 Flowchart
Start
Enter a number (num)
i=0
fib0 = 0
fib 1 = 1
while False
i < num
True
True
if i < = 1 fibnext = 1
False
fibnext = fib0 + fib 1
fib0 = fib 1
fib 1 = fibnext
i=i+1
Write fibnext
Stop
Output:
3.14 Write a Program in Python to Compute Whether the given
Integer Number is a Palindrome
3.14.1 Theory
A number is said to be Palindrome whose digits when read backwards
are same as the original number.
Example: 121
3.14.2 Algorithm
Step 1: Start
Step 2: Read the value of num
Step 3: Initialize the variable
rev 0, temp num
Step 4: while temp >0 repeat the followiing step Step 4.1: rev
(10*rev) + temp % 10
Step 4.2: temp temp//10
Step 5: if rev = = num
Step 5.1: Write "The given number is a
Palindrom",num
Step 5.2: goto Step 7
Step 6: else
Step 6.1: Write"The given number is not a
palindrome",num
Step 7: Stop
3.14.3 Flowchart
Start
Enter a number
(num)
rev = 0
temp = num
while False
temp> 0
True
rev = (10*rev) + temp % 10
temp// = 10
True
if rev = = num num is
False Palindrome
num is not a
Palindrome
Stop
3.14.4 Python Program: Palindrome.py
Output:
Example 2: 153 = 13 + 53 + 33
1×1×1= 1
5 × 5 × 5 = 125
3 × 3 × 3 = 27
153
3.15.2 Algorithm
Step 1: Start
Step 2: Read the value of num
Step 3: Initialize the variables
sum 0, temp num
Step 4: while temp! = 0 repeat the following steps
Step 4.1: digit temp% 10
Step 4.2: sum sum + digit * digit * digit
Step 4.3: temp temp // 10
Step 5: if num = = sum
Step 5.1: Write "The given number is Armstrong", num
Step 5.2: goto step 7
Step 6: else
Step 6.1: Write"The given numberis not an Armstrong", num
Step 7: Stop
3.15.3 Flowchart
Start
Enter a number
(num)
sum = 0
temp = num
False
while temp
!=0
True
digit = temp % 10
sum + = digit *digit* digit
temp//=10
True
If num = = sum num is an
Armstrong No.
False
num is not an
Armstrong No.
Stop
Output:
Example:
3 6 9
3.16.3 Flowchart
Start
Read dec
pos = 1 bin = 0 n = dec
False
when n! = 0
True
rem = n% 2
bin = bin + rem * pos
n = n//2
pos = pos * 10
Stop
Output:
3.17 Write a Python Program to Convert a given Binary Number
to its Equivalent Decimal Number
3.17.1 Theory
Binary number system is based on base 2 and only two digits 0 and 1
exist. They find tremendous applications in Computer Systems. In
computer technology they are known as follows:
1 digit 1 bit
4 digits 1 nibble
8 digits 1 byte
1 0 1 0
23 22 21 20
= 1* 23 + 0* 22 + 1 * 21 + 0 * 20
=8+0+2+0
= 10
3.17.2 Algorithm
Step 1: Start
Step 2: Read the value for bin
Step 3: raise to 0, dec 0, n bin
Step 4: while n ! = 0 repeat the steps
Step 4.1: rem = n%10
Step 4.2: dec = dec + int (rem*math.pow(2,raise_to)
Step 4.3: n = n//10
Step 4.4: raise_to = raise_to + 1
Step 5: Write the value of dec
Step 6: Stop
3.17.3 Flowchart
Start
Read bin
dec = 0 raise_to = 0 n = bin
False
while n! = 0
true
rem = n% 10
dec = dec + rem * pow(2,raise_to)
n//= 10
raise_to = raise_to + 1
Syntax
Example:
Output:
Syntax:
range ( start , stop, [ step ] ) is used to iterate
over numbers in an incremental manner.
range ( stop ) : produces numbers from 0 to stop
-I
range ( start, stop) : produces numbers from
start to stop -I
range ( start, stop, step): Produces numbers
from start to stop - I and increments by step. It can be
both negative and positive but not zero.
Example:
Output:
Chapter 4
User-defined Functions
4.1 Introduction
Function_name
arg1 = 'param 1'
arg2 = 'param 2'
argn = 'param N'
Program statement
return
Output:
Output:
Output:
Here the arguments can be passed in any order to the called function as
long as the arguments have names. In case of keyword arguments, the
values can be of the form parameter_name,=<expr>instead of
just <expr>.
Output:
Note: **kargs is essentially a dictionary object. Thus all operations that
we perform on dictionary can be applied to **kargs. Thus we use
kargs.items ( ) to extract key value pairs.
Output:
Note: The out of the else part does not return any value. Thus Python
returns the type none.
Note: Immutable data types such as integers, floats, strings and tuples
are passed by value. A copy of the variable is passed and modification
to it is not reflected in the original variable.
Output:
Note:Mutable data types such as lists, dictionaries are passed by
reference. Thus they are modified inside a function and that
modification is reflected in the original mutable object type.
Output:
4.10 Anonymous Function in Python
Output:
In the above example lambda x: x * x is the
lambda function. Here x is the argument and x * x is the
expression that gets evaluated and returned.
The above function has no name (anonymous) and
it returns a function object which is assigned to the
identifier y. Thus we can now invoke it as a normal
function.
Lambda functions are generally used as argument
to a higher-order function, i.e., a function that takes in
other functions as arguments.
Output:
4.12.1 Theory
Least Common Mutiple (LCM) of two numbers is the
smallest number expect zero that is multiple of both.
Example:
= 6×8
2
= 24
4.12.2 Algorithm
Step 1: Start
Step 2: Read “Enter the value of a”, a
Step 3: Read “Enter the value of b”, b
Step 4: lcm (6, 8)
Step 5: Stop
Algorithm gcd(a,b)
Step 1: a 6 b 8
Step 2: if a < b
Step 2.1: t a
Step 2.2: a b
Step 2.3: b t
Step 3: r a % b
Step 4: while r ! = 0 repeat the following steps
Step 4.1: a = b
Step 4.2: b = r
Step 4.3: r = a % b
Step 5: return b
Start
↓
Read value of a,b
↓
lcm(a,b)
A ↓
Stop
lcm(a,b)
↓
a = 6, b = 8
↓
lst_com_mult
↓
A
gcd(a,b)
↓
a = 6, b = 8
↓ False
if a < b
↓ True
t=a
a=b
b=t
↓
r=a%b
↓ False
while r! = o
True ↓
a=b
b=r
r=a%b
↓
return b
Output:
Example:
Theory:
Output:
Chapter 6
Python Lists
6.1 Introduction
Output:
6.3 Accessing Elements of a List
Output:
6.6 Basic List Operations
Output:
6.7 Built-in List Functions
Output:
67.10.1 Theory
6.10.2 Algorithm
Step 1: Start
Step 2: Read “The range of list”,start,end
Step 3: even_sum 0
Step 4: odd_sum 0
Step 5: even_lst [ ]
Step 6: odd_lst [ ]
Step 7: for num in range (start, end + 1) repeat the following
steps
Step 7.1: If num mod 2 == 0
Step 7.1.1: even_sum even_sum + num
Step 7.1.2: odd_lst.append(num)
Step 7.2: else
Step 7.2.1: odd_sum odd_sum + num
Step 7.2.2: odd_lst.append(num)
Step 8: Write “Even numbers are”, even_lst,”even sum is”,
even_sum
Step 9: Write “Odd numbers are”,odd_lst, “odd sum is”,
odd_sum
Step 10: Stop
6.10.3 Flow chart
Start
Read range of list, start, end
even_sum 0, odd_sum0
even_lst [], odd_lst []
A
A
for num in range(start,end + 1)
Output:
6.11.1 Theory
Consider a given input_list [1, 2, 3, 4, 5]. Reversal of list
means arranging the elements in reverse order. That is,
elements are arranged as input_list [5, 4, 3, 2, 1].
Trace of the Program
i=0
For loop: is i < n/2, i.e., is 0 < 5/2, i.e, 0 < 2 YES
iteration 1
temp = input_list[i], i.e., temp = input_list[0], i.e., temp =1
input_list[i] = input_list[n – i- 1], i.e., input_list[0] =
input_list[5 – 0-1], i.e.,
input_list[0] = 5
input_list[n – 1 -1] = temp, i.e., input_list[4] = 1
thus the updated input_list[5,2,3,4,1]
i = i +1, i.e., i = 1
For Loop: is i < n/2, i.e., is 1< 5/2, i.e., 1 < 2 YES
Iteration 2
temp = input_list[i], i.e., temp = input_list[1], i.e.,
temp = 2
input_list[i] = input_list[n – i – 1], i.e., input_list[1] = input[5 –
I – 1], i.e.,
input_list[1] = 4
input_list[n – I – 1] = temp, i.e., input_list[3] = 2
Thus the updated input_list[5,4,3,2,1]
i = i + 1, i.e., i = 2
For Loop: is i < n/2, i.e., is 2 < 5/2, i.e., 2 < 2 No
Thus the final input_list = [5,4,3,2,1]
6.11.2 Algorithm
Step 1: Start
Step 2: Read “The number of elements to be reversed”, n
Step 3: input_list [ ]
Step 4: Write “Enter the elements of the list”
Step 5: for i in range (0,n) repeat the following steps
Step 5.1: read input( ) and append as i to input_list [ ]
Step 6: for I in range(n//2) repeat the following steps:
Step 6.1: temp input_list[i]
Step 6.2: input_list input_list[n – I – 1]
Step 6.3: input_list[n – I – 1] temp
Step 7: Write input_list
Step 8: Stop
6.11.3 Flowchart
Start
Read number of elewments, n
input_list = []
Write “Enter the elements”
for i in range(0,n)
input_list.append(input())
Write input_list
Stop
Output:
Iteration 2:
10 20 30 40 50 60
num_lst num_lst num_lst num_lst num_lst num_lst
[0] [1] [2] [3] [4] [5]
6.12.3 Algorithm
Step 1: Start
Step 2: Read “The number of elements in the list”, n
Step 3: num_lst [ ]
Step 4: Write “Enter the elements in ascending order”
Step 5: for i in range (0,n) repeat the following steps
Step 5.1: Read input and append to num_lst[ ]
Step 6: Write num_lst
Step 7: Read “The element to be searched”, element
Step 8: low 0
Step 9: high n – 1
Step 10: mid = (low + high)//2
Step 11: while low < = high repeat the following steps
Step 11.1: if num_lst[mid] == element
Step 11.1.1: Write “Element found”,
element, “Location”, mid + 1
Step 11.2: else if num_lst[mid] < element
Step 11.2.1: low mid + 1
Step 11.3: else
Step 11.3.1: high = mid – 1
Step 11.4: mid = (low + high)//2
Step 12: If low > high
Step 12.1: Write “No element found”
Step 13: Stop
6.12.3 Flowchart
Start
Read “No of Elements”,n
num_lst []
Write “Enter the elements in
ascending order”
for i in range(0,n)
num_lst.append(int(input()))
Write num_lst
Read “The element to be
searched”, element
low 0
high n – 1
mid = (low+high)//2
while low< = high
True
If num_lst[mid]== element Write element
found
False True break
If num_lst[mid]<element lowmid+1
high = mid – 1
mid = (low + high)//2
A
True Write
Element
If low > high not found
False
Stop
Output:
6.13 Write a Python Program to sort an Integer
List using Bubble Sorting Technique
6.13.1 Theory
Bubble sort compares the adjacent elements in the list at
each pass. Thus at the given pass the largest element
moves to the end of the list. Thus if we have near we end
up having n – 1 passes before the elements are sorted. It
is known as bubble as the smallest element “bubbles”
up.
Example:
Input_list [5, 3, 2, 4, 1] and n = 5
Outer For Loop: is i in range 0 to n, i.e., i =
0 < 5 YES
Inner For Loop: is j in range 0 to n – i – 1,
i.e., 0 < 5–0–1, i.e., 0 < 4 YES
Pass 1
If input_list[j] > input_list[j + 1], i.e., input_list[0] >
input_list[0 + 1], i.e., 5 > 3 YES
temp = input_list[j], i.e., temp = 5
input_list[j] = input_list[j + 1], i.e., input_list[0 = 3
input_list[j + 1] = temp, i.e., input_list[1] = 5
j = j + 1, i.e., j = 1
Updated input_list[3,5,2,4,1]
Inner Loop: is j in range 0 to n – i – 1, i.e.,1
< 5 – 0 – 1, i.e., 1 < 4 YES
If input_list[j] > input_list[j + 1], i.e. input_list[1] >
input_list[1 + 1], i.e., 5 >2 YES
temp = input_list[j] i.e., temp = 5
input_list[j] = input_list[j + 1], i.e., input_list[1] = 2
input_list[j + 1] = temp, i.e., input_list[2] = 5
j = j + 1, i.e., j = 2
Updated input_list[3,2,5,4,1]
Inner For Loop: is j in range 0 to n – i – 1, i.e., 2 <
5 – 0 – 1, i.e., 2 < 4 YES
If input_list[j] > input_list[j + 1], i.e.,
input_list[2] > input_list[2 + 1], i.e., 5 > 4
YES
temp = input_list[j], i.e., temp = 5
input_list[j] = input_list[j + 1], i.e.,
input_list[2] = 4
input_list[j + 1] = temp, i.e., input_list[3] = 5
j = j + 1, i.e., j = 3
Updated input_list[3,2,4,5,1]
Inner For Loop: is j in range 0 to n – i – 1, i.e.,
3 < 5 – 0 -1, i.e., 3 < 4YES
If input_list[j] > input_list[j + 1], i.e., input_list[3] >
input_list[3 + 1],i.e., 5>1 YES
temp = input_list[j],i.e., temp = 5
input_list[j] = input_list[j + 1], i.e., input_list[3] =1
input_list[j+1] = temp, i.e., input_list[4] = 5
j = j + 1,i.e., j = 4
Updated input_list[3,2,4,1,5] Note: The largest value is in
its right place
Inner For Loop: is j in range 0 to n - i - 1,
i.e., 4 < 5 - 0 - 1,i.e., 4 < 4 NO i = i + 1, i.e., i
=1
Outer For Loop: is i in range 0 to n, i.e., i =
1 < 5 YES
Inner For Loop: is j in range 0 to n - i - 1,
i.e., 0 < 5 - 1-1, i.e. 0 <3 YES
Pass 2
If input_list[j] > input_list[j+1], i.e., input_list[0] >
input_list[0+1], i..e., 3>2 YES
temp = input_list[j],i.e., temp = 3
input_list[j] = input-list[j=1],i.e.,input_list[0] = 2
input_list[j+1] = temp,i.e.,input_list[1] = 3
j = j=1,i.e., j = 1
Updated input_list[2,3,4,1,5]
Inner For Loop: is j in range 0 to n - i - 1,
i.e., 2 < 5 - 1 - 1, i.e., 1 < 3 YES
If input_list[j] > input-list[j+1],i.e. input-list[1]
> input_list[1+1],i.e., 3 > 4 NO
j = j+1, i.e., j =2
Updated input_list[2,3,4,1,5]
Inner Loop: is j in range 0 to n - i - 1, i.e., 2
< 5 - 1 -1, i.e., 2 < 3YES
If input_list[j] ? input_list[j+1],i.e.,input_list[2]
> input_list[2+1], i.e., 4 > 1 YES
temp = input_list[j], i.e., temp = 4
input_list[j] = input_list[j+1], i.e., input_list[2]
=1
input_list[j+1] = temp, i.e., input_list[3] = 4
j = j+1, i.e., j = 3
Updated input_list[2,3,1,4,5]
Inner Loop: is j in range 0 to n - i - 1, i.e., <
5 - 1 - 1, i.e., 3 < 3 NO
i = i + 1, i.e., i = 2
Outer for Loop: is in range 0 to n, i.e., i = 2
< 5 YES
Inner For Loop: is j in range 0 to n - i - 1,
i.e., 0 < 5 - 2 - 1, i.e., 0 < 2 YES
Pass 3
If input_list[j]> input_list[j+1],i.e.,
input_list[0] > input_list [ 0+1} , i.e., 2 > 3
NO
j = j + 1, i.e., j = 1
Updated input_list [2,3,1,4,5]
Inner For Loop: is j in range 0 to n - i - 1,
i.e., 1 < 5 - 2 - 1, i.e., 1 < 2 YES
If input_list [j] > input_list[j+1], i.e.,
input_list[1] > input_list[1+1], i.e., 3 > 1 YES
temp = input_list[j], i.e.,, temp = 3
input_list[j] = input_list[j+1], i.e., input_list[1]
=1
input_list[j+1] = temp, i.e., input_list[2] = 3
j = j + 1, i.e., j = 2
Updated input_list[2,1,3,4,5]
Inner For Loop: is j in range 0 to n - i - 1,
i.e.,, 2 < 5 - 2 - 1, i.e., 2 < 2 NO
i = i + 1, i.e., i = 3
Outer For Loop: is i in range 0 to n , i.e., i =
3 < 5 YES
Inner For Loop: is j in range 0 to n - i - 1,
i.e., 0 < 5 - 3 - 1, i.e., 0 < 1 YES
Pass 4
If input_list[j] > input_list[j+1],i.e.,
input_list[0] > input_list[0+1], i.e., 2 > 1 YES
temp = input_list [j],i.e., temp = 2
input_list[j] = input_list[j+1], i.e., input_list[0]
=1
input_list[j+1] = temp, i.e., input_list[1] = 2
j = j+1, i.e., j = 1
Updated input_list[1,2,3,4,5]
Inner Loop: is j in range 0 to n - i - 1, i.e., 1
< 5 - 2 - 1, i.e., 1 < 1 NO
i = i + 1, i.e., i = 4
Outer For Loop: is i in range 0 to n, i.e. i =
4 < 5 YES
Inner For Loop: is j in range 0 to n - i - 1,
i.e., 0 < 5 - 4 - 1, i.e., 0 < 0 NO
Final input_ list [ 1,2,3,4,5]
6.14.2 Algorithm
Step 1: Start
Step 2: Read the numbers of elements, n
Step 3: input_list [ ]
Step 4: for i in range (0,n) repeat the following steps
Step 4.1: Read the input ( ) and append to input_list [ ]
Step 5: Write input_list
Step 6: for i in range (0,n) repeat the following steps
Step 6.1: for j in range (0,n - i - 1) repeat the
following steps
Step 6.1.1: if input_list[j] > input_list[j+1]
Step 6.1.1.1: temp = input_list[j]
Step 6.1.1.2: input_list[j] = input_list[j+1]
Step 6.1.1.3: input_list[j+1] = temp
Step 7: Write input_list
Step 8: Stop
6.14.3 Flowchart
Start
Read "number of elements",n
input_list []
for i in range(0,n)
input_list.appendi(input( ) )
write input _list
for i in range (0,n)
for j in range (0,n-i-1)
False
If input_list [j] >
input_list[j+1]
True
temp = input_list[j]
input_list[j] = input_list[j+1]
input_list[j+1] = temp
Write input_list
Stop
6.15.1 Theory
3 5 2 4 1
Now j = 2
3 5 2 4 1
Now j = 3
2 3 5 4 1
Now j = 4
2 3 4 5 1
6.15.2 Algorithm
Step 1: Start
Step 2: Read "The number of elements in the List", n
Step 3: input_list [ ]
Step 4: for i in range(0,n) repeat the following steps
Step 4.1: Read the input ( ) and append to input_list [ ]
Step 5: Write "Entered List", input_list
Step 6: for i in range (1, len(input_list)) repeat the
following steps
Step 6.1: j i
Step 6.2: while j > 0 and input_list[j - 1] > input_list[j]
repeat the following steps
Step 6.2.1: temp input_list[j]
Step 6.2.2: input_list[j] input_list[j-1]
Step 6.2.3: input_list[j - 1] temp
Step 6.2.4: j j - 1
Step 7: Write "Sorted List:", input_list
Step 8: Stop
6.15.3 Flowchart
Start
Read "The no
of elements",n
input_list []
for I in range(0,n)
input_list.append(int(input))
Write input_list
for i in range (1,len(input_list))
j1
False
while j>0 and
input_list[j-1]>
input_list[j]
True
temp input_list[j], input_list[j] input_list[j-1],
input_list[j-1] temp, j j - 1
Output: