Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
15 views

Python Python 1

Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

Python Python 1

Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 159

CHAPTER 1

Basics of Python Programming

1.1 What is Python?

Python was visualized in the late 1980s. Its implementation began


in1989 by Guido Van Rossum from Netherlands. Python got its name
from "Monty Python's Flying Circus". Python 3.0 was released in the
year 2000. In brief Python is a multi-paradigm programming interpreted
programming language. This is because it supports, procedural
programming (structured), fully object-oriented programming and has
features that support functional programming.

Python is an interpreted language and Python programs are


executed by an interpreter. Python interpreter works in two modes, i.e.,
interactive mode and script mode. In the interactive mode, you type
Python statements and the interpreter displays the output.

>>> 8 * 4

>>> 32

In the script mode the interpreter executes the content of a file


which has an extension.py. Consider the first Python program named
HelloWorld.py which displays the string "Hello World!" and
"Welcome to Python Programming".
Iteration:

Iteration is a process of repeating the same set of statements again and


again until the specified condition holds true.

Output:

1.2 Python Keywords

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:

1.3 Python Variable


A variable is a name that refers to a value stored in memory location.
Rules followed for writing python variables are as follows.
 A python variable must begin with a letter (a-z, A-Z) or
underscore (-) followed by letters, numbers o underscore.
 Python variable are case sensitive ( variable name sum and sum
are two different variables)

happy_new_year valid variable


1_ happy_new_year valid variable
happy_new_year@ valid variable
1 _happy_new_year valid variable

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.

1.5 Python Data Types


Variables in Python are typeless. Python supports dynamic typing and
the variable type is decided at run type.
Python data types
Numeric Sequence Sets Mapping
int str set dict
float list frozen set
complex tuple
boolean
Figure 1.1 Python data types

To determine the data type of the variable use the type ( )


function in python.
Python program: Datatype.py

Output:
1.6 Python Literals

A literal is a notation that represents a fixed value.

1.6.1 Numeric Literals

They consist of digits (0-9) with an optional (+ or -) possibly a decimal


point.

Examples of integer literals are

10 3500 -4500 +220

Floating point literals are

10.0 3500.253 -4500.234 +220.034

Python uses double precision floating point representation


format as per IEEE754 with a range of
10-308 to 10308. It uses a precision of 53 bits to store floating point values
internally.

1.6.1.1. Arithmetic overflow error

A condition that occurs when a computation produces a result that is


greater than that data type variable can store.

Example: Write a Python program to stimulate an arithmetic overflow


error.
Output:

The output generated by the python program is inf (infinity).

1.6.2 String Literals

They represent a group of characters. They may be enclosed in a single


quote to double quote, 'Hello World !' or "Hello world !". There is no
difference between single quote and double quote in Python.We use
triple quotes in Python for writing a docstring. A docstring at the
beginning of a function explains its interface. It is a multiline string.

Example: Write a python to represent strings.


Output:

1.6.3 List of Literals in Python

Python supports the following types of literals:

Literal Type Example


Integer literals 10,11,.-12,-13
Floating point literals 5.6,-3.8.0.22
String literals "hello",'hi'
Complex number literals 2+4j,3-2j
List literals [], [ 1,2,.3 ]
Turple literals (), ( 1,2,3 )
Dictionary literals {}, {'a:', 8}
Set literals { 1, 2, 3, 4 }
Unicode literals u"xyz", u''''
1.7.4 Write a Python Program Add_Complex.py to Add Two Complex
Numbers c1 = 2 + 3j and c2 = 4 +7j
Output:

1.7 Python Constants

The following are built-in constants in Python:

 True - represents the true value of bool type


 False - represents the false value of bool type
 None - is used to represent the absence of value

1.7.1 Write a python program (TestBool.py) using Boolean Data


Types
Output:

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.

1.7 Python Operators

An operator is a special symbol that helps Operand


the user to write arithmetic o logical
computations. The operand specifies 2+3
the data that is to be manipulated by the
operator. Operator
1.8.1 Python Operators

Python supports the following arithmetic operators:

Operator Description Example


+ Addition operator >>>40+20
60
- Subtraction >>>40-20
operator 20
* Multiplication >>>40*20
operator 800
/ Division operator >>>40/20
2.0
// Floor Division >>>40//20
operator 2
% Modulus operator >>>3.5%1.0
0.5
** Exponentiation >>>40**20
operator 10995116277600000000
000

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.

1.8.2 Relational Operators

Python supports the following relational operators:

Operator Description Example


== Logical comparison >>> 40==20
False
!= Not equal to >>> 40! =20
True
> Greater than >>> 40 > 20
True
< Less than >>> 40< 20
False
>= Greater than equal to >>> 40 >=20
True
<= Less than equal to >>> 40 <= 20
False
1.8.2.1 Write a python program to demonstrate the use of logical comparison

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

Bitwise operation means working with individual bits of data.

For example, consider the number 22.Its representation in binary


is 10100.

1.8.4.1 Bitwise AND(&)

a B a&b
0 0 0
1 0 0
0 1 0
1 1 1

If one of the values is 0 the result of bitwise AND is 0. If both the


values are 1 then the result of bitwise AND is 1.

For example, consider 22&20.

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:

1.8.4.3 Bitwise XOR(^)


A b a^b
0 0 0
1 0 1
0 1 1
1 1 0
If only one of the values is 1 the result is 1 otherwise it is 0.
22 1 0 1 1 0
20 1 0 1 0 0
Result(22^20)= 0 0 0 1 0
2

Output:

1.8.4.4 Bitwise Not(~)


a ~a
0 1
1 0

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.

Example: Consider a value a = 22 and shift the same to right by 2 bits.

format ( ) is the new way of printing formated output in Python .

-indicates the current value which has not yet been assigned to a
variable in python.

1.8.4.6 Left shift operator (<<)

Here data is shifted to the left by the specified number of bits and the
trailing bits are replaced by zero.

Example: Consider a value a = 22 and shift the same to left by 2 bits.


1.8.5 Python Identity Operators

Python provides is and is not identity operators.These operators are used


to check the memory locations of the two objects.

 is: Evaluates True if the other variable of the is operator


points to the same object otherwise evaluates to False.

Example: 1

Example: 2

 is not: Evaluates True if the other variable of the is not


operator points to different object otherwise evaluates to
False.
Example: 1

Example: 2

1.8.6 Python Membership Operators

Python provides the membership operators for determining the presence


of items in a sequence such as Strings, Lists and Turples. There are two
membership operators:

 in: returns True if x is present in the sequence otherwise it


returns False.

Example:1
Example: 2

 not in: returns True if x is not present in the sequence others


False.

Example: 1

Example: 2
1.8.7 Type Conversion in Python

Conversion from one data type to another is known as typecasting.


Python provides the following functions to achieve the same.

 Conversion of string and Floating point to an Integer we


have int( ) function.

Example: 1

Example: 2

 Conversion of String and Integer to a Floating Point Number


we have Float ( ) function.

Example: 1
Example: 2

 Conversion of an Integer, Float, List, Turple and Dictionary


to string str ( ) function.

Example: 1

Example: 2
Example: 3

 Conversion of a String, Turple and Dictionary to List we


have list( ) function.

Example: 1

Example: 2
Example: 3

 Conversion of a String, List and Dictionary to a Turple we


have a function.

Example: 1

Example: 2
Example:3

1.8.8 Type Promotion (Coercion) in Python

 if one of the number is complex the other number is


converted to complex.
 If one of the operand is Float the other is converted to Float.
 If both numbers are Integer then no promotion is required.

Example:

1.9 Python Operator Precedence


A python expression is made up of values, variable, operators and
method calls. To evaluate an expression we come across precedence and
at times associativity.

 Precedence: Defines the priority of an operator and guides the


first sub-expression to be evaluated.
 Associativity: If there are two operators in an expression with
the same level of precedence, then associativity tells us whether
we have to evaluate the expression from left to right or right to
left.

Example: Consider the expression 2 + 3 * 4 - 5

Consider the operator precedence table and we observe *


operator has the higher priority. Thus we consider the sub-expression 3
* 4 and get a result 12. Now we observe that there are two more
operators + and - and as they have same precedence levels, we find
associativity from the precedence table. The associativity is from left to
right.

Thus the expression now become 2 + 12 - 5 and we evaluate 2 +


12first and get 14. Finally, we evaluate 14 - 5 which becomes 9.

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:

1.9.1 Python Expressions

Evaluate the following python expressions.


Example 1:
2+ 3 * 4 / / 5 - 17
Step 1: (3*4) = 12
Step 2: 12//5 = 2 ( Integer division)
Step 3: 2 +2 = 4
Step 4: 4 - 17 = - 13
Ans: - 13

Example 2:

2** 3 + 4//7 - 6*9

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

2.1 Input Statements in Python

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.

Suppose you want to have input as a integer or float, you can


convert them to integer by invoking the built-in functions like:

int( ): is a built-in function which is useful for converting an


input which is of string type to an integer.

Syntax

int ( x, base)

Example

>>> int ( '1010' , 2)

10

>>> int ( ' ' 25 ' ' )

25

float( ): is a built-in function which is useful for converting a floating


point number which is of string type to a floating point data type.

Syntax

float ( x )
Example

>>> float ( ' '1.23 ' ' )

1.23

>>> float ( ' '2 ' ' )

2.0

Example: Write a Python program to accept the name of an employee,


age, and salary. Note that name should be a string,age-should be an
integer and salary can be floating point value.

Program:

Output:
2.2 Output Statements in Python

2.2.1 Print ( ) function

As the program has to generate output to the standard console,


we have the print( ) function for the same.

Example: Write a Python program to accept your name and display


your name by appending it with a greeting.

Output:

In the above output it is observed that there is a space between


name and punctuation. This is because Python's print( ) function
introduced the same. Now suppose we do not want to have space after
the greeting and after the name we can use the + operator.
The following Programming example illustrates the concept.

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.

To overcome this constraint convert integer and float to string


with the str ( ) function.

Output:

Another way to remove space between strings is to use the


keyword parameter sep.

These parameter if not passed to a print ( ) function explicit


then the print ( ) function introduces a space by default. If the sep
parameter is specified as sep = ' ' in the print ( ) function then the
default space between argument is eliminated.

Example: Write a Python program to display name and Greeting by


eliminating the space between the multiple arguments.

Output:

2.3 Python String Formatting Options

Python provides us a way to format the output by using a format ( )


method which can be invoked by string, i.e., str.format ( )

str.format( ) method lets you concatenate elements together


within a string through positional formatting.

Example:
Output:

In the above program the placeholder was indicated curly braces


{ } and the value was passed by the string passed to format ( )
method.

Index numbers can be passed to curly braces which act as


placeholders to the sting.
Example:

Output:

We can format data types using the following syntax in curly


braces {field name: conversion} where, field name is the index
of the argument and conversion specifies the conversion types given
in
Table 2.1.
Table 2.1 Format Specification Types with Meaning

Type Meaning

'b' Represents binary format and the


number in base 2.
'c' Represents character and converts the
integer to the corresponding Unicode
character before printing. It accepts
integer or single character string.
'd' Represents decimal Integer and the
number in base 10.
'o' Represents octal number format and the
number in base 8.

'x' Represents number in hex format and


the number in base 16, using lower case
letters for the digits above 9.
'X' Represents number in hex format and
the number in base 16, using upper case
letters for the digits above 9.
'e' Represents the number in scientific
notation using the letter 'e' to indicate
the exponent and the default precision is
6.
'E' Represents the number in scientific
notating and uses an uppercase 'E' to
indicate the exponent and the default
precision.
'f' Represents the number as fixed point
number and the default precision is 6.
'F' Represents the number as fixed point
number but converts nan to NAN and inf
to INF.
's' Represents the value in String format.
'%' Represents the number in percentage
format, i.e., multiplies the number by
100 and displays in fixed('f') format,
followed by a percent sign.

Flowchart Symbols

A flowchart is drawn using different kinds of symbols. Every symbol


used in a flowchart is for specific purpose.

Table 2.2 Different symbols of the flowchart along with their names

Symbol Symbol Name Description

Process Operation or action step

Alternate to normal
Alternate Process
Process

Decision Decision or a branch

Input/Output(I/O) to or
Data
form a process
Pre defined Process previously
Process specified

Internal Storage Stored in memory

Document A document

Multi Document Multi Document

Terminator Start or Stop Point

Preparation Set-Up-Process

Manual Input Data entry from a form

Manual Operation Operation to be done


manually

Connector Join Flow Lines

Off-Page Continue on another page


Connector

Card I/O from a punched card

Summing Junction Logical AND


OR logical OR

Collate Organize in a format

Sort Sort in some order

Merge Merge in a predefined


order

Stored Data General Data Storage

Delay Wait

Sequential access Stored on magnetic step


storage

Magnetic disk I/O from magnetic disk

Direct access Storing on hard disk


Storage

Display Display Output

Flow lines Indicates the direction of


flow
Difference between Algorithm, Flowchart and Pseudocode

S.No ALGORITHM FLOWCHART PSEUDOCODE

1 An algorihthm is Flowchart is a Pseudocode is a


a sequence of pictorial readable, formally
steps used to representation of styled English like
solve a particular an algorithm to language
problem. solve a particular representation of
problem. to algorithm.

2 It can be It uses different It uses structured


represented using kind of boxes constructs of the
a flowchart or a and lines for programming
Pseudocode. representation. language for
representation.

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

C=(F -32) *5.0/9.0

Write "temperature in
Celsius", C

Write temperature in
Celsius, C

F=9.50/ 5.0* C+32

Enter "temperature in
Fahrenheit", F

Stop
2.3.1.4 Python program: TempConv.py

Output:

2.4 Python Math Library

Python provides useful mathematical function in a math library. This


library is implemented as a module. Some of the functions provided in
the math library are specified in Table 2.2.

Table 2.2 Math Built-In Functions Supported in Python


Name Description
sqrt(x) Returns the square root of x
pow(x,y) Returns x raised to y
log10(x) Returns the base 10 logarithm of x
pi Returns the mathematical constant π =
3.141592
e Returns the mathematical constant e=
2.718281
ceil(x) Returns the smallest integer value
greater than or equal to x.
fabs(x) Returns the absolute value of x.
factorial(x) Returns the x factorial
sin(x) Returns the sine of x in radians
cos(x) Returns the cosine of x in radians
tan(x) Returns the tangent of x in radians
radians(x) Converts the angle x from degrees to
radians
degrees(x) Converts the angle x from radians to
degrees

Note: The above mathematical library functions are supported as of


Python version 3.1.2.

Example: Write a python program to demonstrate the usage of built-in


mathematical functions.
Output:

2.5 Write a Python Program to compute Simple Interest (SI) and


compound Interest (CI) for a given Principal, rate of Interest and
Duration in years

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

Example 2: Imagine Mr. X has borrowed 1000 rupees at the rate of


10% Compound 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.
CI = 1000* [(1+10/100)5)]-1 = 610.51
Thus he has to pay (P) + CI = 1000 + 610.51 = 1610.51 rupees.
Note: Simple Interest is same as the compound Interest for the first
year.

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

2.5.3 Flow chart


Start

Read the values of
P, r and t

si = (p*t*r)/100


Write si


ci = p*(pow((1+r/100),t)-1)


Write si


Stop

2.5.4 Python Program: InterestCalc.py

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.

Example 1: Consider two variables m = 20, n = 10.


m = m + n = 20 + 10 = 30
n = m - n = 30 -10 = 20
m = m - n = 30 - 20 = 10
Thus the final value of m = 10 and n = 20 which have been
swapped without using a third variable.

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.6.4 Python Program: Swap_direct.py


Output:

2.7 Write a Python Program to Print the Ones Place of any given
Integer Number

2.7.1 Theory

Decimal numbers from 0-9 can be represented by their place values.

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

The modulo operator % yields the remainder from the division


of the first argument by the second.

Example: 123456% 10 Thus the modulo operation performed on a


number with a value.

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

2.7.4 Python Program: Unit.digit.py

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:

3. Write a Python program to generate a Hour Glass Format.


Output:
Answer:

Chapter 3
Python Programs on Control Structures
3.1 Decision Making

In many programming situation we come across situation where, we


need to take a decision and execute a set of statements based on that
decision.

3.2 if Statement

The if statement is one of the most simple decision making statements.


It has the following syntax.

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.

Table 3.1 BMI values and category

Value Category

< 18.5 Underweight

< = 18.5 and < 25 Normal Weight

> = 25 and < 30 Overweight

> = 30 Obese

Example: If Raju has a weight of 80 kg and Height of 1.788 meters (5


feet and 10 inches) then

BMI = 80 / (1.788*1.788) = 25.02

Thus Raju is Overweight.

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: bmiweight / ( 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

3.3.3 Flow chart

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

3.3.4 Python Program: Weight_Height.py

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

True block statements



Rest of program Statements

3.5 Write a Python Program to Compute Whether a given year is a


Leap Year or not

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.

How to compute a Leap year


Case(i):
A given year is a Leap year if it can be divided evenly by 4 and not by
100. This is the general principal which says that are divisible evenly by
4 and not by 100 are Leap years.
Example(a): Consider the year 2016. It is evenly divisible by 4 and not
evenly divisible by 100.
2016 / 4 = 504
2016 / 100 = 20.16

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

3.5.4 Python Program: Leap Year.py

Output:

3.6.3 Flowchart
Start

Enter the coefficient a

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)

If disc > 0 root2 = (-b + sqrt (disc))/(2*a)

Write “Roots are real and distinct”

False True 

Root1=-b/(2*a)
If disc = = 0 Root2 = -b/(2*a)
Write “Roots are real
andEqual”
False True 

If disc < 0 Real = -b / (2*a)


Imag =sqrt ( fabs(-

disc))/(2*a)

Write “The equation is


Not quadratic”

Stop
3.6.4 Python Program: QuadRoot.py
Output:

Example:
mark = 25
if marks > 25;
print " Highest score"
Print " Well Done"

3.7 Write a Python Program to Find Largest Among Three Integer


Numbers

3.7.1 Flowchart

Start

Read the values of a, b and c

if a > b False big = b


True
big = a

if c > big False


True
big = c

Write the biggest


among the three
a, b and c is big

Stop
3.7.4 Python Program: BigOfThree.py
Output:

3.8 if-elif-else Statement

Multi-way election is possible in Python through the if-elif-else


statement. The test_expression is evaluated one by one. If one of them
is true then the corresponding statement/statements are executed and the
control goes to the rest of the program statements. If none of the test-
expressions are true the last else statement and its corresponding
statements are executed.

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:

if block statements elif


test_expression:

elif block statements

else block statements

Rest of program statements


3.9 Write a Python Program to Compute the Percentage and Class
of Students given the Average of Six Subject Marks. The Maximum
Mark for each Subject is 100 Marks
3.9.1 Theory
The average marks of a student in six subjects with a maximum of 100
in each subject, helps us to compute the percentage of marks and the
corresponding class.
Example: Raju scored a total marks of 365 in 6 subjects.
percentage = (365 * 100) / 600
= 60. 833
The class of the student, i.e., First Division is based upon Table
3.2.
Table 3.2 Percentage Range and Class

Percentage Range Class

< 35 Failure

> = 35 and < 50 Passed

> = 50 and < 60 Second Division

> = 60 and < 70 First Division

> = 70 First class with


Distinction

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"

Else if False Else if False False


If per <35 per>=35 and per>=50 and
per<50 per < 60

True True True

Write"Failure Write "Passed" Write


"Second division

A
Else if False Write" First class
Per>=60and with distinction"
per < 70

True A
Write"First Stop
Division"

3.9.4 Python Program: Ifelse.py

Output:
Note: Python does not have a switch or case statement.
3.10 Repitition Statements

At times in programming you need to excuse a set of statements


repeatedly based on some conditions. These are accomplished by
looping constructs. Python provides two loop constructs.

 while loop
 for loop

3.10.1 while 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

Rest of program statements


3.11 Write a Program in Python to Compute the Factorial for a
given Number

3.11.1 Theory

Factorial of number is a positive integer n denoted as n! is given as n! =


n*(n - 1 ) * (n - 2)... 2*1. Factorial is defined by the recurrence
relation given by the Equation (6.3).
Example: 5 = 1 × 2 × 3 × 4 × 5 = 120

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

Enter a number (num)

fact = 1
count = 1

True

If num < 0 Write" Factorial


does not exist"

False
If num == 0 Write "Factorial is 1"

False
while count < = num False

True
fact = fact*count
count = count + 1

Write "Factorial is", fact

Stop

3.11.4 Python Program: Factorial.py

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.12.4 Python Program: Prime.py


Output:

3.13 Write a Program in Python to Generate Fibonacci Series for a


given Number
3.13.1 Theory
Fibonacci series is a series of numbers given 0 1 1 2 3 5 8 13 21 ...
where, the next number is the sum of the previous two numbers.
Fibonacci numbers is given by the recurrence relation given in
Equation( 6.4).
Fn= Fn-1 + Fn-2
where, F0 = 0, F1= 1
3.13.2 Algorithm
Step 1: Start
Step 2: Read the value of num
Step 3: Initialize the variables
i  0, fib 0  0, fib 1  1
Step 4: while i < num repeat the following steps
Step 4.1: if i  1
Step 4.1.1: fibnext  i
Step 4.1.2: goto Step 4.3
Step 4.2: else
Step 4.2.1: fibnext = fib0 +fib 1
Step 4.2.2: fib0 = fib 1
Step 4.2.3: fib 1 = fibnext
Step 4.3: i  i + 1
Step 4.4: Write fibnext
Step 5: 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

3.13.4 Python Program: Fibonacci.py

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:

3.15 Write a Program to Compute Whether a given Number is an Armstrong


number
3.15.1 Theory

Armstrong numbers also known as Narcissistic numbers are positive


integers whose value equals the sum of cubes of its digits.
Example 1: Num = 370
Digits of 370 are 3, 7 & 0
Cubes of individual digits = 33 + 73 + 03
sum of cubes of individual digits = 27 + 343 + 0 =
370
Num = = Sum
Thus 370 is an Armstrong

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

3.15.4 Python Program: Armstrong.py

Output:

3.16 Write a Python Program to Convert a given Decimal Number


to its Corresponding Binary Number
3.16.1 Theory

Decimal Number System: Is a number system which is to the base 10


and is also based on the familiar Hindu Arabic numeral system. It is
positional numeral systems with digits ranging from { 0,
1,2,3,4,5,6,7,8,9}.

Example:

3 6 9

Hundreds Tens Units

Binary Number System:

Is a number system which is to the base 2 and consists of two


digits { 0,1}. It has tremendous applications in digital electronics and
serves as the foundation of modern computer systems.

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

when " The value


of bin"

Stop

3.16.4 Python Program: DecToBin.py

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

Each digit in binary which represents 1 represents a value which


is of the power of 2 and 0 represents 0.

Example: Conversion of (1010)2 to (?)10

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

Write the value


of dec

Stop

3.17.4 Python Program: Bin_to_Dec.py


Output:

3.18 for loop

For loop is considered as an advanced form of while loop. It works like


an iterator loop allowing you to iterate through a string, list, tuple or
dictionary.

Syntax

for value in sequence:


statement 1
statement 2
statement N
Rest of the program statements

Example:
Output:

 The range ( ) function is associated with the for loop.

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

Python enables users to define their own functions. These functions as


user-defined functions are a logical grouping of code that can be
invoked by a name as and when required and as many times as required.
Advantages of functions

1. They make your code modular rather than monolithic.This is helpful


for debugging your code.
2. These functions are reusable in nature and can be invoked any
number of times.
3. A user-defined function can be developed independently by
developers thereby promoting rapid application development.
4. A program divided into functions is easier to understand.
5. A program divided into functions is easier to maintain.
4.2 Syntax of User-defined Function

def function_name (arg1 , arg2 ; ...... argn)


program statement 1
program statement 2
...
...
program statement n
return
Flow chart
Start

Function_name(arg1, arg2,....argn)

Program statement

Stop

Function_name

arg1 = 'param 1'
arg2 = 'param 2'
argn = 'param N'

Program statement

return

Example: Write a Python program that accepts two integer numbers


and returns the maximum integer value.

Output:

4.4 Return statement


Every Python function returns a value. The syntax is
return [expression]
The return statement evaluates the expression and returns the value to
the caller of the function. If there is no expression and returns the value to the
caller of the function.If there is no expression for the return statement or no
return statement itself then the type of the value returned is none.

Example: Write a Python program to demonstrate return statement.

Output:

4.5 Function Arguments in Python


Arguments to function in Python can be classified into the following
types:
 Positional arguments
 Keyword arguments
 Variable_length arguments

4.5.1 Positional Arguments

These essential arguments need to be passed to a function when they are


invoked. The type, order and number of arguments in the invoked
function should match the parameters in the function definition.
Note: Arguments are part of function calls whereas parameters are part
of function definition.

Output:

Here val is assigned 1, val2, is assigned 3. Each arguments is


matched with a parameter. If there is no match an error is generated.
Example: pos_param (val1, val2, val3) expects three arguments
and if we invoke pos_param (1, 2) an error is generated as follows:

4.5.2 Keyword Arguments

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

Note: When you have parameter_name =<expr> in function


definition, it is default value for a parameter when no value is provided
in the invocation; when you have parameter_name =<expr> in the
invocation, it is supplying a value overriding the default for that
parameter_name, i.e., the key word parameter.

Example: Write a Python program to demonstrate keyword parameter.


Output:

In the aforementioned program the arguments can be passed in


any order and the possible because of passing Keyword arguments.

4.5.3 Variable_length Arguments

In Python you can pass a variable_length of arguments to a function


using *args and **kargs
 *args: *args is used when you want to send non-keyword based
arguments list to a function.

Example: Write a Python program to demonstrate *args type


variable_length argument lists.
Output:

 **kargs: Provides a variable length argument list for keyword


arguments.

Example: Write a Python program to demonstrate the usage of **kargs.

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.

4.6 Default Parameter

A default parameter has the form parameter = expression. When such a


parameter exists the function call can skip the arguments for default
parameters for they will be substituted.

Example: Write a Python program to demonstrate default parameters.

Output:
Note: The out of the else part does not return any value. Thus Python
returns the type none.

4.7 Call-by-value vs. Call-by-reference in Python

In call-by-value a copy of actual arguments is passed to respective


formal arguments. Any changes made to the formal arguments will not
be visible outside the scope of the function.
In call-by-reference the location (address) of actual arguments
is passed to formal arguments, hence any change made to formal
arguments will also reflect in actual arguments.

Example: Write a Python program to demonstrate call-by-value.


Output:

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.

Example: Write a Python program to demonstrate call-by-reference.

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.

Python variable are actually object reference, i.e., the variable


stores the memory address of a variable and not the actual value of the
variable. Thus Python functions support what is called call-by-object-
reference. The Python interpreter looks at the type of object reference,
if the variable represents a mutable type, then call-by-reference applies
or if the variable in immutable type then call-by-value applies.

4.8 Nested Functions in Python

In Python programming language we can define a function inside


another function. This is known as nesting of the functions. The basic
level is known as encapsulation whereby the inner function is hidden
from the global scope.

Example: Write a Python program to demonstrate the working of


nested functions.
Output:

Note: Invoking inner_add (10) will result in error.

Nested functions can access the variables of the


enclosing scope. However these variables are read-only.
If we need to modify these variables we need to define
them with the keyword nonlocal.

4.9 Closure Function in Python

When a function retains an access to a local variable


even though the scope access to exist, it is known as
closure.
Example: Write Python program to demonstrate the
usage of closure.

The above program defines an outer function


outer_add ( vall ) with a parameter vall and a nested
function inner_add ( ). The nested inner_add ( ) has
access to vall even through vall is not local to inner_add (
). The function outer-add (vall) returns a closure
containing a copy of the value of vall, and the function
inner-add( ), which adds the value of vall with value 5
and stores it in va12. Thus a closure is a function object
together with an environment.

Output:
4.10 Anonymous Function in Python

Anonymous functions are also known as lambda function


in Python. The lambda function can have multiple
arguments but only one expression.
Syntax
lambda args : expr

Example: Write a Python program to demonstrate the


use of lambda function.

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.

4.11 Function Composition in Python

Function composition is a way of combining functions


such that the result of each function is passed as the
argument of the next function
For example, the composition of two functions p
and q is denoted as p ( g(x) ), x is the argument of q, the
result of q is passed as the arguments of p and the result
of the composition is the result of p.
Example: Write a Python program to demonstrate
function composition.

Output:

In the above program first dec (10) is invoked


which return the value 10 – 1, i.e., 9. This value is
inputted to square (9) which is 81.

4.12 Write a Python Program using Functions to Compute


the Least Common Multiple (LCM) of Two given Integers

4.12.1 Theory
Least Common Mutiple (LCM) of two numbers is the
smallest number expect zero that is multiple of both.

Example:

(i) Compute LCM of 6 and 8.


Multiples of 6 are:
6, 12, 18, 24, 30, 36, 42, 48, 54, 60.
Multiplies of 8 are:
8, 16, 24, 32, 40, 48, 56, 64, 72, 80.

Thus the Least Common Multiple of 6 and 8 is 24.


To find easily the LCM of two numbers a and b, given that
we are able to compute the GCD of those two numbers
with Equation (4.2).
a× b
LCM (a,b) =
GCD (a,b)
(ii) Compute the LCM of two numbers 6 and 8.
First GCD (6, 8) = 2
Now
6 × 8
LCM (6, 8) =
GCD (6, 8)

= 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 lcm (a, b)


Step 1: a 6 b 8
Step 2: y (a × b)/gcd(a, b)
Step 3: Write Least Common Multiple, y

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

4.12.3 Flow chart

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

4.12.4 Python Program: lcm.py

Output:

4.13 Recursive Function in Python


A recursive function is a function that cells itself one or
more times until it encounters a base case which
prevents further recursion. A base is case which leads to
problem solution without further recursion. If base case is
missing the recursive calls may head to infinity.
“Recursion in computer science is a method where,
the solution to a problem is based on solving smaller
instances of the same problem”.

Example:

(1) Write a Python program to compute factorial of a


number using recursion.

Theory:

Factorial of number is a positive integer n denoted as n!


is given as n! = n × (n – 1) ×(n – 2) … 2 × 1

Python Program: FactRecursive.py


Output:

(2) Write a Python program to compute the Fibonacci


series using recursion.
Fibonacci sequence numbers are 0, 1, 2, 3, 5, 8, 13, …

In mathematical terms, the sequence Fn of Fibonacci


numbers is defined by the recurrence relation
Fn = Fn -1 + Fn-2

Where, F0= 0 and F1 = 1 (initial values)

fib(4) = fib(3) + fib(2) i.e., fib(4) = 2 + 1 = 3


fib(3) = fib(2) + fib(1) i.e., fib(3) = 1 + 1 = 2
fib(2) = fib(1) + fib(0) i.e., fib(2) = 1 + 0 = 1
fib(1) = 1
fib(0) = 0
Python Program: FiboRecursive.py

Output:
Chapter 6
Python Lists
6.1 Introduction

In Python a sequence is considered as generic term for


an ordered set. The examples of data structures which
are types of sequences are list, tuples and strings.
List is considered as the most versatile sequence
type data structure. It is mutable. i.e., the elements of
the list can change over a period of time.
Example:

The elements of the list need not be of the same


type. It can be an integer, float, string, etc.

6.2 How to Read a List Type from a Keyboard

The following Python progarm demonstrates how to read


from the keyboard.

Example: To read elements of a List with a for loop and


with append( ) function.

Output:
6.3 Accessing Elements of a List

We can access elements of a list with square brackets [ ]


and a index value. The index value for lists begins with
the value 0 in Python.

Example: A Python program to demonstrate the access


of list elements
Output:

6.4 Modifying Elements of a List

List are mutable, i.e., they can be modified. List can be


modified as a single object or through slice operations.

Example: A Python program to demonstrate list


modification.
Output:

6.5 Deleting Elements of a List

The del statement can be used to remove a single


element or all element through slice operation.

Example: Python program to demonstrate deletion of


elements in a List.

Output:
6.6 Basic List Operations

 Concatenation: You can concatenate two lists with


the help of
+ operator
Syntax
List1 [ ] + list2 [ ]
This returns a new concatenated list containing all
the elements of list1 and list2.
 Repetition: You can repeat the object of the list
with the * operator.
Syntax
List1 [ obj ] * 3
This returns a new list [obj, obj, obj]
 Length of the list: You can get the length of the
list with the built-in function len( )
Syntax
List = [obj1, obj2, … objn]
len (list)
This method returns the length of the list.
 Return the delected element of a list: You can
delete and return the specified element from the list
using the pop ( ) method.
Syntax
list = [obj1, obj2, … objn]
item = list.pop (index)
 Membership: The membership operator in returns
True if the element is in the list else it returns
False.
Syntax
Element in list [obj1, obj2, … objn]

Example: Python program to demonstrate basic list


operations.

Output:
6.7 Built-in List Functions

 len(list): returns the number of items in a list.


 max (list): returns the element from the list which
has the maximum value.
 min (list): returns the element from the list which
has the minimum value.
Note: cmp ( list1, list2) is no longer supported in Python 3.0.

 list (sequence): This built-in function returns the


input sequence as a list.

Example: Write a Python program to demonstrate the


built-in functions for lists.
Output:

6.8 Python List Methods

 list.insert (index,element): This list method inserts


the element at the specified index by shifting the
elements to the right.
 list.index (element): This list method searches for the
specified element from the start and if the element is
found it returns the index or else rreturns an error.
 list.remove (element): This list method searches for
the first instances of the element and removes it from
the list else generates an error.
 list.append (element): This list method adds a
element to the end of the list.
 list.count(element): This list method counts how
many times the element occurs in the list.
 list.sort( ): This list method sorts the elements of the
list in place.
 list.extend(listA): This list method adds the elements
of listA at the end of the list with which the extend
method was invoked.
 list.reverse( ): This list method reverse the elements
of the list in place.
 list.pop(element): This list method removes and
returns the element specified by the index.

Example: Write a Python program to demonstrate List


methods.

Output:

6.9 Python List Duplication and Comparison of Two


List:
Python List Duplication
 One way to copy lst1 to lst2is to use the slice
operator. For example, consider lst1 = [1, 2, 3, 4].
If we say lst2 = lst1[:]. Then this statement will
result in lst2 being an identical copy of lst1. Slicing
a portion of a create a new list, and copy the
portion of the original list into this new list.
 The other way is let lst1 = [1, 2, 3, 4] and then we
say lst1, list (lst1), i.e., we use the built-in function
list( ) which constructs a list based on the passed
sequence.

Comparison of Two Lists


 The == logical comparison can be used to check
whether the two lists are equal. The result of
comparison is True or if two elements of two lists are
not same results.

Example: Write a Python program to demonstrate list


duplication and comparison.
Output:

6.10 Write a Python Program to Compute the Sum


of Odd and Even Numbers for a given Range Range
in a List:

67.10.1 Theory

Even Number: An integer when divided by 2 and has a


reminder 0 is said to be an even number.
Example: 2 % 2 = 0. We use modulus operator as it
returns the reminder. Sum of even numbers is then
computed by adding the even numbers.
Odd Number: An integer when divided by 2 and has a
reminder of 1 is said to be an odd number.
Example:

(i) 3 % 2 = 1. Sum of odd numbers is then


computed by adding the odd numbers.
(ii) Consider the list of numbers L = [1, 2, 3, 4, 5, 6,
7, 8, 9, 10]
Then Even_lst = [2, 4, 6, 8, 10] as all these numbers
when divided by 2 have a remainder 0, even_sum
= 30.
Similarly, odd_lst = [1, 3, 5, 7, 9] as all these
numbers when divided by 2 have remainder 1,
odd_sum = 25.

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_sum0
even_lst  [], odd_lst []

A

A

for num in range(start,end + 1)

even_sum even_sum+num if num mod2


even_lst.append==0

Odd_sum  odd_sum + num
Odd_lst.append(num)

Write “Even numbers are”, even_lst


“even sum is”, even_sum

Write “Odd numbers are”, odd_lst
“odd sum is”, odd_sum

Stop

6.10.4 Python Program: SumOddEven.py

Output:

6.11 Write a Python Program to Reverse the


Members of a given List

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

for i in range (0, n//2)



temp = input_list[i]

input_list[i] = input_list[n – i – 1]

input_list[n-i-1] = temp

Write input_list

Stop

6.14.4 Python Program: Reverse_list.py

Output:

6.12 Write a Python Program to Search a given


Element in an Integer List using Binary Search
Technique
6.12.1 Theory
Binary search requires that the list be in sorted order. To
begin with, search the element in the middle of the list. If
it is found we print success along with the element and
position. If the element is not there in the middle of the
list and is greater than the middle, then we search in the
upper position of the list or else we search in the lower
portion of the list and go on looking in the middle of the
new portion array until we find the element or else if the
if the element is not available in the search list we say
so.

Example: Consider the following list of six elements,


Element to be searched is 50.
Iteration 1:
num_lst[]
low = 0
high = n – 1 = 6 -1 = 5
mid = (low + high)/2 = (0 + 5)/2 = 2 (Integer division)
num_lst[2] == 30 is < 50
So now low = mid + 1, i.e., low = 3
Iteration 2:
high = 5
mid = (low + high)/2 = (0 + 5)/2 = 2 (interdivision)
num_list[4] = 50 which is equal to our search element
at location 5
Iteration 1:
10 20 30 40 50 60
num_lst num_lst num_lst num_lst num_lst num_lst
[0] [1] [2] [3] [4] [5]

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 lowmid+1


high = mid – 1

mid = (low + high)//2
A
 True Write
Element
If low > high not found
False 
Stop

6.12.4 Python Program: Binary_Search.py

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.14.4 Python Program: Bubble_Sort.py


Output:

6.15 Write a Python Program to Sort an Integer


List using Insertion Sorting Technique

6.15.1 Theory

In insertion sorting the adjacent elements are compared


and then inserted in the right place and this is repeated
until all the elements are placed in proper place.

Example: consider input_list [ 5,3,2,4,1]


j = 1 and number of elements in the list are five.

5 3 2 4 1

Since 3 > 55 interchange their places

3 5 2 4 1
Now j = 2

3 5 2 4 1

Is 2 > 5 interchange their places


3 2 5 4 1

Is 2 < 3 interchange their places


2 3 5 4 1

Now j = 3

2 3 5 4 1

Is 4 < 5 their interchange their places


2 3 5 4 1

Now j = 4
2 3 4 5 1

Is 1 < 5 then interchange their places


2 3 4 1 5

Is 1 < 4 then interchange their places


2 3 1 4 5
Is 1 < 3 then interchange their places
2 1 3 4 5

Is 1 < 2 then interchange their places


1 2 3 4 5

Final sorted list is


1 2 3 4 5

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

j1

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

Write "Sorted List:"


input_list

Stop
6.15.4 Python Program: Insertion.Sort.py

Output:

You might also like