Semester i - Problem Solving and Python Programming (Ge8151)_compressed
Semester i - Problem Solving and Python Programming (Ge8151)_compressed
Engineering
DEPARTMENT VISION
To create eminent professionals of Computer Science and Engineering
by imparting quality education.
DEPARTMENT MISSION
M1: To provide technical exposure in the field of Computer Science
and Engineering through state of the art infrastructure and ethical
standards.
M2: To engage the students in research and development activities in
the field of Computer Science and Engineering.
M3: To empower the learners to involve in industrial and multi-
disciplinary projects for addressing the societal needs.
Department of Computer Science and Engineering
PROGRAM EDUCATIONAL OBJECTIVES
Our graduates shall
PEO1: Analyse, design and create innovative products for addressing
social needs.
PEO2: Equip themselves for employability, higher studies and research.
PEO3: Nurture the leadership qualities and entrepreneurial skills for their
successful career .
PROGRAM SPECIFIC OUTCOMES
Students will be able to
PSO1: Apply the basic and advanced knowledge in developing software,
hardware and firmware solutions addressing real life problems.
PSO2: Design, develop, test and implement product-based solutions for
their career enhancement.
K.RAMAKRISHNAN COLLEGE OF
ENGINEERING ,TRICHY
INSTITUTE VISION
To achieve a prominent position among the top technical institutions.
INSTITUTE MISSION
M1: To bestow standard technical education par excellence through
state of the art infrastructure, competent faculty and high ethical
standards.
M2: To nurture research and entrepreneurial skills among students in
cutting edge technologies.
M3: To provide education for developing high-quality professionals to
transform the society.
Program Outcomes
Engineering knowledge:
Apply the knowledge of mathematics, science, engineering
fundamentals, and an engineering specialization to the solution of complex
engineering problems.
Problem analysis:
Identify, formulate, review research literature, and analyze complex
engineering problems reaching substantiated conclusions using first principles
of mathematics, natural sciences, and engineering sciences.
Design/development of solutions:
Design solutions for complex engineering problems and design system
components or processes that meet the specified needs with appropriate
consideration for the public health and safety, and the cultural, societal, and
environmental considerations.
Conduct investigations of complex problems:
Use research-based knowledge and research methods including design
of experiments, analysis and interpretation of data, and synthesis of the
information to provide valid conclusions.
Modern tool usage:
Create, select, and apply appropriate techniques, resources, and modern
engineering and IT tools including prediction and modeling to complex
engineering activities with an understanding of the limitations.
Program Outcomes
The engineer and society:
Apply reasoning informed by the contextual knowledge to assess
societal, health, safety, legal and cultural issues and the consequent
responsibilities relevant to the professional engineering practice.
Environment and sustainability:
Understand the impact of the professional engineering solutions in
societal and environmental contexts, and demonstrate the knowledge of, and
need for sustainable development.
Ethics:
Apply ethical principles and commit to professional ethics and
responsibilities and norms of the engineering practice.
Individual and team work:
Function effectively as an individual, and as a member or leader in
diverse teams, and in multidisciplinary settings.
Communication:
Communicate effectively on complex engineering activities with the
engineering community and with society at large, such as, being able to
comprehend and write effective reports and design documentation, make
effective presentations, and give and receive clear instructions.
Program Outcomes
Project management and finance:
Demonstrate knowledge and understanding of the engineering and
management principles and apply these to one’s own work, as a member and
leader in a team, to manage projects and in multidisciplinary environments.
Life-long learning:
Recognize the need for, and have the preparation and ability to engage in
independent and life-long learning in the broadest context of technological
change.
SUB CODE & NAME:
GE8151 – PROBLEM SOLVING AND PYTHON PROGRAMMING
UNIT 1
ALGORITHMIC PROBLEM SOLVING
Course Outcome
Knowled
SNO DESCRIPTION
ge Level
Outcome:
Develop algorithmic solutions to simple computational
problems.
Problem Solving Techniques
PROBLEM SOLVING
Problem solving is the systematic approach to define the problem and
creating number of solutions.
Properties of Algorithms
Should be written in simple English
Each and every instruction should be precise and unambiguous.
Instructions in an algorithm should not be repeated infinitely.
Algorithm should conclude after a finite number of steps.
Should have an end point
Derived results should be obtained only after the algorithm terminates.
Qualities of a good algorithm
ALGORITHM
The following are the primary factors that are often used to judge the
quality of the algorithms.
Time – To execute a program, the computer system takes some amount of
time. The lesser is the time required, the better is the algorithm.
Memory – To execute a program, computer system takes some amount of
memory space. The lesser is the memory required, the better is the
algorithm.
Statements:
Statement is a single action in a computer.
Control flow:
The process of executing the individual statements in a given order is
called control flow.
1. sequence
2. selection
3. iteration
Sequence:
All the instructions are executed one after another is called sequence
execution.
Example:
Add two numbers:
Step 1: Start
Step 4: Display c
Step 5: Stop
Selection:
A selection statement causes the program control to be transferred to
a specific part of the program based upon the condition.
If the conditional test is true, one part of the program will be executed,
otherwise it will execute the other part of the program.
Example
Write an algorithm to check whether he
is eligible to vote?
Step 1: Start
Step 2: Get age
Step 3: if age >= 18 print “Eligible to
vote”
Step 4: else print “Not eligible to
vote”
Step 5: Stop
Iteration:
In some programs, certain set of statements are executed again and
again based upon conditional test. i.e. executed more than one time.
This type of execution is called looping or iteration.
Example
Write an algorithm to print all natural numbers up to n
Step 1: Start
Step 6: go to step 4
Step 7: Stop
Functions:
Function is a sub program which consists of block of code(set of
instructions) that performs a particular task.
For complex problems, the problem is been divided into smaller and
simpler tasks during algorithm design.
Benefits of Using Functions
Reduction in line of code
code reuse
Better readability
Information hiding
Improved maintainability
Example:
Algorithm for addition of two numbers using function
Main function()
Step 1: Start
Step 3: Stop
sub function add()
Step 1: Function start
Step 4: Print c
Step 5: Return
NOTATIONS
FLOW CHART
Flow chart is defined as graphical representation of the logic for
problem solving.
The purpose of flowchart is making the logic of the program clear in a
visual representation.
Rules for drawing a flowchart
1. The flowchart should be clear, neat and easy to follow.
3. Only one flow line should come out from a process symbol.
4.Only one flow line should enter a decision symbol. However, two or
three flow lines may leave the decision symbol.
Cost: : - For large application the time and cost of flowchart drawing
becomes costly.
PSEUDO CODE:
Pseudo code consists of short, readable and formally styled
English languages used for explain an algorithm.
END
Syntax for For: Example: Print n natural numbers
FOR( start-value to end-
BEGIN
value) DO
GET n
statement
INITIALIZE i=1
...
FOR (i<=n) DO
ENDFOR
PRINT i
i=i+1
ENDFOR
END
Syntax for While: Example: Print n natural numbers
WHILE (condition) DO
BEGIN
statement
GET n
...
INITIALIZE i=1
ENDWHILE
WHILE(i<=n) DO
PRINT i
i=i+1
ENDWHILE
END
Advantages:
Pseudo is independent of any language; it can be used by most
programmers.
GET a,b
ADD c=a+b
PRINT c
END
PROGRAMMING LANGUAGE
A programming language is a set of symbols and rules for instructing
a computer to perform specific tasks.
The programmers have to follow all the specified rules before writing
program using programming language
.
The user has to communicate with the computer using language
which it can understand.
2. Assembly language
Machine dependent:
According to architecture used, the computer differs from each other.
So machine language differs from computer to computer. So a
program developed for a particular type of computer may not run on
other type of computer.
ASSEMBLY LANGUAGE:
To overcome the issues in programming language and make the
programming process easier, an assembly language is developed
which is logically equivalent to machine language but it is easier for
people to read, write and understand.
Hard to learn :
It is machine dependent, so the programmer should have the
hardware knowledge to create applications using assembly language.
Less efficient:
Ø Execution time of assembly language program is more than
machine language program.
Machine independent
High level language program have the advantage of being portable
between machines.
Easy debugging
Easy to find and correct error in high level language
Disadvantages:
Interpreter translates the high level language program in line by line
manner. The interpreter translates a high level language statement in a
source program to a machine code and executes it immediately before
translating the next statement. When an error is found the execution
of the program is halted and error message is displayed on the
screen.
Less efficient
Examples:
Pascal
Python
Functional programming language:
Functional programming language defines every
computation as a mathematical evaluation. They focus on
the programming languages are bound to mathematical
calculations
Examples:
Clean
Haskell
Compiled Programming language:
A compiled programming is a programming language
whose implementation are typically compilers and not
interpreters.
C++
C#
JAVA
Procedural programming language:
Procedural (imperative) programming implies specifying
the steps that the programs should take to reach to an
intended state.
Examples:
Hyper talk
MATLAB
Scripting language:
Scripting language are programming languages that
control an application. Scripts can execute independent of
any other application.
Examples:
Apple script
VB script
Markup languages:
A markup language is an artificial language that uses
annotations to text that define hoe the text is to be
displayed.
Examples:
HTML
XML
Concurrent programming language:
Concurrent programming is a computer programming
technique that provides for the execution of operation
concurrently, either with in a single computer or across a
number of systems.
Examples:
Joule
Limbo
Object oriented programming language:
Object oriented programming is a programming paradigm
based on the concept of objects which may contain data in
the form of procedures often known as methods.
Examples:
Lava
Moto
ALGORITHMIC PROBLEM SOLVING:
Algorithmic problem solving is solving problem that
require the formulation of an algorithm for the solution.
Understanding the Problem
It is the process of finding the input of the problem that
the algorithm solves.
It is very important to specify exactly the set of inputs the
algorithm needs to handle.
A correct algorithm is not one that works most of the time,
but one that works correctly for all legitimate inputs.
Ascertaining the Capabilities of the Computational Device
If the instructions are executed one after another, it is
called sequential algorithm.
1. Iterations
2. Recursions
1. Iterations:
A sequence of statements is executed until a specified
condition is true is called iterations.
1. for loop
2. while loop
Syntax for For: Example: Print n natural numbers
FOR( start-value to end-
BEGIN
value) DO
GET n
statement
INITIALIZE i=1
...
FOR (i<=n) DO
ENDFOR
PRINT i
i=i+1
ENDFOR
END
Syntax for While: Example: Print n natural numbers
WHILE (condition) DO
BEGIN
statement
GET n
...
INITIALIZE i=1
ENDWHILE
WHILE(i<=n) DO
PRINT i
i=i+1
ENDWHILE
END
Recursions:
A function that calls itself is known as recursion.
Step2: Get n
Step5: Stop
Sub function factorial(n):
Step1: if(n==1) then fact=1 return fact
BEGIN
ELSE
RETURN
fact=n*factorial(n-1)
More examples
Write an algorithm to find area of a
rectangle:
Step 1: Start
DISPLAY A
END
Write an algorithm for Calculating simple interest
Step 1: Start
Step3:Calculate
BEGIN
SI=(p*n*r)/100
READ P, n, r
Step 4: Display S
CALCULATE S
Step 5: Stop
SI=(p*n*r)/100
DISPLAY SI
END
Write an algorithm for Calculating engineering cutoff
Step 1: Start
Step3:calculate
BEGIN
Cutoff= (P/4+C/4+M/2)
READ P,C,M
Step 4: Display Cutoff
CALCULATE
Step 5: Stop
Cutoff= (P/4+C/4+M/2)
DISPLAY Cutoff
END
To check greatest of two numbers
Step 1: Start
Step 2: get y
Step1: Start
Step2: Get A, B, C
Step6: Stop
To check greatest of three numbers
BEGIN ELSE
ELSE END IF
END IF END
To check greatest of three numbers
Write an algorithm to check whether given number is +ve, -ve
or zero.
Step 1: Start
Step 6: Stop
Write an algorithm to check whether given number is +ve, -ve
or zero.
BEGIN
GET n
IF(n==0) THEN
DISPLAY “ n is zero”
ELSE
IF(n>0) THEN
DISPLAY “n is positive”
ELSE
DISPLAY “n is positive”
END IF
END IF
END
Write an algorithm to print all natural numbers up to n
Step 1: Start
Step 7: go to step 4
Step 8: Stop
Write an algorithm to print all natural numbers up to n
BEGIN
GET n
INITIALIZE i=1
WHILE(i<=n) DO
PRINT i
i=i+1
ENDWHILE
END
Write an algorithm to print n odd numbers
Step 1: start
step 8: stop
Write an algorithm to print n odd numbers
BEGIN
GET n
INITIALIZE i=1
WHILE(i<=n) DO
PRINT i
i=i+2
ENDWHILE
END
Write an algorithm to print n even numbers
Step 1: start
step 8: stop
Write an algorithm to print n even numbers
BEGIN
GET n
INITIALIZE i=2
WHILE(i<=n) DO
PRINT i
i=i+2
ENDWHILE
END
Write an algorithm to print squares of a number
Step 1: start
step 8: stop
Write an algorithm to print squares of a number
BEGIN
GET n
INITIALIZE i=1
WHILE(i<=n) DO
PRINT i*i
i=i+2
ENDWHILE
END
Write an algorithm to print to print cubes of a number
Step 1: start
step 8: stop
Write an algorithm to print to print cubes of a number
BEGIN
GET n
INITIALIZE i=1
WHILE(i<=n) DO
PRINT i*i*i
i=i+2
ENDWHILE
END
Write an algorithm to find sum of a given number
Step 1: start
step 9: stop
Write an algorithm to find sum of a given number
BEGIN
GET n
INITIALIZE i=1,sum=0
WHILE(i<=n) DO
sum=sum+i
i=i+1
ENDWHILE
PRINT sum
END
Write an algorithm to find factorial of a given number
Step 1: start
step 9: stop
Write an algorithm to find sum of a given number
BEGIN
GET n
INITIALIZE i=1,fact=1
WHILE(i<=n) DO
fact=fact*i
i=i+1
ENDWHILE
PRINT fact
END
Basic python programs:
Addition of two numbers
a=eval(input(“enter first no”))
c=a+b
enter second no
6
the sum is 11
Basic python programs:
Addition of two numbers
a=eval(input(“enter first no”))
c=a+b
enter second no
6
the sum is 11
Basic python programs:
Area of rectangle
l=eval(input(“enter the length of rectangle”))
a=l*b
print(a)
Output:
30
Basic python programs:
Area & circumference of circle
r=eval(input(“enter the radius of circle”))
a=3.14*r*r
c=2*3.14*r
n=eval(input(“enter no of years”))
si=p*n*r/100
cutoff=(p/4+c/4+m/2)
print(“cutoff =”,cutoff)
Output:
enter physics marks 100
enter chemistry marks 99
If(age>=18):
else:
19
for i in range(1,5,1):
print(i)
print(i)
Output:
13579
Basic python programs:
Print n even numbers
for i in range(2,10,2):
print(i)
print(i*i)
Output:
1 4 9 16
Basic python programs:
find sum of n numbers
factorial of n numbers/product of
i=1 n numbers
i=1
sum=0
product=1
while(i<=10): while(i<=10):
product=product*i
sum=sum+i
i=i+1
i=i+1
print(product)
print(sum)
Output:
Output:
3628800
55
UNIT – II
DATA, EXPRESSIONS,
STATEMENTS
A function definition Which
consists of following
components.
Keyw ord def marks the start of function header.
A function name to uniquely identify it. Function naming follows the same rules of w
riting identifiers in Python.
Parameters (arguments) through which we pass values to a function. They are optional.
A colon (:) to mark the end of function header.
Optional documentation string (docstring) to describe what the function does.
One or more valid python statements that make up the function body. Statements must
have same indentation level (usually 4 spaces).
An optional return statement to return a value fr
What is a program?
A program is a sequence of instructions that specifies how to perform a
computation. The computation might be something mathematical, such as
solving a system of equations or finding the roots of a polynomial, but it
can also be a symbolic computat o , such as searching and replacing text
in a document or (strangely enough) compiling a program.
There are few basic instructions appear in every programming lan uage:
input: Get data from the keyboard, a file, or some other device.
output: Display data on the screen or send data to a file or other device.
math: Perform basic mathematical operations like addition and
multiplication.
conditional execution: Check for certain conditions andx cute the
appropriate code.
repetition: Perform some action repeatedly, usually with some variation.
In script mode, type python program in a file and store the file with .py
extension and use the interpreter to execute the contents of the file, which
is called a script. bug: An error in a program.
debugging: The process of finding and removing any of the three kinds of
programming errors.
syntax: The structure of a program.
syntax error: An error in a program that makes it impossible to parse (and
therefore impossible to interpret).
exception: An error that is detected while the program is running.
semantics: The meaning of a program.
semantic error: An error in a program that makes it do something
other than what the programmer intended.
VARIABLES, EXPRESSIONS AND STATEMENTS
Values and types
A value is one of the basic things a program. There are different
values integers, float and strings. The numbers with a decimal
point belong to a type called float. The values written inquotes will
be considered as string, even it’s an integer. If type of value is not
known it can beinterpreted as
Eg:
type('Hello, World!') <type 'str'>
type(17)
<type 'int'>
type('17')
<type 'str'>
type('3.2')
<type 'str'>
Variables
A variable is a name that refers to a value. A var able s a location in
memory used to store some data (value). They are given unique
names to differentiate between different memory locations.
The rules for writing a variable name are same as the rules for
writing identifiers in Python. The assignment operator (=) to assign
values to a variable. An assignment statement creates new variables
and gives them values
Eg:
message = 'And now for something completely different'
n = 17
pi = 3.1415926535897932
type(messae) <type 'str'>
type(n)
<type 'int'>
type(pi) <type'float'>
Python Identifiers
Identifier is the name given to entities like class, functions, variables
etc. in Python. It helps differentiating one entity from another.
Rules for writing identifiers
Identifiers can be a combination of letters in lowercase (a to z) or
uppercase (A to Z) or digits (0 to 9) or an underscore ( ). Names like
myClass, var 1 and print_this_to_screen, all are valid example.
An identifier cannot start with a digit. 1variable is invalid, but
variable1 is perfectly fine.
Keywords cannot be used s identifiers.
We cannot use special symbols like !, @, #, $, % etc. in our identifier.
Identifier can be of any l ngth.
Data types in Python
In Python programming, data types are actually classes and
variables are instance (object) of these classes. They are defined as
int, float and complex class in Python.
Lists
List is an ordered sequence of items. Python knows a number of
compound data types, used to group together other values. The
most versatile is the list, which can be written as a list of comma-
separated values (items) between square brackets. List items need
not all have the same type.
Eg:
a = [’spam’, ’eggs’, 100, 1234]
a
Output: [’spam’, ’eggs’, 100, 1234]
Expressions and statements
An expression is a combination of values, variables, and operators.
Eg:
17
x
x + 17
Instructions that a Python interpreter can execute are called
statements. A statement is a
unit of code that the Python interpreter can execute. Two kinds
of statement: print and
assignment.
Eg:
a=1+2+3+\
4+5+6+\
7+8+9
Python Indentation
Most of the programming languages like C, C++, Java use braces
{ } to define a block of code. Python uses indentation.
A code block (body of a function, loop etc.) starts with
indentation and ends with the first unindented line. The amount
of indentation is up to you, but it must be consistent throughout
that block.
Generally four whitespaces are used for
indentation and is preferred over tabs. Here is an example.
Python Tuple
Tuple is an ordered sequence of items same as list.The only
difference is that tuples are immutable. Tuples once created cannot
be modified.
Tuples are used to write-protect data and are usually faster than list
as it cannot change dynamically.
It is defined within parentheses () where items are separated by
commas.
Eg:
t = (5,'program', 1+3j)
a=(5,7.9,10)
eg:
s = "This is a string"
s = '''a multiline
Comments
Comments indicate Information in a program that is meant for
other programmers (or anyone reading the source code) and has
no effect on the execution of the program. In Python, we use the
hash (#) symbol to start writing a comment. Eg:
#This is a comment
#print out Hello
print('Hello')
Python Output Using print() function
The actual syntax of the print() function is
print (“Statement”,variable name)
print (‘Statement’,variable name)
print (“Statement %formatting function”%variable name)
After all values are printed, end is pri ted. It defaults into a new line.
The file is the object where the values are printed and its default value is
sys.stdout (screen)
Eg:
print ('This sentence is output to the screen')
Output: This sentence is output to the screen a = 5
print ('The value of a is', a)
# Output: The value of a is 5
Python Input
The syntax for input() is
input([prompt])
raw_input([prompt])
where prompt is the string we wish to display on the screen. It is
optional.
Eg:
>>> num = input('Enter a number: ')
Enter a number: 10
>> num:
'10'
>>>a=raw_input(‘Enter a number’)
10
Modules
A module is a file containing Python definitions and statements.
The file name is the module name with the suffix .py appended. A
module can contain executable statements as well as function
definitions. Each module has its own private symbol table, which
is used as the global symbol table by all functions defined in the
module. Modules can import other modules.
Python Import
A module is a file containing Python definitions and statements.
Python modules have a filename and end with the extension .py.
Definitions inside a module can be imported to another module
or the interactive interpreter in Python. We use the import
keyword to do this.
Python provides two ways to import modules.
import math
print math
<module 'math' (built-in)>
print math.pi 3.14159265359
Python programming language
Python is an example of a high-level lan uage; other high-level
languages you might have heard of are C, C++, Perl, and Java. There
are also low-level languages, sometimes referred to as “machine
languages” or “assembly languages.
The high-level program is called the source code, and the
translatedprogram is called the object code or the executable. O ce a
program is compiled, you can execute it repeatedly without further
translation.
Programs written in high-level language have to be processed before
they can run. Python is considered an int rpr ted language because
Python programs are executed by an interpreter. There are two ways to
use the interpreter: interactive mode and script mode.
In interactive mode, type Python programs and the interpreter displays
the result.
Eg: >>> 1 + 1
2
Where, >>> is the prompt the interpreter uses to indicate that it is ready
Functions
Requiredarguments
Keywordarguments
Defaultarguments
Variable-lengtharguments
Required arguments
Required arguments are the arguments passed to a function in
correct positional order. Here, the number of arguments in the
function call should match exactly with the function definition.
# Function definition is here def printme( str ):
"This prints a passed string into this function"
print str
return;
printme()
When the above code is executed, it produces the following result:
Traceback (most recent call last):
File "test.py", line 11, in <module> printme();
TypeError: printme() takes exactly 1 argument (0 given)
Keyword arguments
Keyword arguments are related to the function calls. When you use
keyword arguments in a function call, the caller identifies the
arguments by the parameter name.
This allows you to skip arguments or place them out of order because
the Python interpreter is able to use the keywords provided to match
the values with parameters. You can also make keyword calls to the
printme() function in the following ways−
#!/usr/bin/python
# Function definition is here
def printme( str):
"This prints a passed string into this function" print str
return;
# Now you can call printme function
printme( str = "My string")
My string
Default arguments
A default argument is an argument that assumes a default value if
a value is not provided in the function call for thatargument.
def printinfo( name, age = 35 ):
"This prints a passed info into this function"
print "Name: ", name
print "Age ", age return;
printinfo( age=50, name="miki" )
printinfo( name="miki" )
Name: miki Age 50
Name: miki Age 35
Variable-length arguments
You may need to process a function for more arguments than you
specified while defining the function. These arguments are called
variable-length arguments and are not named in the function
definition, unlike required and defaultarguments.
Syntax for a function with non-keyword variable arguments is this −
def functionname([formal_args,] *var_args_tuple ):
"function_docstring" function_suite return[expression]
An asterisk (*) is placed before the variable name that holds the
values of all nonkeyword variable arguments. This tuple remains
empty if no additional arguments are specified during the function
call. Following is a simple example −
# Function definition is here
def printinfo( arg1, *vartuple ):
"This prints a variable passed arguments" print "Output is: "
print arg1
for var in vartuple:
print var
return;
# Now you can call printinfo function
printinfo( 10 )
printinfo( 70, 60, 50 )
Output is:
10
Output is:
70
60
50
Scope and Lifetime of variables
Scope of a variable is the portion of a program where the
variable is recognized. Parameters and variables defined inside
a function is not visible from outside. Hence, they have a local
scope.
Lifetime of a variable is the period throughout which the variable
exits in the memory.
The lifetime of variables inside a function is as long as the
function executes.
They are destroyed once we return from the function. Hence, a
function does not remember the value of a variable from its
previous calls.
Eg:
def my_func():
x = 10
print("Value inside function:",x)
x = 20
my_func()
print("Value outside function:",x)
Output:
Value inside function: 10
Value outside function: 20
Local Scope and Local Variables
A local variable is a variable that is only accessible from with n a g
ven function. Such variables are said to have local scope .
Global Variables and Global Scope
A global variable is a variable that is defined outside of any
function definition. Such variables are said to have global scope
.
Output:
Simple CalculatorProgram Addition 11
def sum(a,b):
return a+b Subtraction 4
def sub(a,b):
return a-b Multiplication
def mul(a,b): 32
return a*b
def div(a,b): Division 4
return(a//b)
print ("Addition", sum(5,6))
print ("Subtraction",sub(8,4))
print ("Multiplication",mul(8,4)) print
("Division",div(8,2))
Swapping of two variables
def swap(a,b):
print("Values before swapping", a,b)
a,b=b,a
print("Values after swapping",a,b) swap(4,5)
Output:
Values before swapping 4 5
Values after swapping 5 4
Sum of n numbers Output:
def sum(n): s=0 Enter the input
for i in range(1,n): value of n 10
s=s+i
return s Sum of n numbers
n=input("Enter the input value of n") 45
n=int(n)
print("Sum of n numbers", sum(n))
Distance between two points and the midpoint
Output:
Distance between two points 6.324555320336759
Adding two numbers using user defined function.
# Program to illustrate
# the use of user-defined functions def add_numbers(x,y):
sum = x + y return sum
num1 = 5 num2 = 6
print("The sum is", add numbe s(num1, num2))
Distance between twopoints
Output:
Distance between two points 6.324555320336759
#Initialize array
arr = [1, 2, 3, 4, 5];
#n determine the number of times an array should be rotated
n = 3;
#Displays original array
print("Original array: ");
for i in range(0, len(arr)):
print(arr[i]),
#Rotate the given array by n times toward right
for i in range(0, n):
#Stores the last element of array
last = arr[len(arr)-1];
for j in range(len(arr)-1, -1, -1):
#Shift element of array by one
arr[j] = arr[j-1];
#Last element of the array will be added to the start of the array.
arr[0] = last;
#Displays resulting array after rotation
print("Array after right rotation: ");
for i in range(0, len(arr)):
print(arr[i]),
Output:
Original Array:
1 2 3 4 5
Array after right rotation:
3 4 5 1 2
arr = [1, 2, 3, 4, 5]; A
0
1
1
2 2
3
3
4
5
print("Original array: ");
for i in range(0, len(arr)):
//for i in range(0, 5):
print(arr[i]),
for i in range(0, n):
last = arr[len(arr)-1];
for j in range(len(arr)-1, -1, -1):
arr[j] = arr[j-1];
arr[0] = last;
Range(0, 3)
last=arr[5-1]
arr[4]
0 1 2 3 4
1 2 3 4 5
5 1 2 3 4
4 5 1 2 3
3 4 5 1 2
Boolean expressions
A boolean expression is an expression that is either true or false.
The following examples use the operator ==, which compares two
operands and produces True if they are equal and False otherwise:
5==5
True
5==6 False
True and False are special values that belong to the type bool; they
are not strings:
type(True)
<type 'bool'>
type(False)
<type 'bool'>
==operator is.onein of the relational operators; the others are:
x != y # x is not equal to y
x > y # x is greater than y
x < y # x is less than y
x >= y # x is greater than or equal to y
x <= y # x is less than or equal to y
Logical operators
There are three logical operators: and, or, and not. The semantics
(meaning) of these operators is similar to their meaning in English.
For example, x > 0 and x < 10 is true only if x is greater than 0 and
less than 10. n%2 == 0 or n%3 == 0 is true if either of the conditions
is true, that is, if the number is divisible by 2 or 3.
Finally, the not operator negates a boolean expression, so ot (x > y)
is true if x > y is false, that is, if x is less than or equal to y. The
operands of the logical operators should be boolean expressions.
Any nonzero number is interpreted as “t ue.”
17 and True
True
BOOLEAN VALUES:
Boolean:
Outcome:
Structure simple Python programs for solving problems.
CONDITIONALS
1. Conditional if
2. Alternative if… else
3. Chained if…elif…else
4. Nested if….else
Conditional (if):
conditional (if) is used to test a condition, if the condition
is true the statements inside if will be executed.
Syntax:
if(condition 1):
Statement 1
Flowchart:
Conditional (if):
Example:
1. Program to provide flat rs 500, if the purchase amount is
greater than 2000.
if(purchase>=2000):
purchase=purchase-500
Output:
print(“amount to pay”,purchase) enter your purchase
amount
2500
amount to pay
2000
Conditional (if):
Example:
2. Program to provide bonus mark if the category is sports
m=eval(input(“enter ur mark out of 100”))
mark is 90
alternative (if-else)
In the alternative the condition must be true or false.
In this else statement can be combined with if statement.
The else statement contains the block of code that
executes when the condition is false.
If the condition is true statements inside the if get
executed otherwise else part gets executed. The
alternatives are called branches, because they are
branches in the flow of execution.
Syntax:
Flowchart:
EXAMPLES
if(n%2==0):
Output:
print("even number")
enter a number 4
else:
even number
print("odd number")
alternative (if-else)
Example:
2. positive or negative number
n=eval(input("enter a number"))
if(n>=0):
Output:
print("positive number")
enter a number 8
else:
positive number
print("negative number")
alternative (if-else)
Example:
3. leap year or not
y=eval(input("enter a yaer"))
if(y%4==0):
Output:
print("leap year")
enter a year 2000
else:
leap year
print("not leap year")
alternative (if-else)
Example:
4. greatest of two numbers
a=eval(input("enter a value:"))
b=eval(input("enter b value:"))
Output:
if(a>b):
enter a value:4
print("greatest:",a)
enter b value:7
else:
greatest: 7
print("greatest:",b)
alternative (if-else)
Example:
5. eligibility for voting
age=eval(input("enter ur age:"))
if(age>=18):
else: Output:
The if block can have only one else block. But it can have
multiple elif blocks.
elif(mark>=80):
print("grade:A") Output:
elif(mark>=70): enter ur mark:78
print("grade:B")
grade:B
elif(mark>=50):
print("grade:C")
else:
print("fail")
Chained conditionals(if-elif-else)
Example:
2. traffic light system
colour=input("enter colour of light:")
if(colour=="green"):
print("GO")
Output:
elif(colour=="yellow"):
enter colour of light:green
print("GET READY")
GO
else:
print("STOP")
Chained conditionals(if-elif-else)
Example:
3. compare two numbers
x=eval(input("enter x value:"))
y=eval(input("enter y value:"))
if(x == y):
Output:
print("x and y are equal")
enter x value:5
elif(x < y):
enter y value:7
print("x is less than y")
x is less than y
else:
print("x is greater than y")
Chained conditionals(if-elif-else)
Example:
4. Roots of quadratic equation
a=eval(input("enter a value:"))
b=eval(input("enter b value:"))
c=eval(input("enter c value:"))
d=(b*b-4*a*c)
Output:
if(d==0):
enter a value:1
print("same and real roots")
enter b value:0
elif(d>0):
print("diffrent real roots")
enter c value:0
else:
same and real roots
print("imaginagry roots")
Nested conditionals
Oneconditional can also be nested within another. Any
number of condition can be nested inside one another.
Syntax: Flowchart:
EXAMPLES
if(n==0):
else:
break
continue
pass
State:
Transition from one process to another process under
specified condition with in a time is called state.
While loop:
While loop statement in Python is used to repeatedly
executes set of statement as long as a given condition is
true.
i=1
sum=0
Output:
while(i<=n): enter n
sum=sum+i
i=i+1
10
print(sum)
55
While loop
Example:
2. Factorial of a numbers:
n=eval(input("enter n"))
i=1
fact=1
Output:
while(i<=n): enter n
fact=fact*i
5
i=i+1
120
print(fact)
While loop
Example:
3. Sum of digits of a number:
n=eval(input("enter a number"))
sum=0
while(n>0):
Output:
a=n%10
enter a number
sum=sum+a
123
n=n//10
6
print(sum)
While loop
Example:
4. Reverse the given number:
n=eval(input("enter a number"))
sum=0
while(n>0):
Output:
a=n%10
enter a number
sum=sum*10+a
123
n=n//10
321
print(sum)
While loop
Example:
if(sum==org):
print("The given number is Armstrong number")
else:
print("The given number is not
Armstrong number")
While loop
Example:
if(sum==org):
print("The given no is palindrome")
else:
print("The given no is not palindrome")
For loop:
for in range:
We can generate a sequence of numbers using range()
function. range(10) will generate numbers from 0 to 9 (10
numbers).
The body of for loop is separated from the rest of the code
using indentation.
Syntax
For loop:
Sequence can be a list, strings or tuples
EXAMPLES
for i in range(1,n,1):
Output:
if(i%5==0 and i%10!=0):
enter a:30
print(i)
5
15
25
Example:For loop:
2. Fibonacci series
a=0
b=1
n=eval(input("Enter the number of terms: "))
print("Fibonacci Series: ") Output:
print(a,b)
Enter the number of terms: 6
for i in range(1,n,1):
Fibonacci Series:
c=a+b
01
print(c)
1
a=b
2
b=c
3
5
8
Example:For loop:
3. find factors of a number
n=eval(input("enter a number:"))
for i in range(1,n+1,1):
Output:
if(n%i==0):
enter a number:10
print(i)
1
10
For loop:
Example:
4. check the no is prime or not
n=eval(input("enter a number"))
for i in range(2,n):
if(n%i==0):
if(sum==n):
print("the number is perfect number")
else:
print("the number is not perfect number")
For loop:
Example:
6. Program to print prime numbers in range
lower=eval(input("enter a lower range"))
upper=eval(input("enter a upper range"))
Output:
for n in range(lower,upper + 1):
enter a lower range50
enter a upper range100
if n > 1: 53
59
for i in range(2,n): 61
if (n % i) == 0: 67
71
break 73
79
else: 83
print(n) 89
97
For loop:
Example:
7. Program to print first n prime numbers
number=int(input("enter no of prime numbers to be
displayed:"))
count=1 Output:
n=2
enter no of prime
numbers to be
while(count<=number): displayed:5
for i in range(2,n): 2
if(n%i==0): 3
break 5
7
11
else:
print(n)
count=count+1
n=n+1
BREAK
Break statements can alter the flow of a loop.
It terminates the current
loop and executes the remaining statement outside the loop.
If the loop has else statement, that will also gets terminated and come
out of the loop completely.
Flowchart
Syntax
Break
BREAK
Example:
for i in "welcome":
if(i=="c"):
Output:
break w
e
print(i)
l
CONTINUE
It terminates the current iteration and transfer the control to the next
iteration in the loop.
Flowchart
Syntax
Continue
BREAK
Example:
for i in "welcome":
if(i=="c"):
Output:
continue w
e
print(i)
l
e
PASS
Itis used when a statement is required syntactically but you don‟t
want any code to execute.
Syntax
pass
break
PASS
Example:
for i in "welcome":
if(i=="c"):
Output:
pass w
e
print(i)
l
e
Difference between break and continue
else statement in loops:
else in for loop:
If else statement is used in for loop, the else statement is
executed when the loop has reached the limit.
print(i) 3
else: 4
5
print("the number greater than 6")
the number greater than 6
else statement in loops:
else in while loop:
If else statement is used within while loop , the else part
will be executed when the condition become false.
while(i<=5): 3
print(i)
i=i+1 4
5
else:
print("the number greater than 5") the number greater than 5
Fruitful Function
A function that returns a value is called fruitful function.
Example Example
Root=sqrt(25) def add():
a=10
b=20
c=a+b
return c
c=add()
print(c)
Void Function
A function that perform action but don‟t return any value.
Example Example
print(“Hello”) def add():
a=10
b=20
c=a+b
print(c)
add()
Return values:
return keywords are used to return the values from the
function.
Example
return a – return 1 variable
2. Keyword parameters
3. Default parameters
Example
Output:
def student( name, roll ):
George 98
print(name,roll)
student(“George”,98)
Keyword parameter:
When we call a function with some values, these values
get assigned to the parameter according to their position.
When we call functions in keyword parameter, the order of
the arguments can be changed.
Example
def student(name,roll,mark):
print(name,roll,mark)
Output:
student(90,102,"bala") 90 102 bala
Default parameter:
Python allows function parameter to have default values;
if the function is called without the argument, the
argument gets its default value in function definition.
Example
def student( name, age=17):
print(name,mark)
student (“bala”,102,90)
Local and Global Scope
Global Scope
The scope of a variable refers to the places that you can
see or access a variable.
def add(a,b):
c=a+b Output:
return c 900
def mul(c,d):
e=c*d
return e
c=add(10,20)
e=mul(c,30)
print(e)
Function Composition:
find sum and average using function composition
def sum(a,b):
sum=a+b
return sum
Output:
def avg(sum):
avg=sum/2 enter a:4
return avg
enter b:8
a=eval(input("enter a:"))
b=eval(input("enter b:")) the avg is 6.0
sum=sum(a,b)
avg=avg(sum)
Recursion
Strings:
Strings
String slices
Immutability
String module
Strings:
String is defined as sequence of characters represented
in quotation marks (either single quotes ( „ ) or double
quotes ( “ ).
2. Slicing
3. Concatenation
4. Repetitions
5. Member ship
Operations on string:
Immutability:
Python strings are “immutable” as they cannot be
changed after they are created.
y birthday")) 0123456789abcdefABCDEF
print(string.hexdigits) 01234567
print(string.octdigits)
Escape sequences in string
List as array:
Array:
Array is a collection of similar elements. Elements in
the array can be accessed by index. Index starts with 0.
Array can be handled in python by module named
array.
a- array name
i- integer datatype
List as array:
Example
Program to find sum of array elements
import array
Output
sum=0 10
a=array.array('i',[1,2,3,4])
for i in a:
sum=sum+i
print(sum)
Convert list into array:
fromlist() function is used to append list to array. Here
the list is act like a array.
Syntax :
arrayname.fromlist(list_name)
Convert list into array:
Example
program to convert list into array
import array
Output
sum=0 35
l=[6,7,8,9,5]
a=array.array('i',[])
a.fromlist(l)
for i in a:
sum=sum+i
print(sum)
Methods in array
a=[2,3,4,5]
Methods in array
a=[2,3,4,5]
Methods in array
a=[2,3,4,5]
ILLUSTRATIVE PROGRAMS:
Square root using newtons method:
def newtonsqrt(n): Output
enter number to find Sqrt: 9
root=n/2
3.0
for i in range(10):
root=(root+n/root)/2
print(root)
newtonsqrt(n)
ILLUSTRATIVE PROGRAMS:
GCD of two numbers
n1=int(input("Enter a number1:"))
n2=int(input("Enter a number2:"))
for i in range(1,n1+1):
8
ILLUSTRATIVE PROGRAMS:
Exponent of number
def power(base,exp):
if(exp==1):
return(base)
else:
return(base*power(base,exp-1))
base=int(input("Enter base: "))
result=power(base,exp) Output
Enter base: 2
print("Result:",result) Enter exponential value:3
Result: 8
ILLUSTRATIVE PROGRAMS:
sum of array elements:
a=[2,3,4,5,6,7,8]
sum=0
for i in a:
sum=sum+i
Output
the sum is 35
ILLUSTRATIVE PROGRAMS:
Linear search
a=[20,30,40,50,60,70,89]
print(a)
search=eval(input("enter a element to search:"))
for i in range(0,len(a),1):
if(search==a[i]):
print("element found at",i+1)
break
Output
else: [20, 30, 40, 50, 60, 70, 89]
print("not found")
enter a element to search:30
element found at 2
ILLUSTRATIVE PROGRAMS:
Binary search
a=[20, 30, 40, 50, 60, 70, 89]
print(a)
search=eval(input("enter a element to search:"))
start=0
stop=len(a)-1
while(start<=stop):
mid=(start+stop)//2
if(search==a[mid]):
print("elemrnt found at",mid+1)
break Output
elif(search<a[mid]):
stop=mid-1
[20, 30, 40, 50, 60, 70, 89]
else:
start=mid+1 enter a element to search:30
else:
print("not found") element found at 2
Syllabus
Lists: list operations, list slices, list methods, list loop, mutability,
aliasing, cloning lists, list parameters; Tuples: tuple assignment, tuple
as return value; Dictionaries: operations and methods; advanced list
processing - list comprehension; Illustrative programs: selection sort,
insertion sort, mergesort, histogram.
Outcome:
Represent compound data using Python lists, tuples,
dictionaries.
Lists
Lists:
Listname[start:stop:steps]
• They do not work on the other sequence types that are not mutable,
that is, the values they contain cannot be changed, added, or
deleted.
Syntax:
1. For loop
2. While loop
3. Infinite loop
1. List using For Loop:
• The for loop in Python is used to iterate over a sequence
(list, tuple, string) or other iterable objects.
Syntax:
Syntax:
while (condition):
body of while
2. List using While loop
Sum of elements in list:
a=[1,2,3,4,5]
i=0
sum=0
Output:
while i<len(a):
15
sum=sum+a[i]
i=i+1
print(sum)
3. Infinite Loop
• A loop becomes infinite loop if the condition given never
becomes false. It keeps on
• When the first element of the list named “a” is replaced, the first
element of the list named “b” is also replaced.
• They are aliases for the same object. This phenomenon is known as
aliasing.
1. Slicing
2. list()method
3. copy() method
Clonning:
clonning using Slicing: clonning using copy()
method:
>>>a=[1,2,3,4,5]
a=[1,2,3,4,5]
>>>b=a[:]
>>>b=a.copy()
>>>print(b)
>>> print(b)
[1,2,3,4,5]
[1, 2, 3, 4, 5]
>>>a is b
>>> a is b
False
False
Clonning:
clonning using List( ) method:
>>>a=[1,2,3,4,5]
>>>b=list
>>>print(b)
[1,2,3,4,5]
>>>a is b
false
List as parameters:
• In python, arguments are passed by reference.
def remove(a):
a.remove(1)
a=[1,2,3,4,5] Output:
remove(a) [2,3,4,5]
print(a)
List as parameters:
Example 2:
def insert(a):
a.insert(0,30)
a=[1,2,3,4,5]
Output:
insert(a)
[30, 1, 2, 3, 4, 5]]
print(a)
Tuple:
• A tuple is same as list, except that the set of elements is
enclosed in parentheses instead of square brackets.
Benefits of Tuple:
• Tuples are faster than lists.
1. Indexing
2. Slicing
3. Concatenation
4. Repetitions
5. Updating
6. Membership
7. Comparison
Operations on Tuples:
Operations on Tuples:
Tuple Methods:
Tuple is immutable so changes cannot be done on the elements of a tuple
once it assigned
Tuple Assignment:
• Tuple assignment allows, variables on the left of an
assignment operator and values of tuple on the right of
the assignment operator.
Output:
50, 20
Multiple assignments:
• Multiple values can be assigned to multiple variables
using tuple assignment.
>>>(a,b,c)=(1,2,3)
>>>print(a)
1
>>>print(b)
2
>>>print(c)
3
Tuple as return value:
Example1:
def div(a,b):
r=a%b
q=a//b
return(r,q)
a=eval(input("enter a value:"))
Output:
enter a value:4
b=eval(input("enter b value:"))
enter b value:3
r,q=div(a,b)
reminder: 1
print("reminder:",r)
quotient: 1
print("quotient:",q)
Tuple as return value:
Example2:
def min_max(a):
small=min(a)
big=max(a)
return(small,big)
a=[1,2,3,4,6]
Output:
smallest: 1
small,big=min_max(a)
biggest: 6
print("smallest:",small)
print("biggest:",big)
Tuple as argument:
• The parameter name that begins with * gathers argument
into a tuple.
Example:
def printall(*args):
print(args) Output:
(2, 3, 'a')
printall(2,3,'a')
Dictionaries:
• Dictionary is an unordered collection of elements. An
element in dictionary has a key: value pair.
Output:
['apple', 'banana', 'mango']
Advanced list processing:
List Comprehension:
• List comprehensions provide a concise way to apply
operations on a list.
• The list comprehension always returns a result list.
Syntax
Selection sort
def selection_sort(L):
for i in range(len(L) - 1):
min_index = argmin(L[i:])
L[i], L[min_index] = L[min_index], L[i]
We begin with the unsorted list:
35124
The unsorted section has all the elements. We look through
each item and determine that 1 is the smallest element. So,
we swap 1 with 3:
15324
Of the remaining unsorted elements, [5, 3, 2, 4], 2 is the
lowest number. We now swap 2 with 5:
12354
This process continues until the list is sorted:
12354
12345
12345
Python Programs on Lists, Tuples, Dictionaries
Illustrative programs:
Selection sort:
Python Programs on Lists, Tuples, Dictionaries
Illustrative programs:
Insertion sort:
a=input("enter a list:").split()
a=list(map(int,a))
Output:
for i in a:
j = a.index(i) enter a list: 8 5 7 1 9 3
while j>0:
if a[j-1] > a[j]: [1,3,5,7,8,9]
a[j-1],a[j] = a[j],a[j-1]
else:
break
j = j-1
print (a)
Python Programs on Lists, Tuples, Dictionaries
Illustrative programs:
Insertion sort:
Python Programs on Lists, Tuples, Dictionaries
Illustrative programs:
Merge sort: def divide(x):
def merge(a,b): if len(x) == 0 or len(x) == 1:
c = [] return x
while len(a) != 0 and len(b) != 0: else:
if a[0] < b[0]: middle = len(x)//2
c.append(a[0]) a = divide(x[:middle])
a.remove(a[0])
else:
b = divide(x[middle:])
c.append(b[0]) return merge(a,b)
b.remove(b[0]) x=[38,27,43,3,9,82,10]
if len(a) == 0: c=divide(x)
c=c+b print(c)
else:
Output:
c=c+a
return c [3,9,10,27,38,43,82]
Python Programs on Lists, Tuples, Dictionaries
Illustrative programs:
Merge sort:
Python Programs on Lists, Tuples, Dictionaries
Illustrative programs:
Histogram:
def histogram(a):
for i in a: Output:
sum = '' ****
while(i>0):
*****
sum=sum+'#'
i=i-1 *******
print(sum) ********
a=[4,5,7,8,12] ************
histogram(a)
def histogram( items ):
for n in items:
output = ''
times = n
while( times > 0 ):
output += '*' Sample Output:
times = times - 1
print(output)
histogram([2, 3, 6, 5]) **
***
******
*****
Python Programs on Lists, Tuples, Dictionaries
Calendar program:
Output:
import calendar
enter year:2017
y=int(input("enter year:")) enter month:11
November 2017
m=int(input("enter month:"))
Mo Tu We Th Fr Sa Su
print(calendar.month(y,m)) 12345
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30
NPTEL References
1 https://nptel.ac.in/courses/106102064
2 https://nptel.ac.in/courses/106106127
Thank You.