0% found this document useful (0 votes)
9 views

Semester i - Problem Solving and Python Programming (Ge8151)_compressed

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

Semester i - Problem Solving and Python Programming (Ge8151)_compressed

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

Department of Computer Science and

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

Understand the problem-solving techniques and analysis of


C105.1 K2
its complexity
Apply the basic concepts of python in developing simple
C105.2 K3
solutions
Make use of the functions concepts to split the programs
C105.3 K3
into smaller codes

Develop Python programs for applications that requires List,


C105.4 K3
Tuples and Dictionaries.

Utilize the concept of file and exception handling to develop


C105.5 K3
efficient applications to handle all kind of errors
Syllabus
UNIT 1 - ALGORITHMIC PROBLEM SOLVING

Algorithms, building blocks of algorithms (statements, state, control


flow, functions), notation (pseudo code, flow chart, programming
language), algorithmic problem solving, simple strategies for
developing algorithms (iteration, recursion). Illustrative problems: find
minimum in a list, insert a card in a list of sorted cards, guess an
integer number in a range, Towers of Hanoi.

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.

The problem solving process starts with the problem specifications


and ends with a Correct program.
PROBLEM SOLVING TECHNIQUES
Problem solving technique is a set of techniques that helps in
providing logic for solving a problem.
PROBLEM SOLVING TECHNIQUES:

Problem solving can be expressed in the form of


1. Algorithms.
2. Flowcharts.
3. Pseudo codes.
4. Programs
Problem Solving Techniques
ALGORITHM
It is defined as a sequence of instructions that describe a method for
solving a problem. In other words it is a step by step procedure for
solving a problem.

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.

 Accuracy – Multiple algorithms may provide suitable or correct solutions to


a given problem, some of these may provide more accurate results than
others, and such algorithms may be suitable.
Example
Write an algorithm to print „Good Morning”
Step 1: Start
Step 2: Print “Good Morning”
Step 3: Stop
BUILDING BLOCKS OF ALGORITHMS (statements, state,
control flow, functions)
Algorithms can be constructed from basic building blocks namely,
sequence, selection and iteration.

Statements:
Statement is a single action in a computer.

In a computer statements might include some of the following actions

Ø input data-information given to the program

Ø process data-perform operation on a given input

Ø output data-processed result


State:
Transition from one process to another process under specified
condition with in a time is called state.

Control flow:
The process of executing the individual statements in a given order is
called control flow.

The control can be executed in three ways

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 2: get a,b

Step 3: calculate c=a+b

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 2: get n value.

Step 3: initialize i=1

Step 4: if (i<=n) go to step 5 else go to step 7

Step 5: Print i value and increment i value by 1

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

Easy to debug and test

Improved maintainability
Example:
Algorithm for addition of two numbers using function
Main function()
Step 1: Start

Step 2: Call the function add()

Step 3: Stop
sub function add()
Step 1: Function start

Step 2: Get a, b Values

Step 3: add c=a+b

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.

2. The flowchart must have a logical start and finish.

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.

5. Only one flow line is used with a terminal symbol.

6. Within standard symbols, write briefly and precisely.

7. Intersection of flow lines should be avoided.


Advantages of flowchart:
Communication: - Flowcharts are better way of communicating the
logic of a system to all concerned.
Effective analysis: - With the help of flowchart, problem can be
analyzed in more effective way.
Proper documentation: - Program flowcharts serve as a good program
documentation, which is needed for various purposes.
Efficient Coding: - The flowcharts act as a guide or blueprint during
the systems analysis and program development phase.

Proper Debugging: - The flowchart helps in debugging process.

Efficient Program Maintenance: - The maintenance of operating


program becomes easy with the help of flowchart. It helps the
programmer to put efforts more efficiently on that part.
Disadvantages of flow chart:
Complex logic: - Sometimes, the program logic is quite complicated.
In that case, flowchart becomes complex and clumsy.

Alterations and Modifications: - If alterations are required the


flowchart may require re-drawing completely.

Reproduction: - As the flowchart symbols cannot be typed,


reproduction of flowchart becomes a problem.

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.

 It does not include details like variable declaration, subroutines.


 It is easier to understand for the programmer or non programmer to
understand the general working of the program, because it is not
based on any programming language.

 It gives us the sketch of the program before actual coding.


 It is not a machine readable
 Pseudo code can’t be compiled and executed.
Guidelines for writing pseudo code:
 Write one statement per line
 Capitalize initial keyword
 Indent to hierarchy
 End multiline structure
 Keep statements language independent
Guidelines for writing pseudo code:
The following gives common keywords used in pseudo codes.
 1. //: This keyword used to represent a comment.
 2. BEGIN,END: Begin is the first statement and end is the last statement.
 3. INPUT, GET, READ: The keyword is used to inputting data.
 4. COMPUTE, CALCULATE: used for calculation of the result of the
given expression.

 5. ADD, SUBTRACT, INITIALIZE used for addition, subtraction and initialization.


 6. OUTPUT, PRINT, DISPLAY: It is used to display the output of the program.

 7. IF, ELSE, ENDIF: used to make decision.


 8. WHILE, ENDWHILE: used for iterative statements.
 9. FOR, ENDFOR: Another iterative incremented/decremented
tested automatically.
Syntax for if else: Example: Greatest of two numbers
IF (condition)THEN
BEGIN
statement
READ a,b
...
IF (a>b) THEN
ELSE
DISPLAY a is greater
statement
ELSE
...
DISPLAY b is greater
ENDIF
END IF

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.

 It is easy to translate pseudo code into a programming language.


 It can be easily modified as compared to flowchart.
 Convertinga pseudo code to programming language is very easy
as compared with converting a flowchart to programming
language.
Disadvantages:
 It does not provide visual representation of the program’s logic.
 There are no accepted standards for writing pseudo codes.
 It cannot be compiled nor executed.
 For a beginner, It is more difficult to follow the logic or write pseudo
code as compared to flowchart.
Example:
Addition of two numbers:
BEGIN

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.

Types of programming language


1. Machine language

2. Assembly language

3. High level language


MACHINE LANGUAGE:
The computer can understand only machine language which uses 0’s
and 1’s. In machine language the different instructions are formed by
taking different combinations of 0’s and 1’s.
ADVANTAGES:
Translation free:
Machine language is the only language which the computer
understands. For executing any program written in any programming
language, the conversion to machine language is necessary. The
program written in machine language can be executed directly on
computer. In this case any conversion process is not required.
High speed:
The machine language program is translation free. Since the
conversion time is saved, the execution of machine language program
is extremely fast.
MACHINE LANGUAGE:
DISADVANTAGES:
It is hard to find errors in a program written in the machine language.

Writhing program in machine language is a time consuming process.

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.

Assembly language is symbolic representation of machine language.


Assembly languages are symbolic programming language that uses
symbolic notation to represent machine language instructions. They
are called low level language because they are so closely related to
the machines.
Assembler:
Assembler is the program which translates assembly language
instruction in to a machine language.

Ø Easy to understand and use.

Ø It is easy to locate and correct errors.


DISADVANTAGE:
Machine dependent:
The assembly language program which can be executed on the
machine depends on the architecture of that computer.

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.

Ø Because assembler is needed to convert from assembly language


to machine language.
HIGH LEVEL LANGUAGE:
High level language contains English words and symbols. The
specified rules are to be followed while writing program in high level
language. The interpreter or compilers are used for converting these
programs in to machine readable form.

Translating high level language to machine language.

The programs that translate high level language in to machine


language are called interpreter or compiler.
Compiler:
A compiler is a program which translates the source code written in a
high level language in to object code which is in machine language
program. Compiler reads the whole program written in high level
language and translates it to machine language. If any error is found it
display error message on the screen.
Interpreter:
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.
Advantages:
Readability
High level language is closer to natural language so they are easier to
learn and understand

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

The translation process increases the execution time of the program.


Programs in high level language require more memory and take more
execution time to execute.
They are divided into following categories:
1.Interpreted programming languages
2.Functional programming languages
3.Compiled programming languages
4.Procedural programming languages
5.Scripting programming language
6.Markup programming language
7.Concurrent programming language
8.Object oriented programming language
Interpreted programming languages:
An interpreted language is a programming language for
which most of its implementation executes instructions
directly, without previously compiling a program into
machine language instructions. The interpreter executes
the program directly translating each statement into a
sequence of one or more subroutines already compiled
into machine code.

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.

It will produce a machine code from source code.


Examples:

C++

C#

JAVA
Procedural programming language:
Procedural (imperative) programming implies specifying
the steps that the programs should take to reach to an
intended state.

A procedure is a group of statements that can be referred


through a procedure call. Procedures help in the reuse of
code. Procedural programming makes the programs
structured and easily traceable for program flow.

Examples:

Hyper talk

MATLAB
Scripting language:
Scripting language are programming languages that
control an application. Scripts can execute independent of
any other application.

They are mostly embedded in the application that they


control and are used to automate frequently executed
tasks like communicating with external program.

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.

If the instructions are executed concurrently, it is called


parallel algorithm.
Choosing between Exact and Approximate Problem Solving
The next principal decision is to choose between solving
the problem exactly or solving it approximately.
Based on this, the algorithms are classified as exact
algorithm and approximation algorithm.
Deciding a data structure:
The next principal decision is to choose between solving
the problem exactly or solving it approximately.

Some of the algorithm design techniques also depend on


the structuring data specifying a problem’s instance.

Algorithm+ Data structure=programs.


Algorithm Design Techniques
An algorithm design technique (or “strategy” or
“paradigm”) is a general approach to solving problems
algorithmically that is applicable to a variety of problems
from different areas of computing.

Learning these techniques is of utmost importance for the


following reasons.
First, they provide guidance for designing algorithms for
new problems,
Second, algorithms are the cornerstone of computer
science.
Methods of Specifying an Algorithm
Pseudocode is a mixture of a natural language and
programming language-like constructs.

In the earlier days of computing, the dominant vehicle for


specifying algorithms was a flowchart, a method of
expressing an algorithm by a collection of connected
geometric shapes containing descriptions of the
algorithm’s steps.

Programming language can be fed into an electronic


computer directly. Instead, it needs to be converted into a
computer program written in a particular computer
language.
Proving an Algorithm’s Correctness
Once an algorithm has been specified, you have to prove
its correctness. That is, you have to prove that the
algorithm yields a required result for every legitimate input
in a finite amount of time.

A common technique for proving correctness is to use


mathematical induction because an algorithm’s iterations
provide a natural sequence of steps needed for such
proofs.

It might be worth mentioning that although tracing the


algorithm’s performance for a few specific inputs can be a
very worthwhile activity, it cannot prove the algorithm’s
correctness conclusively.
Analysing an Algorithm
1. Efficiency

Time efficiency, indicating how fast the algorithm runs,

Space efficiency, indicating how much extra memory it


uses.
2. Simplicity

An algorithm should be precisely defined and investigated


with mathematical expressions.

Simpler algorithms are easier to understand and easier to


program.

Simple algorithms usually contain fewer bugs.


Coding an Algorithm

Most algorithms are destined to be ultimately implemented


as computer programs. Programming an algorithm
presents both a peril and an opportunity.

A working program provides an additional opportunity in


allowing an empirical analysis of the underlying algorithm.
Such an analysis is based on timing the program on
several inputs and then analysing the results obtained.
SIMPLE STRATEGIES FOR DEVELOPING ALGORITHMS:

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.

Recursion is a process by which a function calls itself


repeatedly until some specified condition has been
satisfied.
Algorithm for factorial of n numbers using recursion:
Main function:
Step1: Start

Step2: Get n

Step3: call factorial(n)

Step4: print fact

Step5: Stop
Sub function factorial(n):
Step1: if(n==1) then fact=1 return fact

Step2: else fact=n*factorial(n-1) and return fact


Pseudo code for factorial using recursion:
Main function:

BEGIN

GET n Sub function factorial(n):

CALL factorial(n) IF(n==1) THEN

PRINT fact fact=1

BIN RETURN fact

ELSE

RETURN
fact=n*factorial(n-1)
More examples
Write an algorithm to find area of a
rectangle:

Step 1: Start

Step 2: get l,b values

Step 3: Calculate A=l*b BEGIN

Step 4: Display A READ l,b

Step 5: Stop CALCULATE A=l*b

DISPLAY A

END
Write an algorithm for Calculating simple interest
Step 1: Start

Step 2: get P, n, r value

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

Step2: get P,C,M value

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 a,b value

Step 3: check if(a>b) print a is greater

Step 4: else b is greater

Step 5: Stop BEGIN


READ a,b
IF (a>b) THEN
DISPLAY a is greater
ELSE
DISPLAY b is greater
END IF
END
To check greatest of two numbers
Step 1: Start

Step 2: get a,b value

Step 3: check if(a>b) print a is greater

Step 4: else b is greater

Step 5: Stop BEGIN


READ a,b
IF (a>b) THEN
DISPLAY a is greater
ELSE
DISPLAY b is greater
END IF
END
To check leap year or not
Step 1: Start

Step 2: get y

Step 3: if(y%4==0) print leap year

Step 4: else print not leap year

Step 5: Stop BEGIN


READ y
IF (y%4==0) THEN
DISPLAY leap year
ELSE
DISPLAY not leap year
END IF
END
To check odd or even number
Step 1: Start

Step 2: get num

Step 3: check if(num%2==0) print


num is even

Step 4: else num is odd


BEGIN
Step 5: Stop READ num
IF (num%2==0) THEN
DISPLAY num is even
ELSE
DISPLAY num is odd
END IF
END
To check greatest of three numbers

Step1: Start

Step2: Get A, B, C

Step3: if(A>B) goto Step4 else goto step5

Step4: If(A>C) print A else print C

Step5: If(B>C) print B else print C

Step6: Stop
To check greatest of three numbers

BEGIN ELSE

READ a, b, c IF(b>c) THEN

IF (a>b) THEN DISPLAY b is greater

IF(a>c) THEN ELSE

DISPLAY a is greater DISPLAY c is greater

ELSE END IF

DISPLAY c is greater 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 2: Get n value.

Step 3: if (n ==0) print “Given number is Zero” Else goto


step4

Step 4: if (n > 0) then Print “Given number is +ve”

Step 5: else Print “Given number is -ve”

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 2: get n value.

Step 3: initialize i=1

Step 4: if (i<=n) go to step 5 else go to step 8

Step 5: Print i value

step 6 : increment i value by 1

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 2: get n value

step 3: set initial value i=1

step 4: check if(i<=n) goto step 5 else goto step 8

step 5: print i value

step 6: increment i value by 2

step 7: goto step 4

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 2: get n value

step 3: set initial value i=2

step 4: check if(i<=n) goto step 5 else goto step8

step 5: print i value

step 6: increment i value by 2

step 7: goto step 4

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 2: get n value

step 3: set initial value i=1

step 4: check i value if(i<=n) goto step 5 else goto step8

step 5: print i*i value

step 6: increment i value by 1

step 7: goto step 4

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 2: get n value

step 3: set initial value i=1

step 4: check i value if(i<=n) goto step 5 else goto step8

step 5: print i*i *i value

step 6: increment i value by 1

step 7: goto step 4

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 2: get n value

step 3: set initial value i=1, sum=0

Step 4: check i value if(i<=n) goto step 5 else goto step8

step 5: calculate sum=sum+i

step 6: increment i value by 1

step 7: goto step 4

step 8: print sum value

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 2: get n value

step 3: set initial value i=1, fact=1

Step 4: check i value if(i<=n) goto step 5 else goto step8

step 5: calculate fact=fact*i

step 6: increment i value by 1

step 7: goto step 4

step 8: print fact value

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

b=eval(input(“enter second no”))

c=a+b

print(“the sum is “,c)


Output:
enter first no
5

enter second no
6

the sum is 11
Basic python programs:
Addition of two numbers
a=eval(input(“enter first no”))

b=eval(input(“enter second no”))

c=a+b

print(“the sum is “,c)


Output:
enter first no
5

enter second no
6

the sum is 11
Basic python programs:
Area of rectangle
l=eval(input(“enter the length of rectangle”))

b=eval(input(“enter the breath of rectangle”))

a=l*b

print(a)
Output:

enter the length of rectangle 5

enter the breath of rectangle 6

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

print(“the area of circle”,a)

print(“the circumference of circle”,c)


Output:
enter the radius of circle4

the area of circle 50.24

the circumference of circle 25.12


Basic python programs:
Calculate simple interest
p=eval(input(“enter principle amount”))

n=eval(input(“enter no of years”))

r=eval(input(“enter rate of interest”))

si=p*n*r/100

print(“simple interest is”,si)


Output:
enter principle amount 5000
enter no of years 4
enter rate of interest 6

simple interest is 1200.0


Basic python programs:
Calculate engineering cutoff
p=eval(input(“enter physics marks”))

c=eval(input(“enter chemistry marks”))

m=eval(input(“enter maths marks”))

cutoff=(p/4+c/4+m/2)

print(“cutoff =”,cutoff)
Output:
enter physics marks 100
enter chemistry marks 99

enter maths marks 96


cutoff = 97.75
Basic python programs:
Check voting eligibility
age=eval(input(“enter ur age”))

If(age>=18):

print(“eligible for voting”)

else:

print(“not eligible for voting”)


Output:
Enter ur age

19

Eligible for voting


Basic python programs:
Find greatest of three numbers

a=eval(input(“enter the value of a”))


b=eval(input(“enter the value of b”))
c=eval(input(“enter the value of c”))
if(a>b):
if(a>c): Output:
print(“the greatest no is”,a) enter the value of a 9
else:
print(“the greatest no is”,c) enter the value of a 1
else:
if(b>c): enter the value of a 8
print(“the greatest no is”,b)
else: the greatest no is
print(“the greatest no is”,c)
9
Basic python programs:
Print n natural numbers

for i in range(1,5,1):

print(i)

Output: Print n odd numbers

1234 for i in range(1,10,2):

print(i)

Output:

13579
Basic python programs:
Print n even numbers

for i in range(2,10,2):

print(i)

Output: Print squares of numbers

2468 for i in range(1,5,1):

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

In Python, function is a group of related statements that perform a


specific task. Functions help break our program into smaller and
modular chu nks. As our program grows larger and larger, functions
make it more organized and ma nageable. Furthermore, it avoids
repetition and makes code reusable.
Function Definitions

In Python each function definition is of the form


def name of function (list of formal
parameters):
body of function
For example, we could define the function max by the code
def max(x, y):
if x > y:
return x
else:
return y
def is a reserved word that tells Python that a function is about to be defined.
Function call
A function is a named sequence of statements that performs a
computation. When you define a function, you specify the name
and the sequence of statements. Later, you can “call” the
function by name.
type(32)
<type 'int'>
The name of the function is type. The expression in parentheses
is called the argument of the function. The resultis called the
return value.
The return statement
The return statement is used to exit a function and go back to the
place from where it was called. The Syntax of return statement:
return [expression_list]
This statement can contain expression which gets evaluated and the
value is returned. If there is
no expression in the statement or the return statement its lf is not
present inside a function, then
the function will return the None object.
For example:
print(greet("May")) Hello, May. Good morning! None
Here, None is the returned value.
How Function works in
Python?
Types of Functions

Basically, we can divide functions into the following two types:


Built-in functions - Functions that are built into Python.
User-defined functions - Functions defined by the users themselves.
Type conversion functions
Python provides built-in functions that convert values from one type to
another. The int function takes any value and converts it to an integer, if it
can, or complains otherwise:
int('32')
32
int('Hello')
ValueError: invalid literal for int(): Hello
int can convert floating-point values to integers, but it doesn’t round off; t
chops off the fraction part:
int(3.99999)
3
int(-2.3)
-2
float converts integers and strings to floati g-poi t numbers:
float(32)
32.0
float('3.14159') 3.14159
Finally, str converts its argument to a string:
str(32)
'32'
str(3.14159)
'3.14159'
Math functions
Python has a math module that provides mathematical functions.
>>> import math
This statement creates a module object named math. If you print the
module object, you get some information about it:
>>> print math
<module 'math' (built-in)>
The module object contains the functions and variables defined in the
module. To access one of the functions, you have to specify the name
of the module and the name of the
function, separated by a dot (also known as a period). This format is
called dot notation.
It gives access to the underlying C library functions. For example,
# Square root calculation
import math
math.sqrt(4)

List of Functions in Python Math Module


ceil(x) Returns the smallest integer greater than or equal to x.
copysign(x, y) Returns x with the sign of y
fabs(x) Returns the absolute value of x
factorial(x) Returns the factorial of x
floor(x) Returns the largest integer less than or equal to x
fmod(x, y) Returns the remainder when x is divided by y
frexp(x) Returns the mantissa and exponent of x as the pair (m, e)
Flow of execution
The order in which statements are executed, which is called the
flow of execution. Execution always begins at the first statement
of the program. Statements are executed one at a time, in order
from top to bottom.
Function definitions do not alter the flow of execution of the
program, but remember that statements inside the function are
not executed until the function is called.
Parameters and arguments
Some of the built-in functions we have seen require arguments .
For example, when you call math.sin you pass a number as an
argument. Some functions take more than one argument: math.pow
takes two, the base and the exponent.
Inside the function, the arguments are assigned to variables called
parameters. Here is an example of a user-defined function that takes an
argument:
Eg: def print_twice(bruce):
print bruce
print bruce
This function assigns the argument to a parameter named bruce. When
the function is called, it prints the value of the parameter (whatever it
is) twice.
This function works with any value that can be printed.
print_twice('Spam')
Spam
Spam
print_twice(17)
17
17
print_twice(math.pi) 3.14159265359
3.14159265359
Parameter Passing
Parameter passing is the process of passing arguments to a
function. There are two types of arguments: Actual arguments
and formal arguments. Actual arguments are the values passed
to a function’s formal parameters to be operated on.
Eg:
def f(x): #name x used as formal parameter
y=1
x=x+y
print 'x =', x
return x.
x=3
y=2
z = f(x) #value of x used as actual parameter
print 'z =', z
print 'x =', x
print 'y =', y
When run, this code prints,
x=4
z=4
x=3
y=2
A default argument is an argument that can be optionally provided
in a given function call. When not provided, the corresponding
parameter provides a default value. Eg:
def greet(name, msg = "Good morning!"):
"""
This function greets to
the person with the
provided message.
If message is not provided,
it defaults to "Good
morning!"
"""
print("Hello",name + ', ' + msg)
greet("Kate")
greet("Bruce","How do you do?")
Output:
Hello Kate, Good morning!
Hello Bruce, How do you do?
Function Arguments

You can call a function by using the following types of formal


arguments:

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

The distance formula is an algebraic expression used to


determine the distance between two points with the coordinates
(x1, y1) and (x2, y2).
D=√(x2−x1)2+(y2−y1)2
Distance between two points
import math
p1 = [4, 0]
p2 = [6, 6]
distance = math.sqrt( ((p2[0]-p1[0])**2)+((p2[1]-p1[1])**2) )
print(distance)

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

import math p1 = [4,0]


p2 = [6,6]
distance = math.sqrt( ((p1[0]-p2[0])**2)+((p1[1]-p2[1])**2) )
print(distance)

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:

 Boolean data type have two values. They are 0 and 1.


 0 represents False
 1 represents True
 True and False are keyword.
Example:
>>> 3==5
False
>>> 6==6
True
>>> True+True
2
>>> False+True
1
>>> False*True
0
Syllabus

UNIT 3 - CONTROL FLOW, FUNCTIONS

Conditionals: Boolean values and operators, conditional (if),


alternative (if-else), chained conditional (if-elif-else); Iteration: state,
while, for, break, continue, pass; Fruitful functions: return values,
parameters, local and global scope, function composition, recursion;
Strings: string slices, immutability, string functions and methods,
string module; Lists as arrays. Illustrative programs: square root, gcd,
exponentiation, sum an array of numbers, linear search, binary
search.

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.

purchase=eval(input(“enter your purchase amount”))

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

c=input(“enter ur categery G/S”)


Output:
if(c==”S”):
enter ur mark out of 100
m=m+5 85

print(“mark is”,m) enter ur categery G/S


S

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

1. odd or even number


2. positive or negative number
3. leap year or not
4. greatest of two numbers

5. eligibility for voting


alternative (if-else)
Example:
1. Odd or even number
n=eval(input("enter a number"))

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

print("you are eligible for vote")

else: Output:

print("you are NOT eligible for vote")enter ur age:78


you are eligible for vote
Chained conditionals(if-elif-else)
 The elif is short for else if.
 This is used to check more than one condition.
If the condition1 is False, it checks the condition2 of the
elif block. If all the conditions are False, then the else part
is executed.

Among the several if...elif...else part, only one part is


executed according to the condition.

The if block can have only one else block. But it can have
multiple elif blocks.

The way to express a computation like that is a chained


conditional.
Chained conditionals(if-elif-else)
Syntax:
Flowchart:
EXAMPLES

1. student mark system


2. traffic light system
3. compare two numbers
4. roots of quadratic equation
Chained conditionals(if-elif-else)
Example:
1. student mark system
mark=eval(input("enter ur mark:"))
if(mark>=90):
print("grade:S")

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.

In this, if the condition is true it checks another if


condition1. If both the conditions are true statement1 get
executed otherwise statement2 get execute. if the
condition is false statement3 gets executed

Syntax: Flowchart:
EXAMPLES

1. greatest of three numbers


2. positive negative or zero
Nested conditionals
Example:
1. greatest of three numbers
a=eval(input(“enter the value of a”))
b=eval(input(“enter the value of b”))
c=eval(input(“enter the value of c”))
if(a>b):
if(a>c):
print(“the greatest no is”,a) Output:
else: enter the value of a 9
print(“the greatest no is”,c)
enter the value of a 1
else:
if(b>c): enter the value of a 8
print(“the greatest no is”,b)
else: the greatest no is 9
print(“the greatest no is”,c)
Nested conditionals
Example:
2. positive negative or zero
n=eval(input("enter the value of n:"))

if(n==0):

print("the number is zero")


Output:
else:
enter the value of n:-9
if(n>0):
the number is negative
print("the number is positive")

else:

print("the number is negative")


ITERATION/CONTROL STATEMENTS:
state
while
for

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.

In while loop, test expression is checked first. The body of


the loop is entered only if the test_expression is True.
After one iteration, the test expression is checked again.
This process continues until the test_expression evaluates
to False.
While loop:
Syntax: Flowchart
EXAMPLES

1. program to find sum of n numbers:


2. program to find factorial of a number
3. program to find sum of digits of a number:
4. Program to Reverse the given number:

5. Program to find number is Armstrong number or not

6. Program to check the number is palindrome or not


While loop
Example:
1.Sum of n numbers:
n=eval(input("enter n"))

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:

5. Armstrong number or not n=eval(input("enter a number")) org=n


sum=0 Output:
while(n>0): enter a number153
a=n%10
sum=sum+a*a*a The given number is
n=n//10 Armstrong number

if(sum==org):
print("The given number is Armstrong number")
else:
print("The given number is not
Armstrong number")
While loop
Example:

5. Armstrong number or not n=eval(input("enter a number")) org=n


sum=0 Output:
while(n>0): enter a number121
a=n%10
sum=sum*10+a The given no is palindrome
n=n//10

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

 In range function have to define the start, stop and step


size as range(start,stop,step size). step size defaults to 1 if
not provided.
Flowchart
Syntax
For loop:
For in sequence
The for loop in Python is used to iterate over a sequence
(list, tuple, string). Iterating over a sequence is called
traversal. Loop continues until we reach the last element in
the sequence.

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

1. print nos divisible by 5 not by 10


2. Program to print fibonacci series.
3. Program to find factors of a given number
4. check the given number is perfect number or not

5. check the no is prime or not

6. Print first n prime numbers

7. Program to print prime numbers in range


Example:For loop:
1. print nos divisible by 5 not by 10
n=eval(input("enter a"))

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

print("The num is not a prime")


Output:
break enter a no:7

else: The num is a prime number.

print("The num is a prime number.")


For loop:
Example:
5. check a number is perfect number or not
n=eval(input("enter a number:"))
sum=0
Output:
for i in range(1,n,1):
enter a number:6
if(n%i==0):
sum=sum+i the number is perfect number

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.

 It is a null statement, nothing happens when it is executed.

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.

 The statements inside for loop and statements inside else


will also execute. Output:
Example 1
for i in range(1,6): 2

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.

 The statements inside for loop and statements inside else


will also execute. Output:
Example 1
i=1
2

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

return a,b– return 2 variables

return a,b,c– return 3 variables

return a+b– return expression

return 8– return value


PARAMETERS / ARGUMENTS:
 Parameters are the variables which used in the function
definition. Parameters are inputs to functions. Parameter
receives the input from the function call.

 It is possible to define more than one parameter in the


function definition.
Types of parameters/Arguments:
1. Required/Positional parameters

2. Keyword parameters

3. Default parameters

4. Variable length parameters


Required/ Positional Parameter:
 The number of parameter in the function definition should
match exactly with number of arguments in the function
call.

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, age) Output:

student( “kumar”): Kumar 17

student( “ajay”): Ajay 17


Variable length parameter
 Sometimes, we do not know in advance the number of
arguments that will be passed into a function.

 Python allows us to handle this kind of situation through


function calls with number of arguments.

In the function definition we use an asterisk (*) before the


parameter name to denote this is variable length of
parameter.
Output:
Example
bala ( 102 ,90)
def student( name,*mark):

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.

 A variable with global scope can be used anywhere in the


program.

 It can be created by defining a variable outside the


function.
Local and Global Scope
Local Scope
 A variable with local scope can be used only within the
function .
Function Composition:
 Function Composition is the ability to call one function
from within another function

 It is a way of combining functions such that the result of


each function is passed as the argument of the next
function.

 In other words the output of one function is given as the


input of another function is known as function
composition.
Function Composition:
Example
math.sqrt(math.log(10))

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)

print("the avg is",avg)


Recursion
 A function calling itself till it reaches the base value - stop
point of function call. Example: factorial of a given number
using recursion
Factorial of n
Output:
def fact(n):
if(n==1): enter no. to find fact:5
return 1
else: Fact is 120
return n*fact(n-1)
n=eval(input("enter no. to find
fact:"))
fact=fact(n)
print("Fact is",fact)
Explanation

Recursion
Strings:
Strings

String slices

Immutability

String functions and methods

String module
Strings:
 String is defined as sequence of characters represented
in quotation marks (either single quotes ( „ ) or double
quotes ( “ ).

 An individual character in a string is accessed using a


index. The index should always be an integer (positive
or negative). A index starts from 0 to n-1.

 Strings are immutable i.e. the contents of the string


cannot be changed after it is created.

 Python will get the input at run time by default as a


string. Python does not support character data type. A
string of size 1 can be treated as characters.
Operations on string:
1. Indexing

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.

 Therefore [ ] operator cannot be used on the left side of


an assignment. Syntax to access the method
Stringname.method()
a=”happy birthday”

here, a is the string name.

string built in functions and methods:


 A method is a function that “belongs to” an object.
Operations on string:
Operations on string:
String modules:
 A module is a file containing Python definitions, functions,
statements.

 Standard library of Python is extended as modules.

 To use these modules in a program, programmer needs to import


the module.

 Once we import a module, we can reference or use to any of its


functions or variables in our code.

 There is large number of standard modules also available in python.

 Standard modules can be imported the same way as we import our


user-defined modules.
String modules:
Syntax: Output:
import module_name !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
Example:
0123456789
import string
0123456789abcdefghijklmnopqrstuvwxyzA
BCDEFGHIJ
print(string.punctuation)
KLMNOPQRSTUVWXYZ!"#$%&'()*+,-
print(string.digits)
print(string.printable) ./:;<=>?@[\]^_`{|}~
print(string.capwords("happ
Happy Birthday

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.

 To create array have to import array module in the


program.
Syntax :
import array

Syntax to create array:


Array_name =
module_name.function_name(„datatype‟,[elements])
List as array:
Example:
a=array.array(„i‟,[1,2,3,4])

a- array name

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

n=eval(input("enter number to find Sqrt: "))

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

if(n1%i==0 and n2%i==0):


Output
gcd=i
Enter a number1:8
print(gcd)
Enter a number2:24

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

exp=int(input("Enter exponential value:"))

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

print("the sum is",sum)

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

UNIT 4 - LISTS, TUPLES, DICTIONARIES

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:

 List is an ordered sequence of items. Values in the list are called


elements / items.

 It can be written as a list of comma-separated items (values)


between square brackets[ ].

 Items in the lists can be of different data types.


Operations on list:
1. Indexing
2. Slicing
3. Concatenation
4. Repetitions
5. Updating
6. Membership
7. Comparison
Lists
Lists
List slices:
List slicing is an operation that extracts a subset of
elements from an list and packages them as another list.
Syntax:
Listname[start:stop]

Listname[start:stop:steps]

• default start value is 0

• default stop value is n-1

• [:] this will print the entire list

• [2:2] this will create a empty slice


List slices:
List methods:
• Methods used in lists are used to manipulate the data quickly.

• These methods work only on lists.

• 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:

list name.method name( element/index/list)


List methods:
List methods:
List methods:
List loops:

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.

• Iterating over a sequence is called traversal.

• Loop continues until we reach the last item in the


sequence.

• The body of for loop is separated from the rest of the


code using indentation.

Syntax:

for val in sequence:


1. List using For Loop:
2. List using While loop
• The while loop in Python is used to iterate over a block of
code as long as the test expression (condition) is true.

• When the condition is tested and the result is false, the


loop body will be skipped and the first statement after the
while loop will be executed.

Syntax:

while (condition):

body of while
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

• running. Such loops are called infinite loop.


Example: Output:
a=1 Enter the number 10
you entered:10
while (a==1):
Enter the number 12
you entered:12
n=int(input("enter the number"))
Enter the number 16
you entered:16
print("you entered:" , n)
Mutability:
• Lists are mutable. (can be changed)

• Mutability is the ability for certain types of data to be


changed without entirely recreating it.

• An item can be changed in a list by accessing it directly


as part of the assignment statement.

• Using the indexing operator (square brackets[ ]) on the


left side of an assignment, one of the list items can be
updated.
Mutability:
Aliasing(copying):
• Creating a copy of a list is called aliasing. When you
create a copy both list will be having same memory
location. changes in one list will affect another list.

• Alaising refers to having different names for same list


values.
Aliasing(copying):
• In this a single list object is created and modified using the subscript
operator.

• When the first element of the list named “a” is replaced, the first
element of the list named “b” is also replaced.

• This type of change is what is known as a side effect. This happens


because after the assignment b=a, the variables a and b refer to the
exact same list object.

• They are aliases for the same object. This phenomenon is known as
aliasing.

• To prevent aliasing, a new object can be created and the contents of


the original can be copied which is called cloning.
Clonning:
• To avoid the disadvantages of copying we are using cloning. creating
a copy of a same list of elements with two different memory locations
is called cloning.

• Changes in one list will not affect locations of another list.

• Cloning is a process of making a copy of the list without modifying


the original list.

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.

• If any changes are done in the parameter which refers


within the function, then the changes also reflects back in
the calling function.

• When a list to a function is passed, the function gets a


reference to the list.

• Passing a list as an argument actually passes a reference


to the list, not a copy of the list.

• Since lists are mutable, changes made to the elements


referenced by the parameter change the same list that the
argument is referencing.
List as parameters:
Example 1:

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.

• A tuple is an immutable list. i.e. once a tuple has been


created, you can't add elements to a tuple or remove
elements from the tuple.

• But tuple can be converted into list and list can be


converted in to tuple.
Tuple:

Benefits of Tuple:
• Tuples are faster than lists.

• If the user wants to protect the data from accidental


changes, tuple can be used.

• Tuples can be used as keys in dictionaries, while lists


can't.
Tuple
Operations on Tuples:

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.

• Multiple assignment works by creating a tuple of


expressions from the right hand side, and a tuple of
targets from the left, and then matching each expression
to a target.

• Because multiple assignments use tuples to work, it is


often termed tuple assignment.
Uses of Tuple assignment:
• It is often useful to swap the values of two variables.

Swapping using temporary variable:


a=20
b=50
temp = a Output:
a=b 50, 20
b = temp
print("value after swapping is",a,b)
Uses of Tuple assignment:
Swapping using tuple assignment:
a=20
b=50
(a,b)=(b,a)
print("value after swapping is",a,b)

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.

• All elements in dictionary are placed inside the curly


braces i.e. { }

• Elements in Dictionaries are accessed via keys and not


by their position.

• The values of a dictionary can be any data type.

• Keys must be immutable data type (numbers, strings,


tuple)
Dictionaries:
Methods in dictionary:
Methods in dictionary:
Difference between List, Tuples and dictionary:
Difference between List, Tuples and dictionary:
List Comprehension:

List comprehension offers a shorter syntax when you want to


create a new list based on the values of an existing list.

fruits = ["apple", "banana", "cherry", "kiwi", "mango"]


newlist = []
for x in fruits:
if "a" in x:
newlist.append(x)
print(newlist)

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

list=[ expression for item in list if conditional ]


Advanced list processing:
Nested list:
• List inside another list is called nested list.
Example:
>>> a=[56,34,5,[34,57]]
>>> a[0]
56
>>> a[3]
[34, 57]
>>> a[3][0] >>> a[3][1]
34 57
Illustrative programs:

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.

You might also like