Ge3151 PSPP Study Material

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 151

GE 3151 PROBLEM SOLVING AND PYTHON PROGRAMMING

UNIT I COMPUTATIONAL THINKING AND PROBLEM SOLVING

Fundamentals of Computing – Identification of Computational Problems -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.

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


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

1. Communication: - Flowcharts are better way of communicating the


logic of a system to all concerned.
2. Effective analysis: - With the help of flowchart, problem can be
analyzed in more effective way.
3. Proper documentation: - Program flowcharts serve as a good
program documentation, which is needed for various purposes.
4. Efficient Coding: - The flowcharts act as a guide or blueprint during
the systems analysis and program development phase.
5. Proper Debugging: - The flowchart helps in debugging process.
6. 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:

1. Complex logic: - Sometimes, the program logic is quite complicated.


In that case, flowchart becomes complex and clumsy.
2. Alterations and Modifications: - If alterations are required the
flowchart may require re-drawing completely.
3. Reproduction: - As the flowchart symbols cannot be typed,
reproduction of flowchart becomes a problem.
4. 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.
❖ There is no standard syntax for pseudo code.

Guidelines for writing pseudo code:

❖ Write one statement per line
❖ Capitalize initial keyword
❖ Indent to hierarchy
❖ End multiline structure
❖ Keep statements language independent

Common keywords used in pseudocode

The following gives common keywords used in pseudocodes.


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.

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.
❖ Converting a 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.

Disadvantage:
➢ 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.

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

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:


❖ Data structure plays a vital role in designing and analysis the algorithms.
❖ 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. Pseudocode is usually more precise than natural
language, and its usage often yields more succinct algorithm descriptions.
❖ 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. We can look at such a program as yet
another way ofspecifying the algorithm, although it is preferable to
consider it as the algorithm’s implementation.

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:


FOR( start-value to end-value) DO
Statement
...
ENDFOR

Example: Print n natural numbers


BEGIN
GET n
INITIALIZE i=1
FOR (i<=n) DO
PRINT i
i=i+1
ENDFOR
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
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
Step 4: Display A
Step 5: Stop

Write an algorithm for Calculating area and circumference of circle

Step 1: Start
Step 2: get r value
Step 3: Calculate A=3.14*r*r
Step 4: Calculate C=2.3.14*r
Step 5: Display A,C
Step 6: Stop

Write an algorithm for Calculating simple interest

Step 1: Start
Step 2: get P, n, r value
Step3:Calculate
SI=(p*n*r)/100
Step 4: Display S
Step 5: Stop
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
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

To check positive or negative number

Step 1: Start
Step 2: get num
Step 3: check if(num>0) print a is positive
Step 4: else num is negative
Step 5: Stop
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
Step 5: Stop

BEGIN
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

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

1. What is an algorithm?
Algorithm is an ordered sequence of finite, well defined, unambiguous
instructions for completing a task. It is an English-like representation of the
logic which is used to solve the problem. It is a step- by-step procedure for
solving a task or a problem. The steps must be ordered, unambiguous and finite
in number.

2. Write an algorithm to find minimum of 3 numbers in a list.


ALGORITHM : Find Minimum of 3 numbers in a list
Step 1: Start
Step 2: Read the three numbers A, B, C
Step 3: Compare A and B.
If A is minimum, go to step 4 else go to step 5. Step 4: Compare A and C.
If A is minimum, output “A is minimum” else output “C is minimum”. Go to
step 6.
Step 5: Compare B and C.
If B is minimum, output “B is minimum” else output “C is minimum”.
Step 6: Stop

3. List the building blocks of an algorithm.


The building blocks of an algorithm are
• Statements
• Sequence
• Selection or Conditional
• Repetition or Control flow
• Functions

4. Define statement. List its types.
Statements are instructions in Python designed as components for algorithmic
problem solving, rather than as one-to-one translations of the underlying
machine language instruction set of the computer.
There are three types of high-level programming language statements
Input/output statements make up one type of statement. An input statement
collects a specific value from the user for a variable within the program. An
output statement writes a message or the value of a program variable to the
user’s screen.
5. Write the pseudo code to calculate the sum and product of two numbers
and display it.
INITIALIZE variables sum, product, number1, number2 of type real
PRINT “Input two numbers”
READ number1, number2
sum = number1 + number2
PRINT “The sum is “, sum
COMPUTE product = number1 * number2
PRINT “The Product is “, product
END program

6. How does flow of control work?


Control flow (or flow of control) is the order in which individual statements,
instructions or function calls of an imperative program are executed or
evaluated. A control flow statement is a statement in which execution results in
a choice being made as to which of two or more paths to follow.

7. What is a function?
Functions are "self-contained" modules of code that accomplish a specific task.
Functions usually "take in" data, process it, and "return" a result. Once a
function is written, it can be used over and over and over again. Functions can
be "called" from the inside of other functions.

8. Write the pseudo code to calculate the sum and product displaying the
answer on the monitor screen.
INITIALIZE variables sum, product, number1, number2 of type real
PRINT “Input two numbers”
READ number1, number2 sum = number1 + number2
PRINT “The sum is “, sum
COMPUTE product = number1 * number2
PRINT “The Product is “, product
END program
9. Give the rules for writing Pseudo codes.
• Write one statement per line.
• Capitalize initial keywords.
• Indent to show hierarchy.
• End multiline structure.
• Keep statements to be language independent.

10. Give the difference between flowchart and pseudo code.


Flowchart and Pseudo code are used to document and represent the algorithm.
In other words, an algorithm can be represented using a flowchart or a pseudo
code. Flowchart is a graphical representation of the algorithm. Pseudo code is a
readable, formally styled English like language representation of the algorithm.

11. Define a flowchart.


A flowchart is a diagrammatic representation of the logic for solving a task. A
flowchart is drawn using boxes of different shapes with lines connecting them
to show the flow of control. The purpose of drawing a flowchart is to make the
logic of the program clearer in a visual form.

12. Give an example of iteration.


a=0
for i from 1 to 3 // loop three times
{
a=a+I // add the current value of i to a
}
print a // the number 6 is printed (0 + 1; 1 + 2; 3 + 3)

13. Write down the rules for preparing a flowchart.


While drawing a flowchart, some rules need to be followed—
(1) A flowchart should have a start and end,
(2) The direction of flow in a flowchart must be from top to bottom and left
to right, and
(3) The relevant symbols must be used while drawing a flowchart.

14. List the categories of Programming languages.


Programming languages are divided into the following categories:
Interpreted, Functional, Compiled, Procedural, Scripting, Markup, Logic-Based,
Concurrent and Object-Oriented Programming Languages

15. Mention the characteristics of an algorithm.


• Algorithm should be precise and unambiguous.
• Instruction in an algorithm should not be repeated infinitely.
• Ensure that the algorithm will ultimately terminate.
• Algorithm should be written in sequence.
• Algorithm should be written in normal English.
• Desired result should be obtained only after the algorithm terminates.

16. Compare machine language, assembly language and high-level
language.
Machine language is a collection of binary digits or bits that the
computer reads and interprets.
This language is not easily understandable by the human.
An assembly language directly controls the physical hardware. A program
written in assembly language consists of a series of instructions mnemonics that
correspond to a stream of executable instructions, when translated by an
assembler can be loaded into memory and executed. The programs written in
this language are not portable and the debugging process is also not very easy.
A high level language is much more abstract, that must be translated or
compiled in to machine language. It is easily understandable and the programs
are portable. Debugging the code is easy and the program written is not
machine dependent.

17. What is the difference between algorithm and pseudo code?


An algorithm is a systematic logical approach used to solve problems in a
computer while pseudo code is the statement in plain English that may be
translated later to a programming language. Pseudo code is the intermediary
between algorithm and program.

18. List out the simple steps to develop an algorithm. Algorithm


development process consists of five major steps.
Step 1: Obtain a description of the problem.
Step 2: Analyze the problem.
Step 3: Develop a high-level algorithm.
Step 4: Refine the algorithm by adding more detail.
Step 5: Review the algorithm.

19. Give the differences between recursion and iteration.

20. What are advantages and disadvantages of recursion?

What is computing ?
It is any type of calculation that includes both mathematical and non- arithmetical
steps and follows a well defined model.
Processor
Data -------> Convert or compute -------> information

1) What are the factors used to judge the qualities of the algorithm?
1. Less time
2. Less memory
3. Higher accuracy
4. Sequence
5.Generability

2) What are the characteristics or properties or rules of algorithm?

1. The algorithm must begin with “START “statement.


2. The algorithm must end with “END “statement.
3. The algorithm should be written in sequence.
4. The algorithm should have “finite number of steps”.
5. The algorithm should be written in simple English.
6. Eah and every statement in algorithm should be short and precise.
7. The instruction in algorithm should be repeated finite number of steps.
8. The final statement must give output (result) from the algorithm.

3) What are the demerits or disadvantages of algorithm?


1. Algorithm is Time consuming.
2. Difficult to show Branching and Looping in Algorithms.
3. Big tasks are difficult to put in Algorithms.

4) What are the advantages of algorithm?

1. It is a step-wise representation of a solution to a given problem, which makes it easy to


understand.
2. An algorithm uses a definite procedure.
3. It is not dependent on any programming language, so it is easy to understand for
anyone even without programming knowledge.
4. Every step in an algorithm has its own logical sequence so it is easy to debug.
5. By using algorithm, the problem is broken down into smaller pieces or steps
hence, it is easier for programmer to convert it into an actual program.

5) What are the building blocks of algorithm?


1. Statement
2. State
3. Sequential control
4. Selection or conditional control
5. Repetition or control flow
6. Functions

1. Find minimum in a list


7. Algorithm:
8. Step 1: Start
9. Step 2: Read n
10. Step 3:Initialize i=0
11. Step 4: If i<n, then goto
12. step 4.1, 4.2 else goto
13. step 5 Step4.1: Read a[i]
14. Step 4.2: i=i+1 goto step 4
15. Step 5: Compute min=a[0]
16. Step 6: Initialize i=1
17. Step 7: If i<n, then go to step 8 else goto step 10
18. Step 8: If a[i]<min, then goto
19. step 8.1,8.2 else goto 8.2
20. Step 8.1: min=a[i]
21. Step 8.2: i=i+1 goto 7
22. Step 9: Print min
23. Step 10: Stop

2. Insert a card in a list of sorted cards


Algorithm:
Step 1: Start
Step 2: Read n
Step 3:Initialize i=0
Step 4: If i<n, then goto step 4.1, 4.2 else goto step 5
Step4.1: Read a[i]
Step 4.2: i=i+1 goto step 4
Step 5: Read item
Step 6: Calculate i=n-1
Step 7: If i>=0 and item<a[i], then go to step 7.1, 7.2 else goto step 8
Step 7.1: a[i+1]=a[i]
Step 7.2: i=i-1 goto step 7
Step 8: Compute a[i+1]=item
Step 9: Compute n=n+1
Step 10: If i<n, then goto step 10.1, 10.2 lse goto st 11
Step10.1: Print a[i]
Step10.2: i=i+1 goto step 10
Step 11: Stop
3. Tower of Hanoi
Algorithm:
Step 1: Start
Step 2: procedure HANOI (disk, source,dest,aux)
Step 3: If disk==0,
Step 3.1 : move disk from source to dest
Step 4: ELSE

Step 4.1 : HANOI (disk-1,source,aux,dest)


Step 4.2 : MOVE disk from source to dest
Step 4.3 : HANOI (disk-1,aux,dest,source)
Step 5 :END -IF
Step 6: Stop

Pseudcode:
procedure HANOI (disk, source,dest,aux)
If disk==0,
move disk from source to dest
ELSE
HANOI (disk-1,source,aux,dest)
MOVE disk from source to dest
HANOI (disk-1,aux,dest,source)
END -IF
END procedure

Flowchart:
Procedure to solve Tower of Hanoi
The goal of the puzzle is to move all the disks from leftmost peg to rightmost
peg.
1. Move only one disk at a time.
2. A larger disk may not be p1aced on top of a smaller disk. For example,
consider n=3 disks
4. Guess an integer in a range
Algorithm:
Step1: Start
Step 2: Declare hidden, guess
Step 3: Compute hidden= Choose a random value in a range
Step 4: Read guess
Step 5: If guess=hidden, then
Print Guess is hit
Else
Print Guess not hit
Print hidden
Step 6: Stop
INTRODUCTION TO PYTHON:

Python is a general-purpose interpreted, interactive, object-oriented,


and high-level programming language.

It was created by Guido van Rossum during 1985- 1990.

Python got its name from “Monty Python’s flying circus”. Python was
released in the year 2000.

❖ Python is interpreted: Python is processed at runtime by the


interpreter. You do not need to compile your program before executing it.

❖ Python is Interactive: You can actually sit at a Python prompt and
interact with the interpreter directly to write your programs.

❖ Python is Object-Oriented: Python supports Object-Oriented style or
technique of programming that encapsulates code within objects.

❖ Python is a Beginner's Language: Python is a great language for the
beginner-level programmers and supports the development of a wide
range of applications.

Python Features:

❖Easy-to-learn:Python is clearly defined and easily readable.


The structure of the program is very simple. It uses few keywords.

❖ Easy-to-maintain: Python's source code is fairly easy-to-maintain.



❖ Portable: Python can run on a wide variety of hardware platforms and
has the same interface on all platforms.

❖ Interpreted: Python is processed at runtime by the interpreter. So,
there is no need to compile a program before executing it. You can simply
run the program.

❖ Extensible: Programmers can embed python within their C,C++,Java
script ,ActiveX, etc.

❖ Free and Open Source: Anyone can freely distribute it, read the source
code, and edit it.

❖ High Level Language: When writing programs, programmers
concentrate on solutions of the current problem, no need to worry about
the low level details.

❖ Scalable: Python provides a better structure and support for large
programs than shell scripting.

Python interpreter:

Interpreter: To execute a program in a high-level language by translating


it one line at a time.

Compiler: To translate a program written in a high-level language into a


low-level language all at once, in preparation for later execution.
MODES OF PYTHON INTERPRETER:

Python Interpreter is a program that reads and executes Python code. It


uses 2 modes of Execution.

1. Interactive mode
2. Script mode
1. Interactive mode:

❖ Interactive Mode, as the name suggests, allows us to interact with OS.


❖ When we type Python statement, interpreter displays the
result(s) immediately.
Advantages:
❖ Python, in interactive mode, is good enough to learn, experiment or
explore.
❖ Working in interactive mode is convenient for beginners and for testing
small pieces of code.
Drawback:
❖ We cannot save the statements and have to retype all the statements
once again to re-run them.

In interactive mode, you type Python programs and the interpreter


displays the result:
>>> 1 + 1

2. Script mode:

❖ In script mode, we type python program in a file and then use


interpreter to execute the content of the file.

❖ Scripts can be saved to disk for future use. Python scripts have
the extension .py, meaning that the filename ends with .py

❖ Save the code with filename.py and run the interpreter in script mode
to execute the script.

Integrated Development Learning Environment (IDLE):


❖ Is a graphical user interface which is completely written in Python.
❖ It is bundled with the default implementation of the python language
and also comes with optional part of the Python packaging.

Features of IDLE:
Multi-window text editor with syntax highlighting.
❖ Auto completion with smart indentation.
Python shell to display output with syntax highlightin

Integrated Development Learning Environment (IDLE):


❖ Is a graphical user interface which is completely written in Python.
❖ It is bundled with the default implementation of the python language
and also comes with optional part of the Python packaging.

Features of IDLE:
Multi-window text editor with syntax highlighting.
❖ Auto completion with smart indentation.
Python shell to display output with syntax highlighting.

VALUES AND DATA TYPES

Value:
Value can be any letter ,number or string.
Eg, Values are 2, 42.0, and 'Hello, World!'. (These values belong
to different datatypes.)
Data type:
Every value in Python has a data type.
It is a set of values, and the allowable operations on those values.
Python has four standard data types:
Numbers:

❖ Number data type stores Numerical Values.


❖ This data type is immutable [i.e. values/items cannot be changed].
❖ Python supports integers, floating point numbers and complex numbers.
They are defined as,

Sequence:

❖ A sequence is an ordered collection of items, indexed by positive


integers.
❖ It is a combination of mutable (value can be changed) and
immutable (values cannot be changed) data types.
❖ There are three types of sequence data type available in Python, they are

1. Strings
2. Lists
3. Tuples

1. Strings
➢ A String in Python consists of a series or sequence of characters -
letters, numbers, and special characters.
➢ Strings are marked by quotes:
• single quotes (' ') Eg, 'This a string in single quotes'
• double quotes (" ") Eg, "'This a string in double quotes'"
• triple quotes(""" """) Eg, This is a paragraph. It is made up of multiple
lines and sentences."""
➢ Individual character in a string is accessed using a subscript (index).
➢ Characters can be accessed using indexing and slicing operations
Strings are immutable i.e. the contents of the string cannot be changed after
it is created.

Indexing:

• Positive indexing helps in accessing the string from the beginning


• Negative subscript helps in accessing the string from the end.
• Subscript 0 or –ve n(where n is length of the string) displays the first
element.
Example: A[0] or A[-5] will display “H”
• Subscript 1 or –ve (n-1) displays the second element.
Example: A[1] or A[-4] will display “E”

Operations on string:
i. Indexing
ii. Slicing
iii. Concatenation
iv. Repetitions
v. Member ship

2. 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:
Indexing
Slicing
Concatenation
Repetitions
Updation, Insertion, Deletion
3. 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.
❖ Benefit of Tuple:
❖ Tuples are faster than lists.
❖ If the user wants to protect the data from accidental changes, tuple can
be used.
❖ Tuples can be used as keys in dictionaries, while lists can't.

Basic Operations:

Altering the tuple data type leads to error. Following error occurs when
user tries to do.

Mapping

-This data type is unordered and mutable.


-Dictionaries fall under Mappings.

Dictionaries:

❖ Lists are ordered sets of objects, whereas dictionaries are unordered


sets.
❖ Dictionary is created by using curly brackets. i,e. {}
❖ Dictionaries are accessed via keys and not via their position.
❖ A dictionary is an associative array (also known as hashes). Any key of
the dictionary is associated (or mapped) to a value.
❖ The values of a dictionary can be any Python data type. So dictionaries
are

unordered key-value-pairs(The association of a key and a value is called


a key-value pair )
Dictionaries don't support the sequence operation of the sequence data
types like strings, tuples and lists.

ARIABLES:

❖ A variable allows us to store a value by assigning it to a name, which can


be used later.
❖ Named memory locations to store values.
❖ Programmers generally choose names for their variables that are
meaningful.
❖ It can be of any length. No space is allowed.
❖ We don't need to declare a variable before using it. In Python, we simply
assign a value to a variable and it will exist.

Assigning value to variable:


Value should be given on the right side of assignment operator(=) and
variable on left side.
>>>counter =45
print(counter)
Assigning a single value to several variables simultaneously:
>>> a=b=c=100
Assigning multiple values to multiple variables:
>>> a,b,c=2,4,"ram"

KEYWORDS:

❖ Keywords are the reserved words in Python.


❖ We cannot use a keyword as variable name, function name or any other
identifier.
❖ They are used to define the syntax and structure of the Python language.
❖ Keywords are case sensitive.

IDENTIFIERS:

Identifier is the name given to entities like class, functions, variables
etc. in Python.
❖ 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 (_).
❖ all are valid example.
❖ An identifier cannot start with a digit.
❖ Keywords cannot be used as identifiers.
❖ Cannot use special symbols like !, @, #, $, % etc. in our identifier.
❖ Identifier can be of any length.
Example:
Names like myClass, var_1, and this_is_a_long_variable

Statements:
-Instructions that a Python interpreter can executes are called statements.
-A statement is a unit of code like creating a variable or displaying a value.
>>> n = 17
>>> print(n)
Here, The first line is an assignment statement that gives a value to n.
The second line is a print statement that displays the value of n.

Expressions:
-An expression is a combination of values, variables, and operators.
-A value all by itself is considered an expression, and also a variable.
So the following are all legal expressions:
>>> 42
42
>>> a=2
>>> a+3+2
7
>>> z=("hi"+"friend")
>>> print(z)
Hifriend

INPUT AND OUTPUT

INPUT: Input is data entered by user (end user) in the program.


In python, input () function is available for input.
Syntax for input() is:
variable = input (“data”)
Example:
>>> x=input("enter the name:") enter the name: george
>>>y=int(input("enter the number"))
enter the number 3
#python accepts string as default data type. conversion is required for type.

OUTPUT: Output can be displayed to the user using Print statement .


Syntax:
print (expression/constant/variable)
Example:
print ("Hello") Hello

COMMENTS:

❖ A hash sign (#) is the beginning of a comment.


❖ Anything written after # in a line is ignored by interpreter.
Eg:percentage = (minute * 100) / 60 # calculating percentage of an
hour
❖ Python does not have multiple-line commenting feature. You have to
comment each line individually as follows :

Example:
# This is a comment.
# This is a comment, too.
# I said that already.

DOCSTRING:

❖ Docstring is short for documentation string.


❖ It is a string that occurs as the first statement in a module, function,
class, or method definition. We must write what a function/class does in
the docstring.
❖ Triple quotes are used while writing docstrings.

Syntax:
functionname__doc.__

TUPLE ASSIGNMENT

❖ An assignment to all of the elements in a tuple using a single assignment


statement.
❖ Python has a very powerful tuple assignment feature that allows a
tuple of variables on the left of an assignment to be assigned values from a
tuple on the right of the assignment.
❖ The left side is a tuple of variables; the right side is a tuple of values.
❖ Each value is assigned to its respective variable.
❖ All the expressions on the right side are evaluated before any of the
assignments. This feature makes tuple assignment quite versatile.
❖ Naturally, the number of variables on the left and the number of values
on the right have to be the same.
>>> (a, b, c, d) = (1, 2, 3)
OPERATORS:

❖ Operators are the constructs which can manipulate the value of


operands.
❖ Consider the expression 4 + 5 = 9. Here, 4 and 5 are called
operands and + is called operator

Types of Operators:
-Python language supports the following types of operators
• Arithmetic Operators
• Comparison (Relational) Operators
• Assignment Operators
• Logical Operators
• Bitwise Operators
• Membership Operators
• Identity Operators

Arithmetic operators:

They are used to perform mathematical operations like addition,


subtraction, multiplication etc. Assume, a=10 and b=5
Comparison (Relational) Operators:

• Comparison operators are used to compare values.


• It either returns True or False according to the condition. Assume,
a=10 and b=5
a>=b=> True
Assignment Operators:

-Assignment operators are used in Python to assign values to variables.


Logical Operators:

-Logical operators are the and, or, not operators.

Example
a = True
b = False
print('a and b is',a and b)
print('a or b is',a or b)
print('not a is',not a)

Output
x and y is False
x or y is True
not x is False

Bitwise Operators:

A bitwise operation operates on one or more bit patterns at the level of


individual Bits
Example:
Let x = 10 (0000 1010 in binary) and
y = 4 (0000 0100 in binary)

Membership Operators:

❖ Evaluates to find a value or a variable is in the specified sequence of


string, list, tuple, dictionary or not.
❖ Let, x=[5,3,6,4,1]. To check particular item in list or not, in and not
in operators are used.

Example:
x=[5,3,6,4,1]
>>> 5 in x
True
>>> 5 not in x
False

Identity Operators

They are used to check if two values (or variables) are located on the same
part of the memory.

Example
x=5
y=5
x2 = 'Hello'
y2 = 'Hello'
print(x1 is not y1)
print(x2 is y2)

Output
False
True
OPERATOR PRECEDENCE:

When an expression contains more than one operator, the order of


evaluation depends on the order of operations.
-For mathematical operators, Python follows mathematical convention.

-The acronym PEMDAS (Parentheses, Exponentiation, Multiplication,


Division, Addition, Subtraction) is a useful way to remember the rules:

❖ Parentheses have the highest precedence and can be used to force an


expression to evaluate in the order you want. Since expressions in
parentheses are evaluated first, 2 * (3-1)is 4, and (1+1)**(5-2) is 8.

❖ You can also use parentheses to make an expression easier to read, as in
(minute *100) / 60, even if it doesn’t change the result.

❖ Exponentiation has the next highest precedence, so 1 + 2**3 is 9, not 27,


and 2 *3**2 is 18, not 36.

❖ Multiplication and Division have higher precedence than Addition and
Subtraction. So 2*3-1 is 5, not 4, and 6+4/2 is 8, not 5.

❖ Operators with the same precedence are evaluated from left to right
(except exponentiation).

Example:

a=9-12/3+3*2-1
a=?
a=9-4+3*2-1
a=9-4+6-1
a=5+6-1
a=11-1
a=10

A=2*3+4%5-3/2+6
A=6+4%5-3/2+6
A=6+4-3/2+6
A=6+4-1+6
A=10-1+6
A=9+6
A=15

find m=?
m=-43||8&&0||-2
m=-43||0||-2
m=1||-2
m=1

a=2,b=12,c=1
d=a<b>c
d=2<12>1
d=1>1
d=0

a=2,b=12,c=1
d=a<b>c-1
d=2<12>1-1
d=2<12>0
d=1>0
d=1

a=2*3+4%5-3//2+6
a=6+4-1+6
a=10-1+6
a=15

ILLUSTRATIVE PROGRAMS
Program for SWAPPING (Exchanging )of values
a = int(input("Enter a value "))
b = int(input("Enter b value "))
c=a
a=b
b=c
print("a=",a,"b=",b,)

Output
Enter a value 5
Enter b value 8
a=8
b=5

Program to find distance between two points


import math
x1=int(input("enter x1"))
y1=int(input("enter y1"))
x2=int(input("enter x2"))
y2=int(input("enter y2"))
distance =math.sqrt((x2-x1)**2)+((y2-
y1)**2)
print(distance)

Output
enter x1 7
enter y1 6
enter x2 5
enter y2 7
2.5
Program to circulate n numbers
a=list(input("enter the list"))
print(a)
for i in range(1,len(a),1):
print(a[i:]+a[:i])

Output:
enter the list '1234'
['1', '2', '3', '4']
['2', '3', '4', '1']
['3', '4', '1', '2']
['4', '1', '2', '3']

Unit-3 Control flow, Functions and


Strings

1) Boolean:
1. Boolean data type have two values.They are 0 and 1.
2. 0 represents False.
3. 1 represents True.
4. True and False are keywords.
5. Boolean values respond to logical operators (and / or)

Example:
>>>3==5
False
>>>6==6
True
>>>True+True
2
>>>False+True
1

2) CONDITIONALS:
• Conditional if
• Alternative if…..else
• Chained if…elif….else
• Nested if…..else

✓ Conditional if :
1) The if statement is a decision making statement.
2) The conditional if is used to test a condition.
3) Conditional if is used to test a condition.If the condition is
true the statements inside if will be executed.
Syntax:
if (Condition):
statement 1
Flow chart :

Example program:

mark = int(input(“Enter the marks:”))


if (mark>=35):
print(“The student is pass”)

Output:
Enter the marks:98
The student is pass

✓ Alternative if…..else :
• It is a two way decision making statement.
• In the alternative the condition must be true or false.
• In this else statement can be combined with the 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 get executed.
Syntax:
if (condition 1):
statement 1
else:
statement 2

Flow chart :
Example programs:
Output:
#Program to find odd or even
n=int(input(“Enter the number:”)) Enter the number:5
if (n%2==0): odd number
print(“even number”)
else:
print(“odd number”)

#Greater among two numbers Output:


a=int(input(“Enter a value:”)) Enter a value:76
b=int(input(“Enter b value:”)) Enter b value:98
if (a>b): B is greater
print(“A is greater”)
else:
print(“B is greater”)

#Program to find leap year or not Output:


year=int(input(“Enter the year:”)) Enter the year:2020
if (n%2==0): Leap year
print(“leap year”)

else:
print(“not leap year”)
#Program to find eligible to vote or not Output:
age=int(input(“Enter your age:”)) Enter your age:26

if (age>=18): Eligible to vote


print(“eligible to vote”)
else:
print(“not eligible to vote”)

✓ Chained if…..elif…else :
• The elif is short for else if.
• This is used to check more than one condition.
• If the condition 1 is false, it checks the condition 2 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 can have only one else block, but it can have
multiple elif blocks.

Syntax :
if (condition 1):
statement 1
elif (condition 2):
statement 2

elif (condition 3):


statement 3
else :
default statement

Flow chart :
Example programs :

#student mark statement


mark = int(input(“Enter your marks:”)) Output :
if (mark>=90): Enter your
marks:78
print(“Grade:O”) Grade:B
elif (mark>=80):
print(“Grade:A”)
elif (mark>=70):
print(“Grade:B”)
elif(mark>=60):
print(“Grade:C”)
elif(mark>=50):
print(“Grade:D”)
else:
print(“Fail”)

#traffic light system


Colour=input(“Enter colour of light:”) Output :
if (colour==”Green”): Enter colour of
light : Green
print(“GO”) GO
elif (colour==”Yellow”):
print(“Get Ready”)
else:
print(“Stop”)

#Compare two numbers


a =int(input(“Enter a value:”) Output :
b =int(input(“Enter b value:”)) Enter a value: 5
if(a==b): Enter b value: 5
print(“a and b are equal”) A and B are equal
elif(a>b):
print(“a is greater than b”)
else:
print(“b is greater than a”)

#Roots of quadratic equation


a =int(input(“Enter a value:”)) Output :
b =int(input(“Enter b value:”)) Enter a value: 1
c =int(input(“Enter c value:”)) Enter b value: 0
d=(b*b-4*a*c) Enter c value: 0
if(d==0): Same and real
roots
print(“same and real roots”)
elif(d>0):
print(“different real roots”)
else:
print(“imaginary roots”)

✓ NESTED CONDITIONALS :
One conditional can also be nested within another.Any number
of condition can be nested inside one another.In this, if condition is
true it checks another if condition 1.If both the conditions are true
statement 1 get executed otherwise statement 2 get executed. If the
condition is false statement 3 get executed.

Syntax:
if (condition):
if (condition 1):
statement 1
else:
statement 2
else:
statement 3

Flow chart:

Example programs :

#greatest among three numbers


a=int(input(“Enter a value:”))
b=int(input(“Enter b value:”))
c=int(input(“Enter c value:”))
if(a>b):
if(a>c):
print(“A is greater ”,a)
else:

print(“C is greater ”,c) Output :


else: Enter a value: 8
if(b>c): Enter b value: 1
print(“B is greater ”,b) Enter c value: 9
else: C is greater 9
print(“C is greater ”,c)
#positive negative or zero
n=int(input(“Enter n value:”))
if(n==0):
print(“the number is zero”)
if(n>0):
print(“the number is positive”)
else:
print(“the number is negative”)

Output :
Enter n value:-9
The number is negative

ITERATION/CONTROL STATEMENTS :

Repeated executuion of set of statements is called iteration or


looping.

• 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 statements 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 expresssion is true.
• After one iteration the test expression is checked again.This
process continues until the test expression evaluates to false.
• In pyython,the body of the lopp is determined through
indentation.
• The statements inside the while starts indentation and the first
unindented line marks the end.

Syntax :
Initial value
While(condition):
Body of while loop
Increement

Flowchart :

Example programs :

#sum of n numbers
n=int(input(“Enter n value:”)) Output :
i=1 Enter n value :10
sum=0 55
while(i<=n):
sum=sum+i
i=i+1
print(sum)

#Factorial of n numbers
n=int(input(“Enter n value:”)) Output :
i=1 Enter n value: 5
fact=1 120
while(i<=n):
fact=fact*i
i=i+1
print(fact)

#sum of digits ofa number


n=int(input(“Enter n value:”)) Output :
sum=0 Enter n value:
123
while(n>0): 6
a=n%10
sum=sum+a
n=n//10
print(sum)

#Reverse the given number


n=int(input(“Enter n value:”)) Output :
sum=0 Enter n value:
123
while(n>0): 321
a=n%10
sum=sum*10+a
n=n//10
print(sum)

#Armstrong number or not


n=int(input(“Enter n value:”)) Output :
org=n Enter n value:153
sum=0 The given number is
armstrong while(n>0):
a=n%10
sum=sum+a*a*a
n=n//10
if(sum==org):
print(“the given number is armstrong number”)
else:
print(“the given number is not armstrong number”)

#Palindrome or not
n=int(input(“Enter n value:”)) Output :
org=n Enter n value :121
sum=0 The given number is
palindrome
while(n>0):
a=n%10
sum=sum*10+a
n=n//10
if(sum==org):
print(“the given number is palindrome”)
else:
print(“the given number 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,stepsize).stepsize defaults to 1 if not provided.

Syntax :
for i range(start,stop,steps):
body of for loop
Flowchart :

for in sequence :
• The for loop in python is 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.

Syntax :
for i in sequence:
print(i)

sequence can be a list,strings or tuples :


n sequences examples output
o

For loop in string for i in “Ramu”: R


print(i) A
1
M
U
2 For loop in list for i in [2,3,5,6,9]: 2
print(i) 3
5
6
9
For loop in tuple for i in (2,3,1): 2
3 print(i) 3
1

Example programs :

#print nos divisible by 5 not by 10


n=int(input(“Enter n value:”))
for i in range(1,n,1):
if(i%5==0 and i%10!=0):
print(i)

Output :
Enter n value: 30
5
15
25

#Fibonacci series
a=0
b=1
n=int(input(“Enter the no.of terms:”))
print(“Fibonacci series:”)
print(a,b)
for i in range(1,n,1):
c=a+b
print(c)
a=b
b=c

Output :
Enter the no. of terms :6
Fibonacci series:
01
1
2
3
5
8

#Find factors of a number


n=int(input(“Enter n value:”))
for i in range(1,n+1,1):
if(n%i==0):
print(i)

Output :
Enter n value : 10
1
2
5
10

#check the number is prime or not

n=int(input(“Enter n value:”))
for i in range (2,n):
if(n%i==0):
print(“The number is not a prime”)
break
else:
print(“The number is a prime number”)

Output :
Enter n value: 7
The number is a prime number

#program to print first n prime numbers


n=int(input(“Enter no.of prime number to be displayed:”))
count=1
n=2
while(count<=n):
for i in range (2,n):
if(n%i==0):
break
else:
print(n)
count=count+1
n=n+1

Output :
Enter no.of prime numbers to be displayed:5
2
3
5
7
11

LOOP CONTROL STRUCTURES :

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.
Syntax :
While(test expression):
If(condition for break):
Break
Flowchart :

Example program :
for i in “welcome”: Output :
if(i==”c”): w
break e

print(i) l

CONTINUE STATEMENT :
It terminates the current iteration and transfer the control to the
next iteration in the loop.

Syntax :
While(test expression):
If(condition for continue):
Continue
Flowchart :

Example program :
for i in “welcome”: Output :
if(i==”c”): w
continue e
print(i) l
o
m
e

PASS STATEMENT :
• It is 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
Example program : Output :
for i in “welcome”: w

if(i==”c”): e
pass l
print(i) c
o
m
e
Differences between BREAK and CONTINUE :

break Continue

• It terminates the current loop • It terminates the current


and executes the remaining iterationand transfer the
statement outside the loop. control to the next iteration in
the loop.

• Syntax : • Syntax :
Break Continue

for i in “welcome”: for i in “welcome”:


if(i==”c”): if(i==”c”):
break break
print(i) print(i)
• Output : • Output :
w w
e e
l l
o
m
e

Functions :

• Fruitful function
• Void function
• Return values
• Parameters
• Local and global scope
• Function composition
• Recursion

1. FRUITFUL FUNCTION :
A function that returns a value is called fruitful function.
Example:
Root=sqrt(25)
Example:
def add():
a=10
b=20
c=a+b
return c
c=add()
print(c)

2. VOID FUNCTION :
A function that performs action but don’t returns any
value.
Example :
Print(“Hello”)
Example :
def add():
a=10
b=20
c=a+b
print(c)
add()

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

4. PARAMETERS/ARGUMENTS :
• Parameters are the variables which is used in the function
definition.
• parameters are inputs to function.
• Parameters receives the input from the function call.
• It is possible to define more than one parameter in the function
definition.

TYPES OF PARAMETERS/ARGUMENTS :
a. Required/positional parameters
b. Keyword parameters
c. Default parametrs
d. Variable length parameters

a. Required/positional parameters :
The number of parameter in the function definition should
match with number of arguments in the function call.
Example :
def student(roll,name):
print(roll,name)
student(98 ,”john”)
Output :
98 john

b. Keyword parameters :
When we call a function with some values these values get
assigned to
the parameter according to that position. But when we call a function
in keyword parameter , the order of the arguments can be changed.

Example :
def student(name,roll,mark):
print (name,roll,mark)
student (90.102,’bala’)
Output:
90 120 bala

c. Default parameters :
Python allows function parameters to have default values; if
the function is called without the argument, the argument gets its
default values in function definition.

Example :
def student (name,age=17):
print(name,age)
student(“kumar”)
student(“ajay”)
Output:
Kumar 17
Ajay 17

d. Variable length parameters :


Sometimes we don’t 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 can use asterisks(*) before
the parameter name to denote this is variable length parameter.

Example :
def student(name,*mark):
print(name,mark)
student(“bala”,102,90)
Output :
bala(102,90)

LOCAL AND GLOBAL SCOPE :

Global scope :
The scope of 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.
Example:
a=50------------------------------------>global variable
def add():
b=20---------------------------->local variable
c=a+b
print(c)
def sub():
b=30---------------------------->local variable
c=a-b
print(c)
Output :
70
20

Local scope :
A variable with local scope can be used within the
function.
Example :
def add():
b=20
c=a+b
print(c)
Output :
70

5. FUNCTION COMPOSITION :
I. Function composition is the ability to call one function
from within another function.
II. It is the way of combining functions such that the result
of each function is passed as the arguments of the next
function.
III. In other words,the output of one function is given as
the output of the other function is known as function
composition.

Example:
math.sqrt(math.log(10))
def add(a,b):
c=a+b
return c
def mul(c,d):
e=c*d
return e
c=add(10,20)
e=mul(c,30)
print(e)
Output:
900

6. RECURSION :
A function calling itself till it reaches the base value-stop point of
a function call. Example factorial of a given number using
recursion function

Example :
def fact(n):
if(n==1):
return 1
else:
return n*fact(n-1)
n=int(input(“Enter n value:”))
fact=fact(n)
print(“fact is”,fact)

Output :
Enter n value: 5
120
#sum of n numbers using recursion
def sum(n):
if(n==1):
return 1
else:
return n*sum(n-1)
n=int(input(“Enter n value:”))
sum=sum(n)
print(“sum is”,sum)
Output :
Enter n value:10
Sum is 55

STRINGS :
▪ Strings
▪ String slices
▪ Immutability
▪ String functions and methods
▪ String modules

STRINGS :
• String is defined as sequence ofcharacters represented in
quotation marks(either single quotes(‘) or double quotes
(“) ).
• An individual character in 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 the contents of the
string can’t be changed after it is created.
• Python will get an input at the run time by default as a
string.
• Python does not support character data type. A string of
size 1 can be treated as a character.
1. Single quotes (‘ ‘)
2. Double quotes(“ “)
3. Triple quotes(“”” “””)
OPERATIONS ON A STRING :
1. Indexing
2. Slicing
3. Concatenation
4. Repetitions
5. Membership

1. INDEXING :
The initial character or substring takes zero as its index
and the rest are numbered sequentially.

SYNTAX :
String_variable[index number]

String A H E L L O
Positive
index 0 1 2 3 4
Negative
index -5 -4 -3 -2 -1

a. Positive indexing helps in across the string from the beginning.


>>>a=”Hello”
>>>print(a[0])
>>>H
b. Negative indexing helps in across the string from the end.
>>>print(a[-1])
>>>o

2. SLICING :
• Accessing some part of a string or sub-string is known as
slicing. This can be done by specifying an index range.
• A segment of a string is called a slice. selecting a slice is
similar to selecting a character.
• The operator of slice indicates two types. They are :
1. Square brackets( “[ ]” )
2. Separated by colon( “ : “ )
• The operator colon are denoted [m:n]
• Including first but excluding the last.
Start------> m ; finish---------> n
Syntax :
String name[start : finish-1]
Example :
>>>a=”hello”
>>>print([0:4])-------------> hell

ILLUSTRATIVE PROGRAMS:
Square root using newtons method:
def newtonsqrt(n):
root=n/2
for i in range(10):
root=(root+n/root)/2
print(root)
n=eval(input("enter number to find Sqrt: "))
newtonsqrt(n)

Output:
enter number to find Sqrt: 9
3.0

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):
gcd=i
print(gcd)

output
Enter a number1:8
Enter a number2:24
8

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)
print("Result:",result)

Output:
Enter base: 2
Enter exponential value:3
Result: 8

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

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
else:
print("not found")

output
[20, 30, 40, 50, 60, 70, 89]
enter a element to search:30
element found at 2

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
elif(search<a[mid]):
stop=mid-1
else:
start=mid+1
else:
print("not found")

output
[20, 30, 40, 50, 60, 70, 89]
enter a element to search:30
element found at 2
UNIT-4

LISTS

A list is a sequence of values. In a string, the values are characters; in a list,


they can be any type. The values in a list are called elements or
sometimes items.
There are several ways to create a new list; the simplest is to enclose the
elements in square brackets ([ and]):

[10, 20, 30, 40]

Lists are mutable

The syntax for accessing the elements of a list is the same as for accessing the
characters of a string—the bracket operator. The expression inside the brackets
specifies the index.
Remember that the indices start at 0:

Traversing a list

The most common way to traverse the elements of a list is with a for loop. The
syntax is the same as for strings:

for cheese in cheeses:


print cheese

List operations
The + operator concatenates lists:
>>> a = [1, 2, 3]
>>> b = [4, 5, 6]
>>> c = a + b
>>> print c
[1, 2, 3, 4, 5, 6]

Similarly, the * operator repeats a list a given number of times:


>>> [0] * 4
[0, 0, 0, 0]
>>> [1, 2, 3] * 3
[1, 2, 3, 1, 2, 3, 1, 2, 3]

The first example repeats [0] four times. The second example repeats the list
[1, 2, 3] three times.

List slices

The slice operator also works on lists:


>>> t = ['a', 'b', 'c', 'd', 'e', 'f']
>>> t[1:3]
['b', 'c']
>>> t[:4]
['a', 'b', 'c', 'd']
t[3:] ['d', 'e', 'f']
If you omit the first index, the slice starts at the beginning. If you omit the
second, the slice goes to the end. So if you omit both, the slice is a copy of the
whole list.
>>> t[:]
['a', 'b', 'c', 'd', 'e', 'f']

Since lists are mutable, it is often useful to make a copy before performing
operations that fold, spindle or mutilate lists.
A slice operator on the left side of an assignment can update multiple elements:
>>> t = ['a', 'b', 'c', 'd', 'e', 'f']
>>> t[1:3] = ['x', 'y']
>>> print t
['a', 'x', 'y', 'd', 'e', 'f']

List methods

Python provides methods that operate on lists. For example, append adds a new
element to the end of a list:
>>> t = ['a', 'b', 'c']
>>> t.append('d')
>>> print t
['a', 'b', 'c', 'd']
extend takes a list as an argument and appends all of the elements:
>>> t1 = ['a', 'b', 'c']
>>> t2 = ['d', 'e']
>>> t1.extend(t2)
>>> print t1
['a', 'b', 'c', 'd', 'e']

This example leaves t2 unmodified.


sort arranges the elements of the list from low to high:
>>> t = ['d', 'c', 'e', 'b', 'a']
>>> t.sort()
>>> print t
['a', 'b', 'c', 'd', 'e']

List methods are all void; they modify the list and return None
List Loop

In Python lists are considered a type of iterable . An iterable is a data type that
can return its elements separately, i.e., one at a time.

for <item> in <iterable>:


<body>

Eg:
>>>names = ["Uma","Utta","Ursula","Eunice","Unix"]
>>>for name in names:
...print("Hi "+ name +"!")

Deleting elements

There are several ways to delete elements from a list. If you know the index of
the elementyou want, you can use pop:
>>> t = ['a', 'b', 'c']
>>> x = t.pop(1)
>>> print t
['a', 'c']
>>> print x
b
pop modifies the list and returns the element that was removed. If you don’t
provide an index, it deletes and returns the last element.
If you don’t need the removed value, you can use the del operator:
>>> t = ['a', 'b', 'c']
>>> del t[1]
>>> print t
['a', 'c']
If you know the element you want to remove (but not the index), you can use
remove:
>>> t = ['a', 'b', 'c']
>>> t.remove('b')
>>> print t
['a', 'c']

The return value from remove is None.


To remove more than one element, you can use del with a slice index:
>>> t = ['a', 'b', 'c', 'd', 'e', 'f']
>>> del t[1:5]
>>> print t
['a', 'f']

As usual, the slice selects all the elements up to, but not including, the second
index.

Lists and strings

A string is a sequence of characters and a list is a sequence of values, but a list


of characters is not the same as a string. To convert from a string to a list of
characters, you can use list:
>>>s = 'spam'
>>>t = list(s)
>>> print t
['s', 'p', 'a', 'm']

Because list is the name of a built-in function, you should avoid using it as a
variable name. I also avoid l because it looks too much like 1. So that’s why I
use t.
The list function breaks a string into individual letters. If you want to break a
string into words, you can use the split method:
>>> s = 'pining for the fjords'
>>> t = s.split()
>>> print t
['pining', 'for', 'the', 'fjords']
An optional argument called a delimiter specifies which characters to use as
word boundaries.
The following example uses a hyphen as a delimiter:
>>> s = 'spam-spam-spam'
>>> delimiter = '-'
>>> s.split(delimiter) ['spam', 'spam', 'spam']
join is the inverse of split. It takes a list of strings and concatenates the
elements. join is a string method, so you have to invoke it on the delimiter and
pass the list as a parameter:
>>> t = ['pining', 'for', 'the', 'fjords']
>>> delimiter = ' '
>>> delimiter.join(t)
'pining for the fjords'

In this case the delimiter is a space character, so join puts a space between
words. To concatenate strings without spaces, you can use the empty string, '',
as a delimiter.

Aliasing

If a refers to an object and you assign b = a, then both variables refer to the
same object:
>>> a = [1, 2, 3]
>>> b = a
>>> b is a
True

The association of a variable with an object is called a reference. In this


example, there are two references to the same object.
An object with more than one reference has more than one name, so we say that
the object is aliased.

If the aliased object is mutable, changes made with one alias affect the other:

>>> b[0] = 17
>>> print a
[17, 2, 3]

Cloning Lists
Cloning means making an exact but separate copy
create a new list and copy every element

Eg:
original_list = [10, 22, 44, 23, 4]
new_list = list(original_list)
print(original_list)
print(new_list)

Output: [10, 22, 44, 23, 4]


[10, 22, 44, 23, 4]

List arguments

When you pass a list to a function, the function gets a reference to the list. If the
function modifies a list parameter, the caller sees the change. For example,
delete_head removes the first element from a list:
def delete_head(t):
del t[0]
Here’s how it is used:
>>> letters = ['a', 'b', 'c']
>>> delete_head(letters)
>>> print letters
['b', 'c']

The parameter t and the variable letters are aliases for the same object.

TUPLES
Tuples are immutable

A tuple is a sequence of values. The values can be any type, and they are
indexed by integers, so in that respect tuples are a lot like lists. The important
difference is that tuples are immutable. Syntactically, a tuple is a comma-
separated list of values:
>>> t = 'a', 'b', 'c', 'd', 'e'

Most list operators also work on tuples. The bracket operator indexes an
element:
>>> t = ('a', 'b', 'c', 'd', 'e')
>>> print t[0]
'a'

And the slice operator selects a range of elements.


>>> print t[1:3]
('b', 'c')

But if you try to modify one of the elements of the tuple, you get an error:
>>> t[0] = 'A'
Tuple assignment

It is often useful to swap the values of two variables. With conventional


assignments, you have to use a temporary variable. For example, to swap a and
b:
>>> temp = a
>>> a = b
>>> b = temp

This solution is cumbersome; tuple assignment is more elegant:


>>> a, b = b, a

Tuples as return values

A function can only return one value, but if the value is a tuple, the effect is the
same as returning multiple values. For example, if you want to divide two
integers and compute the quotient and remainder, it is inefficient to compute x/y
and then x%y. It is better to compute them both at the same time.

The built-in function divmod takes two arguments and returns a tuple of two
values, the quotient and remainder. You can store the result as a tuple:
>>> t = divmod(7, 3)
>>> print t
(2, 1)
Or use tuple assignment to store the elements separately:
>>> quot, rem = divmod(7, 3)
>>> print quot
2
>>> print rem
1

Here is an example of a function that returns a tuple:


def min_max(t):
return min(t), max(t)

max and min are built-in functions that find the largest and smallest elements of
a sequence. min_max computes both and returns a tuple of two values.

Dictionaries and tuples

Dictionaries have a method called items that returns a list of tuples, where each
tuple is a key-value pair.
>>> d = {'a':0, 'b':1, 'c':2}
>>> t = d.items()
>>> print t
[('a', 0), ('c', 2), ('b', 1)]

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)
Operations on dictionary:
1. Accessing an element
2. Update
3. Add element
4. Membership
Methods in dictionary:
Difference between List, Tuples and dictionary:
Advanced list processing:

List Comprehension:

List comprehensions provide a concise way to apply operations on a list.

It creates a new list in which each element is the result of applying a
given operation in a list.

It consists of brackets containing an expression followed by a “for”
clause, then a list.

The list comprehension always returns a result list.

Syntax
list=[ expression for item in list if conditional ]
Nested list:
List inside another list is called nested list.

Example:
>>> a=[56,34,5,[34,57]]
>>> a[0]

56
>>> a[3]
[34, 57]
>>> a[3][0]
34
>>> a[3][1]
57
Illustrative programs:

Selection sort
a=input("Enter list:").split()
a=list(map(eval,a))
for i in range(0,len(a)):
smallest = min(a[i:])
sindex= a.index(smallest)
a[i],a[sindex] = a[sindex],a[i]
print (a)

Output
Enter list:23 78 45 8 32 56
[8,2 3, 32, 45,56, 78]
Insertion sort
a=input("enter a list:").split()
a=list(map(int,a))
for i in a:
j = a.index(i)
while j>0:
if a[j-1] > a[j]:
a[j-1],a[j] = a[j],a[j-1]
else:
break
j = j-1
print (a)
output
enter a list: 8 5 7 1 9 3
[1,3,5,7,8,9]

Merge sort
def merge(a,b):
c = []
while len(a) != 0 and len(b) != 0:
if a[0] < b[0]:
c.append(a[0])
a.remove(a[0])
else:
c.append(b[0])
b.remove(b[0])
if len(a) == 0:
c=c+b
else:
c=c+a
return c
def divide(x):
if len(x) == 0 or len(x) == 1:
return x
else:
middle = len(x)//2
a = divide(x[:middle])
b = divide(x[middle:])
return merge(a,b)
x=[38,27,43,3,9,82,10]
c=divide(x)
print(c)

output
[3,9,10,27,38,43,82]
LISTS, TUPLES AND DICTIONARIES

1. What is a list?
A list is an ordered set of values, where each value is identified by an index.
The values that make up a list are called its elements. Lists are similar to strings,
which are ordered sets of characters, except that the elements of a list can have
any type.

2. Solve a)[0] * 4 and b) [1, 2, 3] * 3.


>>> [0] * 4 [0, 0, 0, 0]
>>> [1, 2, 3] * 3 [1, 2, 3, 1, 2, 3, 1, 2, 3]

3. Let list = [’a’, ’b’, ’c’, ’d’, ’e’, ’f’]. Find a) list[1:3] b) t[:4] c) t[3:] .
>>> list = [’a’, ’b’, ’c’, ’d’, ’e’, ’f’]
>>> list[1:3] [’b’, ’c’]
>>> list[:4] [’a’, ’b’, ’c’, ’d’]
>>> list[3:] [’d’, ’e’, ’f’]

4. Mention any 5 list methods.


append() ,extend () ,sort(), pop(),index(),insert and remove()

5. State the difference between lists and dictionary.


List is a mutable type meaning that it can be modified whereas dictionary is
immutable and is a key value store. Dictionary is not ordered and it requires that
the keys are hashable whereas list can store a sequence of objects in a certain
order.

6. What is List mutability in Python? Give an example.


Python represents all its data as objects. Some of these objects like lists and
dictionaries are mutable, i.e., their content can be changed without changing
their identity. Other objects like integers, floats, strings and tuples are objects
that cannot be changed. Example:
>>> numbers = [17, 123]
>>> numbers[1] = 5
>>> print numbers [17, 5]

7. What is aliasing in list? Give an example.


An object with more than one reference has more than one name, then the
object is said to be aliased. Example: If a refers to an object and we assign b =
a, then both variables refer to the same object:
>>> a = [1, 2, 3]
>>> b = a
>>> b is a True

8. Define cloning in list.


In order to modify a list and also keep a copy of the original, it is required to
make a copy of the list itself, not just the reference. This process is called
cloning, to avoid the ambiguity of the word “copy”.
9. Explain List parameters with an example.
Passing a list as an argument actually passes a reference to the list, not a copy of
the list. For example, the function head takes a list as an argument and returns
the first element:
def head(list):
return list[0]
output:
>>> numbers = [1, 2, 3]
>>> head(numbers)

10. Write a program in Python to delete first element from a list.


def deleteHead(list): del list[0]
Here’s how deleteHead is used:
>>> numbers = [1, 2, 3]
>>> deleteHead(numbers)
>>> print numbers [2, 3]

11. Write a program in Python returns a list that contains all but the first
element of the given list.
def tail(list): return list[1:]
Here’s how tail is used:
>>> numbers = [1, 2, 3]
>>> rest = tail(numbers)
print rest [2, 3]

12. What is the benefit of using tuple assignment in Python?


It is often useful to swap the values of two variables. With conventional
assignments a temporary variable would be used. For example, to swap a and b:
>>> temp = a
>>> a = b
>>> b = temp
This solution is cumbersome; tuple assignment is more elegant:
>>> a, b = b, a

13. Define key-value pairs.


The elements of a dictionary appear in a comma-separated list. Each entry
contains an index and a value separated by a colon. In a dictionary, the indices
are called keys, so the elements are called key-value pairs.

14. Define dictionary with an example.


A dictionary is an associative array (also known as hashes). Any key of the
dictionary is associated (or mapped) to a value. The values of a dictionary can
be any Python data type. So dictionaries are unordered key-value-pairs.
Example:
>>> eng2sp = {} # empty dictionary
>>> eng2sp[’one’] = ’uno’
>>> eng2sp[’two’] = ’dos’

15. How to return tuples as values?


A function can only return one value, but if the value is a tuple, the effect is the
same as returning multiple values. For example, if we want to divide two
integers and compute the quotient and remainder, it is inefficient to compute x/y
and then x%y. It is better to compute them both at the same time.
>>> t = divmod(7, 3)
>>> print t (2, 1)

16. List two dictionary operations.


• Del -removes key-value pairs from a dictionary
• Len - returns the number of key-value pairs

17. Define dictionary methods with an example.
A method is similar to a function—it takes arguments and returns a value— but
the syntax is different. For example, the keys method takes a dictionary and
returns a list of the keys that appear, but instead of the function syntax
keys(eng2sp), method syntax eng2sp.keys() is used.
>>> eng2sp.keys() [’one’, ’three’, ’two’]
18. Define List Comprehension.
List comprehensions apply an arbitrary expression to items in an iterable
rather than applying function. It provides a compact way of mapping a list into
another list by applying a function to each of the elements of the list.

19.Write a Python program to swap two variables.


x=5
y = 10
temp = x
x=y
y = temp
print('The value of x after swapping: {}'.format(x))
print('The value of y after swapping: {}'.format(y))

20.Write the syntax for list comprehension.


The list comprehension starts with a '[' and ']', to help us remember that the
result is going to be a list. The basic syntax is [expression for item in list if
conditional ].
1. Explain in detail about lists, list operations and list slices.
A list is an ordered set of values, where each value is identified by an index.
The values that make up a list are called its elements. Lists are similar to strings,
which are ordered sets of characters, except that the elements of a list can have
any type. There are several ways to create a new list. The simplest is to enclose
the elements in square brackets ([and]):
[10, 20, 30, 40]
["spam", "bungee", "swallow"]
The following list contains a string, a float, an integer, and (mirabile dictu)
another list:
["hello", 2.0, 5, [10, 20]]
A list within another list is said to be nested. Lists that contain consecutive
integers are common, so Python provides a simple way to create them:
>>> range (1,5) [1, 2, 3, 4].

LIST OPERATIONS
The + operator concatenates lists
: >>> a = [1, 2, 3]
>>> b = [4, 5, 6]
>>> c = a + b
>>> print c [1, 2, 3, 4, 5, 6]
Similarly, the * operator repeats a list a given number of times:
>>> [0] * 4 [0, 0, 0, 0]
>>> [1, 2, 3] * 3 [1, 2, 3, 1, 2, 3, 1, 2, 3]

LIST SLICES
The slice operator also works on lists:
>>> t = ['a', 'b', 'c',’d’, 'e', 'f']
>>> t[1:3] ['b', 'c']
>>> t[:4] ['a', 'b', 'c', 'd']
>>> t[3:] ['d', 'e', 'f']
If we omit the first index, the slice starts at the beginning. If we omit the
second, the slice goes to the end.
So if we omit both, the slice is a copy of the whole list.
>>> t[:] ['a', 'b', 'c', 'd', 'e', 'f']
Since lists are mutable, it is often useful to make a copy before performing
operations that fold, spindle or mutilate lists. A slice operator on the left side of
an assignment can update multiple elements:
>>> t = ['a', 'b', 'c',’d’, 'e', 'f']
>>> t[1:3] = ['x', 'y']
>>> print t ['a', 'x', 'y', 'd', 'e', 'f,]

Like strings, lists can be indexed and sliced:

>>> list = [2, 4, "usurp", 9.0, "n"]


>>> list[2]
'usurp'
>>> list[3:]
[9.0, 'n']
Much like the slice of a string is a substring, the slice of a list is a list. However,
lists differ from strings in that we can assign new values to the items in a list:

>>> list[1] = 17
>>> list
[2, 17, 'usurp', 9.0, 'n']

We can assign new values to slices of the lists, which don't even have to be the
same length:

>>> list[1:4] = ["opportunistic", "elk"]


>>> list
[2, 'opportunistic', 'elk', 'n']

It's even possible to append items onto the start of lists by assigning to an empty
slice:

>>> list[:0] = [3.14, 2.71]


>>> list
[3.14, 2.71, 2, 'opportunistic', 'elk', 'n']

Similarly, you can append to the end of the list by specifying an empty slice
after the end:

>>> list[len(list):] = ['four', 'score']


list
[3.14, 2.71, 2, 'opportunistic', 'elk', 'n', 'four', 'score']

You can also completely change the contents of a list:

>>> list[:] = ['new', 'list', 'contents']


>>> list
['new', 'list', 'contents']

The right-hand side of a list assignment statement can be any iterable type:

>>> list[:2] = ('element',('t',),[])


>>> list
['element', ('t',), [], 'contents']

With slicing you can create copy of list since slice returns a new list:

>>> original = [1, 'element', []]


>>> list_copy = original[:]
>>> list_copy
[1, 'element', []]
>>> list_copy.append('new element')
>>> list_copy
[1, 'element', [], 'new element']
>>> original
[1, 'element', []]

Note, however, that this is a shallow copy and contains references to elements
from the original list, so be careful with mutable types:

>>> list_copy[2].append('something')
>>> original
[1, 'element', ['something']]

Non-Continuous slices
It is also possible to get non-continuous parts of an array. If one wanted to get
every n-th occurrence of a list, one would use the :: operator. The syntax is a:b:n
where a and b are the start and end of the slice to be operated upon.
>>> list = [i for i in range(10) ]
>>> list
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> list[::2] [0, 2, 4, 6, 8]
list[1:7:2] [1, 3, 5]

2. Explain in detail about list methods and list loops with examples.
Python provides methods that operate on lists. Some of the methods are

• Append()
• Extend()
• Sort()
• Pop()
For example, append adds a new element to the end of a list:
>>> t = ['a', 'b', 'c']
>>> t.append('d')
>>> print t ['a', 'b', 'c', 'd']
Extend takes a list as an argument and appends all of the elements:
>>> t1 = ['a', 'b', 'c']
>>> t2 = ['d', 'e']
>>> t1.extend(t2)
>>> print t1 ['a', 'b', 'c', 'd', 'e']
This example leaves t2 unmodified. sort arranges the elements of the list from
low to high:
>>> t = ['d', 'c', 'e', 'b', 'a']
>>> t.sort()
>>> print t ['a', 'b', 'c', 'd', 'e']
Remove the item in the list at the index i and return it. If i is not given, remove
the the last item in the list and return it.
>>>list = [1, 2, 3, 4]
>>>a = list.pop(0)
>>> list [2, 3, 4]
>>> a
List methods are all void; they modify the list and return None.

LIST LOOPS
Here are two functions that both generate ten million random numbers, and
return the sum of the numbers.
They both work.
import random
joe = random.Random()
def sum1():
""" Build a list of random numbers, then sum them """ # Generate one random
˓→number
xs = []
for i in range(10000000):
num = joe.randrange(1000 )
xs.append(num)
# Save it in our list
tot = sum(xs)
return tot
def sum2():
""" Sum the random numbers as we generate them """
tot = 0
for i in range(10000000):
num = joe.randrange(1000)
tot += num
return tot
print(sum1())
print(sum2())

3. Explain in detail about mutability and tuples with a Python program.

MUTABILITY
Unlike strings, lists are mutable, which means we can change their elements.
Using the bracket operator on the left side of an assignment, we can update one
of the elements:
>>> fruit = ["banana", "apple", "quince"]
>>> fruit[0] = "pear"
>>> fruit[-1] = "orange"
>>> print fruit [’pear’, ’apple’, ’orange’]
With the slice operator we can update several elements at once:
>>> list = [’a’, ’b’, ’c’, ’d’, ’e’, ’f’]
>>> list[1:3] = [’x’, ’y’]
>>> print list [’a’, ’x’, ’y’, ’d’, ’e’, ’f’] \
We can also remove elements from a list by assigning the empty list to them:
>>> list = [’a’, ’b’, ’c’, ’d’, ’e’, ’f’]
>>> list[1:3] = []
>>> print list [’a’, ’d’, ’e’, ’f’]
And we can add elements to a list by squeezing them into an empty slice at the
desired location:
>>> list = [’a’, ’d’, ’f’]
>>> list[1:1] = [’b’, ’c’]
>>> print list [’a’, ’b’, ’c’, ’d’, ’f’]
>>> list[4:4] = [’e’]
>>> print list [’a’, ’b’, ’c’, ’d’, ’e’, ’f’]

4. What is tuple assignment? Explain it with an example.


It is often useful to swap the values of two variables. With conventional
assignments, you have to use a temporary variable. For example, to swap a and
b:
>>> temp = a
>>> a = b
>>> b = temp
This solution is cumbersome; tuple assignment is more elegant:
>>> a, b = b, a
The left side is a tuple of variables; the right side is a tuple of expressions. Each
value is assigned to its respective variable. All the expressions on the right side
are evaluated before any of the assignments. The number of variables on the left
and the number of values on the right have to be the same:
>>> a, b = 1, 2, 3
ValueError: too many values to unpack More generally, the right side can be
any kind of sequence (string, list or tuple). For example, to split an email
address into a user name and a domain, you could write:
>>> addr = 'monty@python.org'
>>> uname, domain = addr.split('@')
The return value from split is a list with two elements; the first element is
assigned to uname, the second to domain.
>>> print uname monty
>>> print domain python.org

5. Is it possible to return tuple as values? Justify your answer with an


example.
Yes, it is possible to return tuple as values. Example: Functions can return
tuples as return values. For example, we could write a function that swaps two
parameters:
def swap(x, y):
return y, x
Then we can assign the return value to a tuple with two variables:
a, b = swap(a, b)
In this case, there is no great advantage in making swap a function. In fact, there
is a danger in trying to encapsulate swap, which is the following tempting
mistake:
def swap(x, y): # incorrect version
x, y = y, x
If we call this function like this: swap(a, b) then a and x are aliases for the same
value. Changing x inside swap makes x refer to a different value, but it has no
effect on a in main. Similarly, changing y has no effect on b. This function runs
without producing an error message, but it doesn’t do what we intended. This is
an example of a semantic error.
The built-in function divmod takes two arguments and returns a tuple of two
values, the quotient and remainder. You can store the result as a tuple:
>>> t = divmod(7, 3)
>>> print t (2, 1)
Or use tuple assignment to store the elements separately:
>>> quot, rem = divmod(7, 3)
>>> print quot 2
>>> print rem 1
Here is an example of a function that returns a tuple: def min_max(t): return
min(t), max(t) max and min are built-in functions that find the largest and
smallest elements of a sequence. min_max computes both and returns a tuple of
two values.

6. Explain in detail about dictionaries and its operations.

DICTIONARIES
A dictionary is like a list, but more general. In a list, the indices have to be
integers; in a dictionary they can be (almost) any type. You can think of a
dictionary as a mapping between a set of indices (which are called keys) and a
set of values. Each key maps to a value. The association of a key and a value is
called a key-value pair or sometimes an item. As an example, we’ll build a
dictionary that maps from English to Spanish words, so the keys and the values
are all strings.
The function dict creates a new dictionary with no items. Because dict is the
name of a built-in function, you should avoid using it as a variable name.
>>> eng2sp = dict()
>>> print eng2sp {}
The squiggly-brackets, {}, represent an empty dictionary. To add items to the
dictionary, you can use square brackets: >>> eng2sp['one'] = 'uno' This line
creates an item that maps from the key 'one' to the value 'uno'. If we print the
dictionary again, we see a key-value pair with a colon between the key and
value:
>>> print eng2sp {'one': 'uno'}
This output format is also an input format. For example, you can create a new
dictionary with three items:
>>> eng2sp = {'one': 'uno', 'two': 'dos', 'three': 'tres'}
But if you print eng2sp, you might be surprised:
>>> print eng2sp {'one': 'uno', 'three': 'tres', 'two': 'dos'}
The order of the key-value pairs is not the same. In fact, if you type the same
example on your computer, you might get a different result. In general, the
order of items in a dictionary is unpredictable. But that’s not a problem because
the elements of a dictionary are never indexed with integer indices. Instead, you
use the keys to look up the corresponding values:
>>> print eng2sp['two'] 'dos'
The key 'two' always maps to the value 'dos' so the order of the items doesn’t
matter. If the key isn’t in the dictionary, you get an exception:
>>> print eng2sp['four'] KeyError: 'four'
The len function works on dictionaries; it returns the number of key-value pairs:
>>> len(eng2sp)
3
The in operator works on dictionaries; it tells you whether something appears as
a key in the dictionary (appearing as a value is not good enough).
>>> 'one' in eng2sp True
>>> 'uno' in eng2sp False
To see whether something appears as a value in a dictionary, you can use the
method values, which returns the values as a list, and then use the in operator:
>>> vals = eng2sp.values()
>>> 'uno' in vals
True
The in operator uses different algorithms for lists and dictionaries. For lists, it
uses a search algorithm, as in Section 8.6. As the list gets longer, the search
time gets longer in direct proportion. For dictionaries, Python uses an algorithm
called a hashtable that has a remarkable property: the in operator takes about the
same amount of time no matter how many items there are in a dictionary

Dictionary operations
The del statement removes a key-value pair from a dictionary. For example, the
following dictionary contains the names of various fruits and the number of
each fruit in stock:
>>> inventory = {’apples’: 430, ’bananas’: 312, ’oranges’: 525, ’pears’: 217}
>>> print inventory {’oranges’: 525, ’apples’: 430, ’pears’: 217, ’bananas’:
312}
If someone buys all of the pears, we can remove the entry from the dictionary:
>>> del inventory[’pears’]
>>> print inventory {’oranges’: 525, ’apples’: 430, ’bananas’: 312}
Or if we’re expecting more pears soon, we might just change the value
associated with pears:
>>> inventory[’pears’] = 0
>>> print inventory {’oranges’: 525, ’apples’: 430, ’pears’: 0, ’bananas’: 312}
The len function also works on dictionaries; it returns the number of key-value
pairs:
>>> len(inventory) 4

7. Explain in detail about dictionary methods.

DICTIONARY METHODS
A method is similar to a function—it takes arguments and returns a value— but
the syntax is different. For example, the keys method takes a dictionary and
returns a list of the keys that appear, but instead of the function syntax
keys(eng2sp), we use the method syntax eng2sp.keys().
>>> eng2sp.keys() [’one’, ’three’, ’two’]
This form of dot notation specifies the name of the function, keys, and the name
of the object to apply the function to, eng2sp. The parentheses indicate that this
method has no parameters. A method call is called an invocation; in this case,
we would say that we are invoking keys on the object eng2sp.
The values method is similar; it returns a list of the values in the dictionary:
>>> eng2sp.values() [’uno’, ’tres’, ’dos’]
The items method returns both, in the form of a list of tuples—one for each key-
value pair:
>>> eng2sp.items() [(’one’,’uno’), (’three’, ’tres’), (’two’, ’dos’)]
The syntax provides useful type information. The square brackets indicate that
this is a list. The parentheses indicate that the elements of the list are tuples. If a
method takes an argument, it uses the same syntax as a function call. For
example, the method has key takes a key and returns true (1) if the key appears
in the dictionary:
>>> eng2sp.has_key(’one’)
True
>>> eng2sp.has_key(’deux’)
False
If you try to call a method without specifying an object, you get an error. In this
case, the error message is not very helpful:
>>> has_key(’one’) NameError: has_key 108

8. Explain in detail about list comprehension .Give an example.

List comprehensions
List comprehensions provide a concise way to create lists. It consists of brackets
containing an expression followed by a for clause, then zero or more for or if
clauses. The expressions can be anything, i.e., all kinds of objects can be in
lists. The result will be a new list resulting from evaluating the expression in the
context of the for and if clauses which follow it. The list comprehension always
returns a result list.
Syntax
The list comprehension starts with a '[' and ']', to help you remember that the
result is going to be a list.
The basic syntax is
[ expression for item in list if conditional ]
This is equivalent to:
for item in list:
if conditional:
expression
List comprehension is a method to describe the process using which the list
should be created. To do that, the list is broken into two pieces. The first is a
picture of what each element will look like, and the second is what is done to
get it.
For instance, let's say we have a list of words:
listOfWords = ["this","is","a","list","of","words"]
To take the first letter of each word and make a list out of it using list
comprehension:
>>> listOfWords = ["this","is","a","list","of","words"]
>>> items = [ word[0] for word in listOfWords ]
>>> print items
['t', 'i', 'a', 'l', 'o', 'w']
List comprehension supports more than one for statement. It will evaluate the
items in all of the objects sequentially and will loop over the shorter objects if
one object is longer than the rest.
>>> item = [x+y for x in 'cat' for y in 'pot']
>>> print item
['cp', 'co', 'ct', 'ap', 'ao', 'at', 'tp', 'to', 'tt']
List comprehension supports an if statement, to only include members into the
list that fulfill a certain condition:
>>> print [x+y for x in 'cat' for y in 'pot']
['cp', 'co', 'ct', 'ap', 'ao', 'at', 'tp', 'to', 'tt']
>>>print [x+y for x in 'cat' for y in 'pot' if x != 't' and y != 'o' ] ['
cp', 'ct', 'ap', 'at']
print [x+y for x in 'cat' for y in 'pot' if x != 't' or y != 'o' ] ['cp', '
co', 'ct', 'ap', 'ao', 'at', 'tp', 'tt']

9. Write a Python program for a) selection sort b) insertion sort.


SELECTION SORT: PROGRAM:
def selectionsort( aList ):
for i in range( len( aList ) ): least = i
for k in range( i + 1 , len( aList ) ):
if aList[k] < aList[least]:
least = k
swap( aList, least, i )
def swap( A, x, y ):
tmp = A[x]
A[x] = A[y]
A[y] = tmp
aList = [54,26,93,17,77,31,44,55,20]
selectionsort(aList)
print(aList)
Insertion sort:
def insertionSort(alist):
for index in range(1,len(alist)):
currentvalue = alist[index]
position = index
while position>0 and alist[position-1]>currentvalue:
alist[position]=alist[position-1]
position = position-1
alist[position]=currentvalue
alist = [54,26,93,17,77,31,44,55,20]
insertionSort(alist)
print(alist)

10. Write a Python program for a) merge sort b) quick sort.

Merge sort:
def mergeSort(alist):
print("Splitting ",alist)
if len(alist)>1:
mid = len(alist)//2
lefthalf = alist[:mid]
righthalf = alist[mid:]
mergeSort(lefthalf)
mergeSort(righthalf)
i=0
j=0
k=0
while i < len(lefthalf) and j < len(righthalf):
if lefthalf[i] < righthalf[j]:
alist[k]=lefthalf[i]
i=i+1
else:
alist[k]=righthalf[j]
j=j+1
k=k+1
while i < len(lefthalf):
alist[k]=lefthalf[i]
i=i+1
k=k+1
while j < len(righthalf):
alist[k]=righthalf[j]
j=j+1
k=k+1
print("Merging ",alist)
alist = [54,26,93,17,77,31,44,55,20]
mergeSort(alist)
print(alist)
Quicksort:
from random import randrange
def partition(lst, start, end, pivot):
lst[pivot], lst[end] = lst[end], lst[pivot]
store_index = start
for i in xrange(start, end):
if lst[i] < lst[end]:
lst[i], lst[store_index] = lst[store_index], lst[i]
store_index += 1
lst[store_index], lst[end] = lst[end], lst[store_index]
return store_index
def quick_sort(lst, start, end):
if start >= end:
return lst
pivot = randrange(start, end + 1)
new_pivot = partition(lst, start, end, pivot)
quick_sort(lst, start, new_pivot - 1)
quick_sort(lst, new_pivot + 1, end)
def sort(lst):
quick_sort(lst, 0, len(lst) - 1)
return lst
print sort([-5, 3, -2, 3, 19, 5])
print sort([345,45,89,569,23,67,56,90,100])
Unit -5

FILES

File is a named location on disk to store related information. It is used to


permanently store data in a non-volatile memory (e.g. hard disk).
Since, random access memory (RAM) is volatile which loses its data when
computer is turned off, we use files for future use of the data.
When we want to read from or write to a file we need to open it first. When
we are done, it needs to be closed, so that resources that are tied with the file
are freed. Hence, in Python, a file operation takes place in the following order.

1. Open a file
2. Read or write (perform operation)
3. Close the file

Opening a file

Python has a built-in function open() to open a file. This function returns a file
object, also called a handle, as it is used to read or modify the file accordingly.
>>> f = open("test.txt") # open file in current directory
>>> f = open("C:/Python33/README.txt") # specifying full path

We can specify the mode while opening a file. In mode, we specify whether we
want to read 'r', write 'w' or append 'a' to the file. We also specify if we want
to open the file in text mode or binary mode.
The default is reading in text mode. In this mode, we get strings when reading
from the file. On the other hand, binary mode returns bytes and this is the
mode to be used when dealing with non-text files like image or exe files.
Python File Modes
Mode : Description
'r' : Open a file for reading. (default)
'w' : Open a file for writing. Creates a new file if it does not exist or truncates
the file if it exists.
'x' : Open a file for exclusive creation. If the file already exists, the operation
fails.
'a' : Open for appending at the end of the file without truncating it. Creates a
new file if it does not exist.
't' : Open in text mode. (default)
'b' : Open in binary mode.
'+' : Open a file for updating (reading and w

f = open("test.txt") # equivalent to 'r' or 'rt'


f = open("test.txt",'w') # write in text mode
f = open("img.bmp",'r+b') # read and write in binary mode

Hence, when working with files in text mode, it is highly recommended to


specify the encoding type.
f = open("test.txt",mode = 'r',encoding = 'utf-8')

Closing a File

When we are done with operations to the file, we need to properly close it.
Closing a file will free up the resources that were tied with the file and is done
using the close() method.
Python has a garbage collector to clean up unreferenced objects but, we must
not rely on it to close the file.
f = open("test.txt",encoding = 'utf-8')
# perform file operations
f.close()
This method is not entirely safe. If an exception occurs when we are
performing some operation with the file, the code exits without closing the
file. A safer way is to use a try...finally block.
try:
f= open("test.txt",encoding = 'utf-8')
# perform file operations
finally:
f.close()

Reading and writing

A text file is a sequence of characters stored on a permanent medium like a


hard drive, flash memory, or CD-ROM.
To write a file, you have to open it with mode 'w' as a second parameter:
>>> fout = open('output.txt', 'w')
>>> print fout
<open file 'output.txt', mode 'w' at 0xb7eb2410>

If the file already exists, opening it in write mode clears out the old data and
starts fresh, so be careful! If the file doesn’t exist, a new one is created.
The write method puts data into the file.
>>> line1 = "This here's the wattle,\n"
>>>fout.write(line1)
Again, the file object keeps track of where it is, so if you call write again, it adds
the new data to the end.
>>> line2 = "the emblem of our land.\n"
>>> fout.write(line2)

When you are done writing, you have to close the file.
>>> fout.close()
Format operator

The argument of write has to be a string, so if we want to put other values in a


file, we have to convert them to strings. The easiest way to do that is with str:
>>> x = 52
>>> fout.write(str(x))

An alternative is to use the format operator, %. When applied to integers, % is


the modulus operator. But when the first operand is a string, % is the format
operator.

The first operand is the format string, which contains one or more format
sequences, which specify how the second operand is formatted. The result is a
string.
For example, the format sequence '%d' means that the second operand should
be formatted as an integer (d stands for “decimal”):
>>> camels = 42
>>> '%d' % camels
'42'

EXCEPTION

Python (interpreter) raises exceptions when it encounters errors. Error caused by


not following the proper structure (syntax) of the language is called syntax error
or parsing error.
>>> if a < 3
File "<interactive input>", line 1
if a < 3
SyntaxError: invalid syntax
Errors can also occur at runtime and these are called exceptions. They occur, for
example, when a file we try to open does not exist (FileNotFoundError),
dividing a number by zero (ZeroDivisionError), module we try to import is not
found (ImportError) etc.
Whenever these type of runtime error occur, Python creates an exception object.
If not handled properly, it prints a traceback to that error along with some
details about why that error occurred.
>>> 1 / 0
Traceback (most recent call last):
File "<string>", line 301, in runcode
File "<interactive input>", line 1, in <module>
ZeroDivisionError: division by zero

>>> open("imaginary.txt")
Traceback (most recent call last):
File "<string>", line 301, in runcode
File "<interactive input>", line 1, in <module>
FileNotFoundError: [Errno 2] No such file or directory: 'imaginary.txt'

Python Exception Handling

Python has many built-in exceptions which forces your program to output an
error when something in it goes wrong.
When these exceptions occur, it causes the current process to stop and passes it
to the calling process until it is handled. If not handled, our program will crash.
For example, if function A calls function B which in turn calls function C and
an exception occurs in function C. If it is not handled in C, the exception passes
to B and then to A.
If never handled, an error message is spit out and our program come to a
sudden, unexpected halt.
Catching Exceptions in Python

In Python, exceptions can be handled using a try statement.


A critical operation which can raise exception is placed inside the try clause and
the code that handles exception is written in except clause.
It is up to us, what operations we perform once we have caught the exception.
Here is a simple example.

MODULES

Any file that contains Python code can be imported as a module. For example,
suppose you have a file named wc.py with the following code:
def linecount(filename):
count = 0
for line in open(filename):
count += 1
return count
print linecount('wc.py')

If you run this program, it reads itself and prints the number of lines in the file,
which is 7.
You can also import it like this:
>>> import wc
7
Now you have a module object wc:
>>> print wc
<module 'wc' from 'wc.py'>
>>> wc.linecount('wc.py')
7
So that’s how you write modules in Python.
The only problem with this example is that when you import the module it
executes the test code at the bottom. Normally when you import a module, it
defines new functions but it doesn’t execute them.
Programs that will be imported as modules often use the following idiom: if
__name__ == '__main__':
print linecount('wc.py')
__name__ is a built-in variable that is set when the program starts. If the
program is running as a script, __name__ has the value __main__; in that case,
the test code is executed. Otherwise, if the module is being imported, the test
code is skipped.
Eg:
# import module import calendar

yy= 2017
mm = 8

# To ask month and year from the user


# yy = int(input("Enter year: "))
# mm = int(input("Enter month: "))

display the calendar


print(calendar.month(yy, mm))
PACKAGE

A package is a collection of modules. A Python package can have sub-


packages and modules.
A directory must contain a file named __init__.py in order for Python to
consider it as a package. This file can be left empty but we generally place the
initialization code for that package in this file.
Here is an example. Suppose we are developing a game, one possible
organization of packages and modules could be as shown in the figure below.

Importing module from a package

We can import modules from packages using the dot (.) operator.
For example, if want to import the start module in the above example, it is
done as follows. import Game.Level.start
Now if this module contains a function named select_difficulty(), we must use
the full name to reference it.
Game.Level.start.select_difficulty(2)

If this construct seems lengthy, we can import the module without the package
prefix as follows.
from Game.Level import start
We can now call the function simply as follows.
start.select_difficulty(2)

ILLUSTRATION PROGRAM

1. Word Count

import sys
file=open("/Python27/note.txt","r+")
wordcount={}
for word in file.read().split():
if word not in wordcount:
wordcount[word] = 1
else:
wordcount[word] += 1
file.close();
print ("%-30s %s " %('Words in the File' , 'Count'))
for key in wordcount.keys():
print ("%-30s %d " %(key , wordcount[key]))

FILES, MODULES AND PACKAGES

1. What is a text file?

A text file is a file that contains printable characters and whitespace, organized
in to lines separated by newline characters.

2. Write a python program that writes “Hello world” into a file.


f =open("ex88.txt",'w')
f.write("hello world")
f.close()

3. Write a python program that counts the number of words in a


file. f=open("test.txt","r")
content =f.readline(20) words =content.split()
print(words)

4. What are the two arguments taken by the open() function?


The open function takes two arguments : name of the file and the mode of
operation.
Example: f = open("test.dat","w")

5. What is a file object?


A file object allows us to use, access and manipulate all the user accessible
files. It maintains the state about the file it has opened.

6. What information is displayed if we print a file object in the given


program? f= open("test.txt","w")
print f
The name of the file, mode and the location of the object will be displayed.

7. What is an exception?
Whenever a runtime error occurs, it creates an exception. The program stops
execution and prints an error message. For example, dividing by zero creates an
exception:
print 55/0
ZeroDivisionError: integer division or modulo

8. What are the error messages that are displayed for the following
exceptions?
a. Accessing a non-existent list item
b. Accessing a key that isn’t in the dictionary
c. Trying to open a non-existent file
a. IndexError: list index out of range
b. KeyError: what
c. IOError: [Errno 2] No such file or directory: 'filename'

9. What are the two parts in an error message?


The error message has two parts: the type of error before the colon, and
speci_cs about the error after the colon.

10. How do you handle the exception inside a program when you try to
open a non-existent file?
filename = raw_input('Enter a file name: ')
try:
f = open (filename, "r")
except IOError:
print 'There is no file named', filename

11. How does try and execute work?

The try statement executes the statements in the first block. If no exception
occurs, then except statement is ignored. If an exception of type IOError occurs,
it executes the statements in the except branch and then continues.

12. What is the function of raise statement? What are its two arguments?
The raise statement is used to raise an exception when the program detects an
error. It takes two arguments: the exception type and specific information about
the error.

13. What is a pickle?


Pickling saves an object to a file for later retrieval. The pickle module helps to
translate almost any type of object to a string suitable for storage in a database
and then translate the strings back in to objects.

14. What are the two methods used in pickling?


The two methods used in pickling are pickle.dump() and pickle.load(). To store
a data structure, dump method is used and to load the data structures that are
dumped , load method is used.
15. What is the use of the format operator?
The format operator % takes a format string and a tuple of expressions and
yields a string that includes the expressions, formatted according to the format
string.

16. What are modules?


A module is simply a file that defines one or more related functions grouped
together. To reuse the functions of a given module, we need to import the
module. Syntax: import <modulename>

17. What is a package?


Packages are namespaces that contain multiple packages and modules
themselves. They are simply directories.
Syntax: from <mypackage> import <modulename>

18. What is the special file that each package in Python must contain? Each
package in Python must contain a special file called __init__.py

19. How do you delete a file in Python?


The remove() method is used to delete the files by supplying the name of the
file to be deleted as argument.
Syntax: os.remove(filename)

20. How do you use command line arguments to give input to the
program?
Python sys module provides access to any command-line arguments via
sys.argv. sys.argv is the list of command-line arguments. len(sys.argv) is the
number of command-line arguments.
COPYING CONTENTS OF ONE FILE TO ANOTHER
print("Enter the Name of Source File: ")
sFile = input()
print("Enter the Name of Target File: ")
tFile = input()

fileHandle = open(sFile, "r")


texts = fileHandle.readlines()
fileHandle.close()

fileHandle = open(tFile, "w")


for s in texts:
fileHandle.write(s)
fileHandle.close()

print("\nFile Copied Successfully!")

VOTER’S AGE VALIDATION

#this program check voting eligibility


def main():
#get the age
try:
age=int(input("Enter your age"))
if age>18:
print("Eligible to vote")
else:
print("Not eligible to vote")
except:
print("age must be a valid number")
main()

COUNTING NO CHARACTERS IN A FILE


#open file in read mode
file = open("C:\data.txt", "r")

#read the content of file


data = file.read()

#get the length of the data


number_of_characters = len(data)

print ('Number of characters in text file :', number_of_characters)

You might also like