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

Pps Final Notes

The document outlines a comprehensive curriculum on Python programming, covering topics such as computational thinking, algorithms, data types, control flow, and data structures. It provides an introduction to Python's features, installation, and applications, along with detailed explanations of algorithms and their building blocks. Additionally, it includes practical examples and algorithms for common tasks, emphasizing the importance of structured problem-solving in programming.

Uploaded by

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

Pps Final Notes

The document outlines a comprehensive curriculum on Python programming, covering topics such as computational thinking, algorithms, data types, control flow, and data structures. It provides an introduction to Python's features, installation, and applications, along with detailed explanations of algorithms and their building blocks. Additionally, it includes practical examples and algorithms for common tasks, emphasizing the importance of structured problem-solving in programming.

Uploaded by

B.PRAVEEN KUMAR
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 181

Table of Contents

UNIT I: COMPUTATIONAL THINKING AND PROBLEM


SOLVING

1.1 PYTHON INTRODUCTION


1.2 ALGORITHMS
1.3 REPRRESENTING PROBLEMS AND SOLVING WITH FLOWCHARTS
1.4 ITERATION
1.5 RECURSION
1.6 ALGORITHM NOTATIONS

UNIT II: DATA TYPES, EXPRESSIONS, STATEMENTS

2.1 PYTHON INTERPRETER


2.2 PYTHON MODES
2.3 VALUES AND DATA TYPES
2.4 PRECEDENCE OF OPERATORS
2.5 ASSIGNMENT OPERATOR
2.6 COMMENTS

UNIT III: CONTROL FLOW, FUCTIONS, STRINGS

3.1 BOOLEAN VALUES AND OPERATOR


3.2 CONDITIONAL STATEMENTS
3.3 ITERATION
3.4 FRUITFUL FUNCTIONS
3.5 STRINGS
3.6 LIST AS ARRAYS

UNIT IV: LISTS, TUPLES, DICTIONARIES

4.1 LISTS
4.2 LIST PARAMETERS
4.3 TUPLES
4.4 TUPLE AS RETURN VALUE
4.5 DICTIONARIES
4.6 ADVANCED LIST PROCESSING
UNIT V: FILES, MODULES, PACKAGES

5.1 FILE AND ITS OPERATION


4.2 FORMAT OPERATOR
4.3 COMMAND LINE ARGUMENTS
4.4 ERRORS AND EXEPTIONS
4.5 MODULES
4.6 PACKAGES
UNIT 1

COMPUTATIONAL THINKING AND PROBLEM SOLVING

1.1 PYTHON INTRODUCTION

Python is a widely used general-purpose, high level programming


language. It was initially designed by Guido van Rossum in 1991 and
developed by Python Software Foundation. It was mainly developed for
emphasis on code readability, and its syntax allows programmers to
express concepts in fewer lines of code.
Python is a programming language that lets you work quickly and integrate
systems more efficiently.
There are two major Python versions- Python 2 and Python 3.
 On 16 October 2000, Python 2.0 was released with many new
features.
 On 3rd December 2008, Python 3.0 was released with more testing
and includes new features.

Evolution of python programming language

The programming language Python was conceived in the late 1980s, and
its implementation was started in December 1989 by Guido van
Rossum at CWI in the Netherlands as a successor to ABC capable
of exception handling and interfacing with the Amoeba operating system.
Van Rossum is Python's principal author, and his continuing central role
in deciding the direction of Python is reflected in the title given to him by
the Python community, Benevolent Dictator for Life (BDFL).Python was
named after the BBC TV show Monty Python's Flying Circus.

Python Version Released Date

Python 1.0 January 1994

Python 1.5 December 31, 1997

Python 1.6 September 5, 2000


Python 2.0 October 16, 2000

Python 2.1 April 17, 2001

Python 2.2 December 21, 2001

Python 2.3 July 29, 2003

Python 2.4 November 30, 2004

Python 2.5 September 19, 2006

Python 2.6 October 1, 2008

Python 2.7 July 3, 2010

Python 3.0 December 3, 2008

Python 3.1 June 27, 2009

Python 3.2 February 20, 2011

Python 3.3 September 29, 2012

Python 3.4 March 16, 2014

Python 3.5 September 13, 2015

Python 3.6 December 23, 2016

Python 3.7 June 27, 2018

Python 3.8 October 14, 2019

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++,
JavaScript, 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.
Powerful: Built-in types and tools, Library utilities, Third party utilities (e.g.
Numeric, NumPy, SciPy)
And Automatic memory management

Applications:
 Bit Torrent file sharing
 Google search engine, YouTube
 Intel, Cisco, HP,IBM
 i–Robot
 NASA
 Face book, Drop box

Why to use Python:

The following are the primary factors to use python in day-to-day life:
o Python is object-oriented
 Structure supports such concepts as polymorphism, operation
overloading and multiple inheritance.
o Indentation
 Indentation is one of the greatest feature in python
 It’s free (open source)
 Downloading python and installing python is free and easy
o It’s Powerful
 Dynamic typing
 Built-in types and tools
 Library utilities
 Third party utilities (e.g. Numeric, NumPy, sciPy)
 Automatic memory management
o It’s Portable
 Python runs virtually every major platform used today
 As long as you have a compatible python interpreter installed,
python programs will run in exactly the same manner, irrespective of
platform.
o It’s easy to use and learn
 No intermediate compile
 Python Programs are compiled automatically to an intermediate
form called byte code, which the interpreter then reads.
 This gives python the development speed of an interpreter without
the performance loss inherent in purely interpreted languages.
 Structure and syntax are pretty intuitive and easy to grasp.
o Interpreted Language
 Python is processed at runtime by python Interpreter
 Interactive Programming Language
 Users can interact with the python interpreter directly for writing the
programs
o Straight forward syntax
 The formation of python syntax is simple and straight forward which
also makes it popular.

Installation:
There are many interpreters available freely to run Python scripts like IDLE
(Integrated Development Environment) which is installed when you install the
python software from http://python.org/downloads/

Steps to be followed and remembered:


Step 1: Select Version of Python to Install.
Step 2: Download Python Executable Installer.
Step 3: Run Executable Installer.
Step 4: Verify Python Was Installed On Windows.
Step 5: Verify Pip Was Installed.
Step 6: Add Python Path to Environment Variables (Optional)
Working with Python Python Code Execution:
Python’s traditional runtime execution model: Source code you type is translated to byte
code, which is then run by the Python Virtual Machine (PVM). Your code is automatically
compiled, but then it is interpreted.

Sourcecode Byte code Runtime

m.py m.pyc PVM

Source code extension is .py Byte code extension is .pyc


(Compiled python code)
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.

1.2 ALGORITHMS
What is algorithm?
An algorithm is a finite number of clearly described, unambiguous ―”doable”
steps that can be systematically followed to produce a desired result for given input in
a finite amount of time . Algorithms are the initial stage of problem solving. Algorithms
can be simply stated as a sequence of actions or computation methods to be done for
solving a particular problem. An algorithm should eventually terminate and used to
solve general problems and not specific problems.

The word ―algorithm is derived from the ninth-century Arab mathematician,


Al-Khwarizmi. He worked on ―written processes to achieve some goal. Computer
algorithms are central to computer science. They provide step-by-step methods of
computation that computers can carry out. High speed computers can follow a given
set of instructions for their computation which are programs. Programs are built from
algorithms. However, the computation that a given computer performs is only as good as
the underlying algorithm used.
Features
● An algorithm is a collection of well-defined, unambiguous and effectively
computable instructions, if execute it will return the proper output.
● Well-defined- The instructions given in an algorithm should be simple and
defined well.
● Unambiguous- The instructions should be clear,there should not be ambiguity .
● Effectively computable- The instructions should be written step by step ,which
helps computer to understand the control flow.
We often use algorithm in our day-to-day life, but when and how?
● Our cooking receipe
● Our daily routine as a student
● When we buy something
● When we go outing
● Our class routine

BUILDING BLOCKS OF ALGORITHMS


Building blocks are necessary to decide how we want to manipulate units of
work. The basis of every algorithm is steps or blocks of operations.
The building blocks are:
● Statements
● State
● Control flow
● Functions
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
It has been proven that any algorithm can be constructed from just three basic
building blocks. These three building blocks are Sequence, Selection, and Iteration
(Repetition).

Sequence
This describes a sequence of actions that a program carries out one after another,
unconditionally. Execute a list of statements in order. Consider an example,

Example 1.1 A l g o r i t h m for Baking Bread

Step1: Add flour.


Step 2: Add salt.
Step 3: Add yeast.
Step 4: Mix.
Step 5: Add water.
Step 6: Knead.
Step 7: Let rise.
Step 8: Bake.

Bread has been baked successfully.

Example 1.2 A l g o r i t h m for Addition of two numbers:


Step1: Start
Step 2: Get two numbers as input and store it in to a and b
Step 3: Set c = a+b
Step 4: Print c
Step 5: Stop.

Example 1.3 Algorithm to prepare Green Tea

Step 1: Fill the kettle with water


Step 2: Boil the water in kettle
Step 3: Put the green tea leaves in the pot
Step 4: Pour the boiling water in the pot
Step 5: Steep the tea leaves for 2 – 3 minutes
Step 6: Stop

Example 1.4 Algorithm to multiply two numbers

Step 1: Input first number as A


Step 2: Input second number as B
Step 3: Set Mul = A*B
Step 4: Print Mul
Step 5: End
Example 1.5 Algorithm for interchanging of two numbers

Step Step
1: Start
1: Start
Step Step
2: READ num1,
2: READ num2num2
num1,
Step Step
3: temp = num1
3: temp = num1
Step Step
4: num1 = num2
4: num1 = num2 S
Step Step
5: num2 = temp
5: num2 = temp
Step Step 6: PRINT
6: PRINT num1,
num1, num2num2
Step Step 7: Stop
7: Stop

1.3 REPRRESENTING PROBLEMS AND SOLVING WITH FLOWCGARTS:

SELECTION:
Control flow statements are able to make decisions based on the conditions.
Selection is the program construct that allows a program to choose between
different actions. Choose at most one action from several alternative conditions.

Entr
y

Fals Conditio Tru


e n to e
make

Action 1 Action 2
The decision statements are:
● if
● if/else
● switch

The general form of the if construct can be:


IF condition then process
Although a program might seem like a linear path—one statement following
another— conditional statements act like intersections, allowing you to change
directions on the basis of a given condition.
A condition flow can also be stated in the following manner:
IFcondition
then process 1
ELSE
process 2
This form is known as the if – else construct. Here, if the condition is true then
process 1 is
executed, else process 2 is executed.
Example 1.6 Algorithm for printing Grade

Marks Grade
Above 75 O
60-75 A
50-60 B
40-50 C
Less than 40 D

Step 1: Enter the marks obtained as M


Step 2: IF M > 75
Print “O”
Step 3: IF M>=60 and M<75
Print “A”
Step 4: IF M>50 and M<60
Print “B”
Step 5: IF M>=40 and M<50
Print “C”
ELSE
Print “D”
[END of IF]
Step 6: End

Example 1.7 Algorithm to find the equality of two numbers

Step 1 : Start
Step 2 : Input first number as A
Step 3 : Input second number as B
Step 4 : IF A==B
Print “Equal”
ELSE
Print “ Not Equal”
Strep 5 : Stop

Example 1.8 Algorithm to find the largest of three numbers


Step 1: Start
Step 2: Declare variables a,b and c.
Step 3: Read variables a,b and c.
Step 4: If a>b
If a>c
Display a is the largest number.
Else
Display c is the largest number.
Else
If b>c
Display b is the largest number.
Else
Display c is the greatest number.
Step 5: Stop

Example 1.9 Algorithm to find biggest among 2 nos:


Step1: Start
Step 2: Get two numbers as input and store it in to a and b
Step 3: If a is greater than b then
Step 4: Print a is big
Step 5: else
Step 6: Print b is big
Step 7: Stop

1.4 ITERATION
While Statement:
The WHILE construct is used to specify a loop with a test at the top. The beginning
and ending of the loop are indicated by two keywords WHILE and ENDWHILE.
The general form is:
WHILE condition
Sequence
END WHILE
FOR loop:
This loop is a specialized construct for iterating a specific number of times,
often called a “counting” loop. Two keywords, FOR and ENDFOR are used.
The general form is:
FOR iteration bounds
Sequence
END FOR
Repetition (loop) may be defined as a smaller program the can be executed several
times in a main program. Repeat a block of statements while a condition is true.
Example 1.10 Algorithm for Washing Dishes
Step1: Stack dishes by sink.
Step 2: Fill sink with hot soapy water.
Step 3: While moreDishes
Step 4: Get dish from counter,Wash dish
Step 5: Put dish in drain rack.
Step 6: End While
Step 7: Wipe off counter.
Step 8: Rinse out sink.
Example 1.11 Algorithm to calculate factorial no:

Step1: Start
Step 2: Read the number num.
Step 3: Initialize i is equal to 1 and fact is equal to 1
Step 4: Repeat step4 through 6 until I is equal to num
Step 5: fact = fact * i
Step 6: i = i+1
Step 7: Print fact
Step 8: Stop

Example 1.12 Algorithm to find the factorial of a number


Step 1. Read the value of n.
Step2.1.i Read
Step =1,F the=1value of n.
Step3.2.ifi (=i1>, nF )=1
Step go to 7
Step4.3.Fif=( Fi >* ni ) go to 7 Step
Step
4. F 5.
Step = Fi =* ii + 1
Step6.5.go
Step i =toi +3 1
Step7.6.Display
Step go to 3 the value of S
Step8.7.Stop
Step Display the value of S Step
8. Stop
Example 1.13 Algorithm to print numbers from 1 to 10
Step
Step1:1:Set
Seti=1,
i=1,n=10
n=10
Step
Step2:2:Repeat
Repeatsteps
steps3 3and
and4 4while
whilei<=n
Step
i<=n3:Step
Print3:i Print i
Step
Step4:4:Set
Seti=i+1
[End of loop]
i=i+1
Step
[End5:of
End
loop] Step
5: End

1.5 RECURSION
Recursion is a technique of solving a problem by breaking it down into smaller
and smaller sub problems until you get to a small enough problem that it can be easily
solved. Usually, recursion involves a function calling itself until a specified a specified
condition is met.
Example 1.14 Algorithm for factorial using recursion

Step 1 : Start
Step 2 : Input number as n
Step 3 : Call factorial(n)
Step 4 : End

Factorial(n)
Step 1 : Set f=1
Step 2: IF n==1 then return 1
ELSE
Set f=n*factorial(n-1)
Step 3 : print f
Functions:
Functions allow us to conceive of our program as a bunch of sub-steps. When
any program seems too hard, just break the overall program into sub-steps! They allow
us to reuse code instead of rewriting it. Every programming language lets you create
blocks of code that, when called, perform tasks. All programming functions have input
and output. The function contains instructions used to create the output from its input.
The general form of a function definition has return type, parameter list, function
name and function body.
def function_name( parameter list ):
body of the function
return [expression]

1.6 ALGORITHM NOTATIONS (EXPRESSING ALGORITHMS)

As we know that, an algorithm is a sequence of finite instructions, often used for


calculation and data processing.
Input List

Algorithm

A step-by-step method for


solving a problem or doing a
task

Output List
Algorithms can be expressed in many kinds of notation, including

Pseudocod
e

Flowchar
t

Programmin
g
Language
1.6.1 Pseudocode
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.

1.6.1.1 Guidelines for writing pseudo code


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

1.6.1.2 Common keywords used in pseudo code


The following gives common keywords used in pseudo codes.
1. This keyword used to represent a comment.
2. BEGIN,END: Begin is the first statement and end is the last statement.
3. INPUT, GET, READ: The keyword is used to inputting data.
4. COMPUTE, CALCULATE: used for calculation of the result of the given
expression.
5. ADD, SUBTRACT, INITIALIZE used for addition, subtraction and
initialization.
6. OUTPUT, PRINT, DISPLAY: It is used to display the output of the program.
7. IF, ELSE, ENDIF: used to make decision.
8. WHILE, ENDWHILE: used for iterative statements.
9. FOR, ENDFOR: Another iterative incremented/decremented tested
automatically.

1.6.1.3 How to write a pseudo code


Start by writing down the purpose of the process.
Write initial steps of pseudo code that set the stage for functions.
Write functional pseudo code.
Add comments, if necessary.
Read over the finished project for logic errors .
Review the pseudo code.

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

get n

i=1

no
yes
is
i <=
n

stop print i

i=i+1
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.
Example 1.22 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

Star factorial(
t n)

Get
n
Yes
if(n =
1) fact =
call 1
factorial(n) N
o

fact = return
Print n*factorial(n-1) fact
fact

Sto
p
Example 1.23 Pseudo code for factorial using recursion:

Main function:
BEGIN
GET n
CALL factorial(n)
PRINT fact
BIN
Sub function factorial(n):
IF(n==1) THEN
fact=1
RETURN fact
ELSE
RETURN fact=n*factorial(n-1)
TWO MARKS QUESTION AND ANSWERS

1. What is an algorithm?
An algorithm is a finite number of clearly described, unambiguous
do able steps that can be systematically followed to produce a
desired results for given input in the given amount of time. In other
word, an algorithm is a step-by-step procedure to solve a problem
with finite number of steps.

2. What is Pseudo code?


Pseudocode is an informal high-level description of the operating
principle of a computer program or algorithm. Pseudo means
false and code refers to instructions written in programming
language.

3. What is Problem Solving?


Problem solving is the systematic approach to define the problem and creating
number of solutions. The problem- s o l v i n g process starts with the problem
specifications and ends with a correct program.

4.Distinguish between algorithm and program.

Algorithm Program
1. Systematic logical approach It is exact code written
which is a well-defined, step-by- for problem following all the
step procedure that allows a rules of the programming
computer to solve a problem. language.
2. An algorithm is a finite number The program will accept the
of clearly described, data to perform computation.
unambiguous do able steps that
can be systematically followed Program=Algorithm + Data
to produce a desired results for
given input in the given amount
of time.

5. Define Flow chart.


A graphical representation of an algorithm. Flow charts is a diagram made up
of boxes, diamonds, and other shapes, connected by arrows.
6. Write an algorithm to accept two numbers, compute the sum and
print the result.
Step 1: Start
Step 2: Declare variables num1, num2 and sum
Step 3: Read values num 1 and num2.
Step 4: Add and assign the result to sum.
Sum←num1+num2
Step 5: Display sum

7. What is Programming language? With example.


Programming Language is a formal language with set of instruction, to the computer to solve a
problem. Java, C, C++, Python, PHP.

8. What are the steps for developing algorithms.


 Problem definition
 Development of a model
 Specification of Algorithm
 Designing an Algorithm
 Checking the correctness of Algorithm
 Analysis of Algorithm
 Implementation of Algorithm
 Program testing
 Documentation Preparation
UNIT II

DATA TYPES, EXPRESSIONS,


STATEMENTS

2.1 PYTHON INTERPRETER


A computer program is a collection of instructions that perform a speciûc task
when executed by a computer.” - Process of writing a program is called programming.
Computer programs are written to solve speciûc problems.

Steps involved in solving a problem is known as Logic.There can be multiple


logic to solve the same problem. Algorithm is a widely used form of representing
Logic.
No. of teachers available= Total no. of teachers– No. of teachers busy in other
classes in 4th lecture – No. of teachers on leaveTop of Form.
Python programming language
● Python is an example of a high level language; other high-level languages
you might have heard of are C++, PHP, Pascal, C#, and Java.
● There are also low-level languages, sometimes referred to as machine
languages or assembly languages.
● Computers can only execute programs written in low-level languages.
● Thus programs written in the high level language have to be translated into
something more suitable before they can run.
● It is easier to program high level languages.
● These high level languages are executed in different computers.
Python features
Python is a High Level, Interpreted, Interactive and Object Oriented Programming
Language
● Beginners Language
● Extensive Standard Library
● Cross Platform Compatibility
● Interactive Mode
● Portable and Extendable
● Databases and GUI Programming
● Scalable and Dynamic Semantics
● Automatic Garbage Collection
High level languages – Only humans can understand
Interpreter / Compiler – Translate the high level language to machine language
and vice ersa Low level language – Only machine can understand (0s and 1s)
The engine that translates and runs Python is called the Python Interpreter:
There are two ways to use it:
1. Immediate mode or interactive mode and
2. Script mode.
Python interpreter and interactive mode
An interpreter is a computer program which executes other programs. Python
interpreter carries out instructions in your program. This interpreter can be used
interactively to test out instructions on the fly.

Python interpreters
Python interpreters are available for many operating systems, allowing Python
code to run on a wide variety of systems.

>>> bytecod
Bytecod Virtual Progra
or
Prompt e
e Machin m
.py
Sc
Compli e Output

.pyc
Module impo
rt
Two Parts
1. Python byte code compiler
The byte code compiler accepts human readable python expressions and
statements as input and produces machine readable python code as output.
2. A virtual Machine which executes python byte code.
The virtual machine accepts Python byte code as input. And executes the virtual
machine instructions represented by the byte code.
2.2 PYTHON MODES
1. Interactive mode
Interactive Mode, as the name suggests, allows us to interact with OS. Here,
when we type Python statement, interpreter displays the result(s) immediately. That
means, when we type Python expression / statement / command after the prompt (>>>),
the Python immediately responses with the output of it.
The three right arrows are the expression prompt. The prompt is telling you that
the Python system is waiting for you to type an expression. The window in which the
output is displayed and input is gathered is termed the console.
Let’s see what will happen when we type print “WELCOME TO PYTHON
PROGRAMMING” after the prompt.
>>>print “WELCOME TO PYTHON PROGRAMMING”
WELCOME TO PYTHON PROGRAMMING
Example:
>>> print 5+10
15
>>> x=10
>>>y=20
>>> print x*y
200
Almost all Python expressions are typed on a single line. An exception to this rule
occurs when expressions are typed in parenthesis. Each opening parenthesis must be
matched to a closing parenthesis.
If the closing parenthesis is not found, a continuation prompt is given. Normally this
continuation prompt looks like an ellipsis, that is, three dots.
(2 +...
The continuation prompt is telling you that there is more to the expression you
need to type. Fill in the rest of the expression, hit return, and the expression will be
evaluated as before:
>>> (2+
……..3)
>>>5

2. Script Mode
In script mode, we type Python program in a file and then use interpreter to
execute the content of the file. Working in interactive mode is convenient for beginners
and for testing small pieces of code, as one can test them immediately.
But for coding of more than few lines, we should always save our code so that it
can be modified and reused.
Python, in interactive mode, is good enough to learn, experiment or explore, but
its only drawback is that we cannot save the statements and have to retype all the
statements once again to re-run them.

Example: Input any two numbers and to find Quotient and Remainder.
Code:
a = input (“Enter first number”)
b = input (“Enter second number”)
print “Quotient”, a/b
print “Remainder”, a%b
Enter first number10
Enter second number3
Quotient 3

2.3 VALUES AND DATA TYPES


2.3.1 VALUES:
A value is one of the basic things a program. There are different values integers, float
and strings. The numbers with a decimal point belong to a type called float. The values
written in quotes will be considered as string, even it’s an integer. If type of value is
not known it can be interpreted as
Example:
>>> type(‘Hello, World!’)
<type ‘str’>
>>> type(17)
<type ‘int’>
>>> type(‘17’)
<type ‘str’>
>>> type(‘3.2’)
<type ‘str’>
Every object has:
● An Identity,
● A type, and
● A value.
2.3.2 Identifier:
Identifier is the name given to entities like class, functions, variables etc. in
Python. It helps differentiating one entity from another.
Rules
1. Identifiers can be a combination of letters in lowercase (a to z) or uppercase
(A to Z) or digits (0 to 9) or an underscore (_). Names like myClass, var_1
and print_this_to_screen, all are valid example.
2. An identifier cannot start with a digit.
3. Keywords cannot be used as identifiers.
4. We cannot use special symbols like !, @, #, $, % etc. in our identifier.
5. Identifier can be of any length.

2.3.3 Data Type

Data Types

Numbers None Sequences Sets Mappings

Integer Floating Complex Point

Boolean
It is a set of values, and the allowable operations on those values. It can be one
of the following:

Category Data Type Example


Numeric int 675
complex 2 + 5j
float 642.43
Textual String(will be discussed “John”
in detail later)
Logical Boolean True, False

1. Python Numbers:
Number data types store numeric values. Number objects are created when you
assign a value to them.
For example
var1 = 1
var2 = 10
You can also delete the reference to a number object by using the del statement.
The syntax of the del statement is
del var1[,var2[,var3[......,varN]]]]
You can delete a single object or multiple objects by using the del statement.
For example
del var
del var_a, var_b
Python supports four different numerical types
 int (signed integers)
 long (long integers, they can also be represented in octal and hexadecimal)
 float (floating point real values)
 complex (complex numbers)
Examples
Here are some examples of numbers

int Long float complex


10 51924361L 0.0 3.14j
100 –0x19323L 15.20 45.j
–786 0122L –21.9 9.322e–36j
080 0xDEFABCECBDAECBFBAEl 32.3+e18 .876j
–0490 535633629843L –90. –.6545+0J
–0x260 –052318172735L –32.54e100 3e+26J
0x69 –4721885298529L 70.2–E12 4.53e–7j

Python allows you to use a lowercase l with long, but it is recommended that
you use only an uppercase L to avoid confusion with the number 1. Python displays
long integers with an uppercase L.
A complex number consists of an ordered pair of real floating-point numbers
denoted by x + yj, where x and y are the real numbers and j is the imaginary unit.
The built in numeric types supports the following operations:

x+y sum of x and y


x–y difference of x and y
x*y product of x and y
x/y quotent of x and y
x//y (floored) quotient of x and y
x%y remainder of x/y
–x x negated
+ x unchanged
abs(x) absolute value of magnitude of x
int(x) x converted to integer
long(x) x converted to long integer
float(x) x converted to floating point
complex(re.im) a complex number with real part re, imaginary part im. im
defaults to zero.
c.conjugate() conjugate of the complex number c. (Identity on real
numbers)
divmod(x, y) the pair (x//y, x%y)
pow(x, y) x to the power y
x**y x to the power y

2.Boolean
A Boolean value is either true or false. It is named after the British mathematician,
George Boole, who first formulated Boolean algebra.
In Python, the two Boolean values are True and False (the capitalization must be
exactly as shown), and the Python type is bool.
>>> type(True)
<class ‘bool‘>
>>> type(true)
Traceback (most recent call last):
File “<interactive input>”, line 1, in <module>
NameError: name ‘true‘ is not defined
Example:
>>> 5 == (3 + 2) # Is five equal 5 to the result of 3 + 2?
True
>>> 5 == 6
False
>>> j = “hel”
>>> j + “lo” == “hello”
True
3. String
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
Example

str = ‘Hello World!’


print str # Prints complete string
print str[0] # Prints first character of the string
print str[2:5] # Prints characters starting from 3rd to 5th
print str[2:] # Prints string starting from 3rd character
print str * 2 # Prints string two times
print str + “TEST” # Prints concatenated string

Output
Hello World!

H
lo
llo World!
Hello World!Hello World!
Hello World!TEST
Strings in Python can be enclosed in either single quotes (‘) or double quotes
(“), or three of each ( ‘ or “””)
>>>type(‘This is a string.‘) <class ‘str‘>
>>> type(“And so is this.”)
<class ‘str‘>
>>>type(“””and this.”””)
<class ‘str‘>
>>>type(‘‘‘and even this...‘‘‘)
<class ‘str‘>
Double quoted strings can contain single quotes inside them.
(“Alice‘s Cup”)
Single quoted strings can contain double quotes inside them
(‘Alice said ,”Hello”’)
Strings enclosed with three occurrences of either quote symbol are called triple
quoted strings. They can contain either single or double quotes:
>>>print(‘‘‘“Oh no”, she exclaimed, “Ben‘s bike is broken!”‘‘‘) “Oh no”,
she exclaimed, “Ben‘s bike is broken!”
>>>Triple quoted strings can even span multiple lines:
>>>message = “””This message will
... span several
... lines.”””
>>>print(message)
This message will span several lines.
4. Lists

List is also a sequence of values of any type. Values in the list are called elements
/Items. These are mutable and indexed/ordered. List is enclosed in square
brackets ([]).
Example
list = [ ‘abcd’, 786 , 2.23, ‘john’, 70.2 ]
tinylist = [123, ‘john’]
print list # Prints complete list
print list[0] # Prints first element of the list
print list[1:3] # Prints elements starting from 2nd till 3rd
print list[2:] # Prints elements starting from 3rd element
print tinylist * 2 # Prints list two times
print list + tinylist # Prints concatenated lists

Output
[‘abcd’, 786, 2.23, ‘john’, 70.200000000000003]
abcd
[786, 2.23]
[2.23, ‘john’, 70.200000000000003]
[123, ‘john’, 123, ‘john’]
[‘abcd’, 786, 2.23, ‘john’, 70.200000000000003, 123, ‘john’]

5. Variable
One of the most powerful features of a programming language is the ability to
manipulate variables. A variable is a name that refers to a value.
The assignment statement creates new variables and gives them values:
>>> message = “What’s up, Doc?”
>>> n = 17
>>> pi = 3.14159
This example makes three assignments. The first assigns the string “What’s up,
Doc?” to a new variable named message. The second gives the integer 17 to n, and the
third gives the floating-point number 3.14159 to pi.
The print statement also works with variables.
>>> print message What’s up, Doc?
>>> print n
17
>>> print pi
3.14159
The type of a variable is the type of the value it refers to.
>>> type(message) <type ‘str’>
>>> type(n)
<type ‘int’>
>>> type(pi)
<type ‘float’>
Multiple Assignment
Python allows you to assign a single value to several variables simultaneously.
For example “
a=b=c=1
Here, an integer object is created with the value 1, and all three variables are
assigned to the same memory location. You can also assign multiple objects to multiple
variables.
For example “
a,b,c = 1,2,”john”
Here, two integer objects with values 1 and 2 are assigned to variables a and b
respectively, and one string object with the value “john” is assigned to the variable c.

6. Keywords
Keywords define the language ‘s rules and structure, and they cannot be used as
variable names. Python has thirty-one keywords:

and del from not while

As elif global or with


assert else if pass yield

break except import print

class exec in raise

continue finally is return

Def For lambda try

7. Expressions And Statements


Expressions
An expression is a combination of values, variables, and operators. If you type
an expression on the command line, the interpreter evaluates it and displays the result:
>>> 1 + 1
2
Example : Finding area and perimeter
length = 5
breadth = 2
area = length * breadth
print(‘Area is’, area)
print(‘Perimeter is’, 2 * (length + breadth))

Output:
Area is 10
Perimeter is 14

Statements
A statement is an instruction that the Python interpreter can execute. We have
seen two kinds of statements: print and assignment. When you type a statement on the
command line, Python executes it and displays the result, if there is one. The result of
a print statement is a value. Assignment statements don‘t produce a result. A script
usually contains a sequence of statements. If there is more than one statement, the
results appear one at a time as the statements execute.
Example

print 1
x=2
print x
It produces the following output
1
2

8. Tuple Assignment

Tuples are a sequence of values of any type and are indexed by integers. They
are immutable. Tuples are enclosed in ().
Example

tuple = ( ‘abcd’, 786 , 2.23, ‘john’, 70.2 )


tinytuple = (123, ‘john’)
print tuple # Prints complete list
print tuple[0] # Prints first element of the list
print tuple[1:3] # Prints elements starting from 2nd till 3rd
print tuple[2:] # Prints elements starting from 3rd element
print tinytuple * 2 # Prints list two times
print tuple + tinytuple # Prints concatenated lists

Output

(‘abcd’, 786, 2.23, ‘john’, 70.200000000000003)


abcd
(786, (2.23, ‘john’, 70.200000000000003)
2.23)

(123, ‘john’, 123, ‘john’)


(‘abcd’, 786, 2.23, ‘john’, 70.200000000000003, 123, ‘john’)
The following code is invalid with tuple, because we attempted to update a tuple,
which is not allowed. Similar case is possible with lists –
tuple = ( ‘abcd’, 786 , 2.23, ‘john’, 70.2 )
list = [ ‘abcd’, 786 , 2.23, ‘john’, 70.2 ]
tuple[2] = 1000 # Invalid syntax with tuple
list[2] = 1000 # Valid syntax with list
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.
(name, surname, b_year, movie, m_year, profession, b_place) = julia
This does the equivalent of seven assignment statements, all on one easy line.
One requirement is that the number of variables on the left must match the number of
elements in the tuple.
One way to think of tuple assignment is as tuple packing/unpacking.
In tuple packing, the values on the left are packed‘ together in a tuple:
>>> b = (“Bob”, 19, “CS”) # tuple packing
In tuple unpacking, the values in a tuple on the right are unpacked‘ into the
variables/names on the right:
>>> b = (“Bob”, 19, “CS”)
>>> (name, age, studies) = b # tuple unpacking
>>> name

‘Bob‘
>>>age
19
>>>studies
‘CS’
Swapping in tuple assignment:
(a, b) = (b, a)
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.
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)
Value Error: need more than 3 values to unpack
2.4 PRECEDENCE OF 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.

Order of operations
When more than one operator appears in an expression, the order of evaluation
depends on the rules of precedence. Python follows the same precedence rules for its
mathematical operators that mathematics does. The acronym PEMDAS is a useful
way to remember the order of operations:
1. 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 though it doesn‘t change the result.

2. Exponentiation has the next highest precedence, so 2**1+1 is 3 and not 4, and
3*1**3 is 3 and not 27.
3. Multiplication and Division have the same precedence, which is higher than
Addition and Subtraction, which also have the same precedence. So 2*3–1 yields
5 rather than 4, and 2/3-1 is -1, not 1 (remember that in integer division, 2/3=0).
4. Operators with the same precedence are evaluated from left to right. So in the
expression minute*100/60, the multiplication happens first, yielding 5900/60,
which in turn yields 98. If the operations had been evaluated from right to left,
the result would have been 59*1, which is 59, which is wrong.

• Operators

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:
Arithmetic operators are used to perform mathematical operations like addition,
subtraction, multiplication etc.
Arithmetic operators in Python

Operator Meaning Example


+ Add two operands or unary plus x+y
– Subtract right operand from the left or
unary minus x-y
* Multiply two operands x*y
/ Divide left operand by the right one (always
results into float) x/y
% Modulus - remainder of the division of left
operand by the right x%y
// x//y
** Exponent - left operand raised to the power
of right x**y(x to the power y)

Examples
a=10
b=5
print(“a+b=”,a+b)
print(“a-b=”,a-b)
print(“a*b=”,a*b)
print(“a/b=”,a/b)
print(“a%b=”,a%b)
print(“a//b=”,a//b)
print(“a**b=”,a**b)

Output
a+b= 15
a-b= 5
a*b= 50
a/b= 2.0
a%b= 0
a//b= 2
a**b= 100000

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.

Operator Symbol Form Result


greater than > a>b True if a is greater than b; else False
less than < a<b True if a is less than b; else False
greater than or equal to >= a>=b True if a is greater than or equal to
b; false False
less than or equal to <= a <=b True if a is less than or equal to b;
else False
equal to == a==b True if a is equal to b; else False
not equal to != a!=b True if a is not equal to b; else False

Example
a=10
b=5
print(“a>b=>”,a>b)
print(“a>b=>”,a<b)
print(“a==b=>”,a==b)
print(“a!=b=>”,a!=b)
print(“a>=b=>”,a<=b)
print(“a>=b=>”,a>=b)

Output:
a>b=> True
a>b=> False
a==b=> False a!
=b=> True
a>=b=> False
a>=b=> True
2.5 ASSIGNMENT OPERATORS
Assignment Operator combines the effect of arithmetic and assignment operator

Operator Name Example Equivalent


+= Addition assignment 1+=8 i=i+8
–= Subtraction assignment i –=8 i=i–8
*= Multiplication assignment 1*=8 1=1*8
/= Float division assignment i/=8 i=i/8
//= Integer division assignment i //=8 i = i // 8
%= Remainder assignment i %=8 i \ i %8
**= Exponent assignment i **=8 i = i ** 8

Example
a = 21
b = 10
c=0
c=a+b
print(“Line 1 - Value of c is “, c) c += a
print(“Line 2 - Value of c is “, c) c *= a
print(“Line 3 - Value of c is “, c) c /= a
print(“Line 4 - Value of c is “, c) c = 2
c %= a
print(“Line 5 - Value of c is “, c) c **= a
print(“Line 6 - Value of c is “, c) c //= a
print(“Line 7 - Value of c is “, c)

Output
Line 1 - Value of c is 31
Line 2 - Value of c is 52
Line 3 - Value of c is 1092
Line 4 - Value of c is 52.0
Line 5 - Value of c is 2
Line 6 - Value of c is 2097152
Line 7 - Value of c is 99864

Logical Operators

Symbol Description
or If any one of the operand is true, then the condition becomes true.
and If both the operands are true, then the condition becomes true.
not Reverses the state of operand/condition.

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
Operator Description Example
& Binary Operator copies a bit to the result (a & b) (means 0000 1100)
AND if it exists in both operands
| Binary OR It copies a bit if it exists in either (a | b) = 61 (means 0011 1101)
operand.
^ Binary XOR It copies the bit if it is set in one (a ^ b) = 49 (means 0011 0001)
operand but not both.
~ Binary Ones It is unary and has the effect of (~a ) = -61 (means 1100 0011
Complement ‘flipping’ bits. in 2’s complement form due to
a signed binary number.
<< Binary The left operands value is moved a << 2 = 240 (means 1111
Left Shift left by the number of bits specified 0000)
by the right operand.
>> Binary The left operands value is moved a >> 2 = 15 (means 0000 1111)
Right Shift right by the number of bits specified
by the right operand.

Example:
a = 60 # 60 = 0011 1100
b = 13 # 13 = 0000 1101
c=0

c = a & b; # 12 = 0000 1100


print “Line 1 - Value of c is “, c

c = a | b; # 61 = 0011 1101
print “Line 2 - Value of c is “, c

c = a ^ b; # 49 = 0011 0001
print “Line 3 - Value of c is “, c

c = ~a; # -61 = 1100 0011


print “Line 4 - Value of c is “, c
c = a << 2; # 240 = 1111 0000
print “Line 5 - Value of c is “, c

Output:
Line 1 - Value of c is 12
Line 2 - Value of c is 61
Line 3 - Value of c is 49
Line 4 - Value of c is -61
Line 5 - Value of c is 240
Line 6 - Value of c is 15
Membership Operators:
These operators test whether a value is a member of a sequence. The sequence
may be a list, a string, or a tuple. We have two membership python operators- ‘in’ and
‘not in’.
Operator Description Example
In Evaluates to true if it finds a variable x in y, here in results in a 1 if
in the specified sequence and false x is a member of sequence y.
otherwise.
not in Evaluates to true if it does not finds a x not in y, here not in results
variable in the specified sequence and in a 1 if x is a member of
false otherwise. sequence y.

Example:
a. in
This checks if a value is a member of a sequence. In our example, we see that the
string ‘fox’ does not belong to the list pets. But the string ‘cat’ belongs to it, so it
returns True. Also, the string ‘me’ is a substring to the string ‘disappointment’.
Therefore, it returns true.
>>> pets=[‘dog’,’cat’,’ferret’]
>>> ‘fox’ in pets
False
>>> ‘cat’ in pets
True
>>> ‘me’ in ‘disappointment’
True
b. not in
Unlike ‘in’, ‘not in’ checks if a value is not a member of a sequence.
>>> ‘pot’ not in ‘disappointment’
True
Identity Operator
Let us proceed towards identity Python Operator.
These operators test if the two operands share an identity. We have two identity
operators- ‘is’ and ‘is not’.
a. is
If two operands have the same identity, it returns True. Otherwise, it returns
False. Here, 2 is not the same as 20, so it returns False. Also, ‘2’ and “2” are the same.
The difference in quotes does not make them different. So, it returns True.
>>> 2 is 20
False
>>> ‘2’ is “2”
True
b. is not
2 is a number, and ‘2’ is a string. So, it returns a True to that.
>>> 2 is not ‘2’
True

2.6 COMMENTS
As programs get bigger and more complicated, they get more difficult to read. It
is a good idea to add notes to your programs to explain in natural language what the
program is doing.
A comment in a computer program is text that is intended only for the human
reader — it is completely ignored by the interpreter.
There are two types of comments in python:
Single line comments
Multi line comments
Single Line Comments
In Python, the # token starts a comment..
Example

print(“Not a comment”)
#print(“Am a comment”)
Result

Not a comment
Multiple Line Comments
Multiple line comments are slightly different. Simply use 3 single quotes before
and after the part you want commented.
Example

’’
print(“We are in a comment”)
print (“We are still in a comment”)
’’
print(“We are out of the comment”)
Result
We are out of the comment

ILLUSTRATIVE EXAMPLES
1. Python Program to swap or exchange the values of two variables
Method 1
a = 10
b = 20
print(“before swapping\na=”, a, “ b=”, b)
temp = a
a=b
b = temp
print(“\nafter swapping\na=”, a, “ b=”, b)
Method 2

a = 30
b = 20
print(“\nBefore swap a = %d and b = %d” %(a, b))
a, b = b, a
print(“\nAfter swaping a = %d and b = %d” %(a, b))
2. Circulate the values of n Variables

l=[1,2,3,4,5]
print(l[::-1])
3. Python Program to test the year is leap or not

year=int(input(“Enter year to be checked:”)) if(year


%4==0 and year%100!=0 or year%400==0):
print(“The year is a leap year!)
else:
print(“The year isn’t a leap year!)
2MARKS QUESTION AND ANSWERS

1. What is mean by high level and low level programming language?


High level language is a computer programming language that resembles natural
language or mathematical notation. It is human readable form. Eg: C, Java,
Python.
Low level language can be understood only by computers. (0,1)
2. What is mean by a python interpreter?

The engine that translates and runs Python is called the Python Interpreter. It is
available for many OS. Two parts of the interpreter are: (i) Python byte code
compiler (ii) A virtual machine
3. What are the two modes of python?
Interactive mode

Interactive Mode, as the name suggests, allows us to interact with OS. Here,
when we type Python statement, interpreter displays the result(s) immediately.
It acts as a calculator.

>>>print “WELCOME TO PYTHON PROGRAMMING” WELCOME


TO PYTHON PROGRAMMING
Script Mode

In script mode, we type Python program in a file and then use interpreter to
execute the content of the file.
4. Define continuation prompt.

The continuation prompt will notify you that there is more to the expression you
need to
type.
>>> (2 +
... 3) # continuation
5
5. What are application and system programs?

Application programs are developed for particular application. System programs


keep the hardware and software running together smoothly.
6. What is mean by values?

A value is one of the basic things a program works with, like a letter or a number.
These values are classified into different classes, or data types:
1,2 – Integers
‘Hello World‘- String
7. Define identifiers.

Identifier is the name given to entities like class, functions, variables etc. in
Python. It helps differentiating one entity from another.
8. What are the rules for declaring the identifiers?

1. 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 (_).
2. An identifier cannot start with a digit.
3. Keywords cannot be used as identifiers.

4. We cannot use special symbols like !, @, #, $, % etc. in our identifier.


5. Identifier can be of any length.
9. Define data type.

The data type specifies the type of data which can be stored.
10. What is Boolean?

A Boolean value is either true or false. In Python, the two Boolean values are
True and False and the Python type is bool
11. What is the use of type() function?

The type function is used to identify the type of the variable.


>>> type(“Hello, World!”)
<class ‘str‘>
>>> type(17)
<class ‘int‘>
12. Define String.

It is an ordered sequence of letters/characters. They are enclosed in single quotes


(‘ ‘) or
double quotes (‘’ “).
str = ‘Hello World!’
>>> type(‘Hello World!‘)
<class ‘str‘>
13. Define Lists.

List is also a sequence of values of any type. Values in the list are called elements
/ items.
These are mutable and indexed/ordered. List is enclosed in square brackets ([]).
list = [ ‘abcd’, 786 , 2.23, ‘john’, 70.2 ]
14. Define variable.

A variable is a name that refers to a value.


The assignment statement creates new variables and gives them values.

>>> message = “Who is this?”


>>> n = 17
15. What is mean by multiple assignment?

Python allows you to assign a single value to several variables simultaneously.


For example “ a = b = c = 1
16. Define keywords.

Keywords define the language‘s rules and structure, and they cannot be used as
variable names. Python has thirty-one keywords. Eg: global, or, with, assert,
else, if, pass, yield
17. State the definition of statement.

A statement is an instruction that the Python interpreter can execute.


Eg: x=2
18. How will you assign a tuple?

Tuples are a sequence of values of any type and are indexed by integers. They
are immutable. Tuples are enclosed in (). Eg: tuple = ( ‘abcd’, 786 , 2.23, ‘john’,
70.2 )
19. State the precedence of operators.

The operator precedence rule in python is used to execute the expression contains
more than one operator.
The precedence rule is:
P EMDAS –
1. Parenthesis
2. Exponentiation
3. Multiplication, Division (Same precedence) – If both comes, evaluate
from left to right
4. Addition , Subtraction (Same precedence) – If both comes, evaluate
from left to right
20. What are comments?

A comment in a computer program is text that is intended only for the human
reader
Comments are used for documenting our program.
It is useful in large programs.
It is not printed and ignored by the interpreter.
Types of comments:
Single line comments – Starts with # symbol.
Eg: #print(“Am a comment”)
Multi line comments – Starts and ends with three single quotes.
Eg:
‘’’
print(“We are in a comment”)
print (“We are still in a comment”)
UNIT III

CONTROL FLOW, FUNCTIONS,


STRINGS
3.1 BOOLEAN VALUES AND OPERATOR
A Boolean expression (or logical expression) evaluates to one of two states true
or false. Python provides the boolean type that can be either set to False or True. The
following examples use the operator ==, which compares two operands and produces
True if they are equal and False otherwise:
Example 3.1:

>>> 5 == 5
True
>>> 5 == 6
False
True and False are special values that belong to the type bool; they are not strings:
Example 3.2:

>>> type(True)
<type ‘bool’>
>>> type(False)
<type ‘bool’>
Capitalization should be exact. Ignoring the proper use of upper or lower case,
will result in error.
Example 3.3:

>>> type(true)
Traceback (most recent call last):
File “<interactive input>, line 1 in <module>,
NameError: name ‘true‘ is not defined
3.1.1 Relational Operators
The relational operators (Comparison Operators) which return the Boolean values
are:

x != y x is not equal to y
x==y x is equal to y
x>y x is greater than y
x<y x is less than y
x >= y x is greater than or equal to y
x <= y x is less than or equal to y
Note: A common error is using the mathematical symbol = in the expressions
and it is an assignment operator. There are no operators like => or =<.
3.1.2 Logical Operators
There are three logical operators: and, or, and not. The semantics (meaning)of
these operators is similar to their meaning in English.
Example3.4:

x>0 True, if x is greater than zero.


x<5 True, if x is less than five.
n%2==0 or n%3==0 True, if either (any one) of the condition is True
True, if both the conditions are True
Example
Program3.5:
Program 1:

n=88
if n%2 ==0 or n%3==0:
print(“yes”)
O
u
t
p
u
t
:
yes
Program 2:

n=6
if n%2==0 or n%3==0:
print(“yes”)
O
u
t
p
u
t
:
yes
The not operator negates a boolean expression, so not (x > y) is True if x > y is
False, that is, if x is less than or equal to y.
The expression on the left of the or operator is evaluated first: if the result is
True, Python does not evaluate the expression on the right — this is called short-
circuit evaluation.
Similarly, for the ―and operator, if the expression on the left yields False, Python
does not evaluate the expression on the right. So there are no unnecessary evaluations.
Python is not very strict. Any nonzero number is interpreted as True:
>>> 42 and True
True
Recommended online video tutorial link: Boolean values and operators
https://www.youtube.com/watch?v=xgzdb2hTdL0

3.1.3 Control Statement


A control statement is a statement that determines the control flow of a set of
instructions. There are three fundamental forms of control that programming languages
provide—
1. Sequential structure (if) – Instructions are executed in an order that they are
written
2. Selection Structure/Branching/Decision Making – Instructions are being
executed selectively based on conditions
● if statement
● If..else statement
● If..elif..else statement
3. Repetition structure/Looping/Iterative – Instructions are repeatedly executed
● while
● For
Unconditional Structure
● Break
● Continue
● Pass

Sequential Control Selection Control Iteractive Control

condition condition
True False
True False
loop

Fig 3.1 Flow of Control Statements


3.2 CONDITIONAL STATEMENTS
IF Statement:
Conditional statement checks conditions and change the behavior of the program
accordingly.
The simplest form is the if statement:
>>>if x > 0:
print(‘x is positive’)
The boolean expression after ―if is called the condition. If it is true, the indented
statement runs. If not, nothing happens.
The syntax of ‘if’ statement:

if <test_expression>:
<body>

Test Fals
Expressio e
n

Tru
e

Body of
if

Fig: 3.2 – Operation of IF statement

Compound statements

Syntax for Compound statements


Header
Body of if
if condition:
Statements
Statements like this are called compound statements. At least one statement must
be there inside the statement and there is no limit for the number of statements.
Occasionally, it is useful to have a body with no statements. In that case, we can use
the pass statement, which does nothing.
Example:

if x < 0:
pass
if grade>=70:
print ( First class‘)
3.2.1.1 if-else Statement (Alternative)

The if..else statement evaluates test expression and will execute body of if only
when test condition is True. If the condition is False, body of else is executed.
Indentation is used to separate the blocks.
The syntax of ‘if..else’ statement:
if test condition:
Body of if
else:
Body of else
Test Fals
Expressio e
n

Tru
e

Body of Body of else


if

Fig 3.3 – Operation of IF..ELSE Statement


Example:

if x % 2 == 0:
print(‘x is even’)
else:
print(‘x is odd’)
If the remainder when x is divided by 2 is 0, then we know that x is even, and the
program displays an appropriate message. If the condition is false, the second set of
statements runs. Since the condition must be true or false, exactly one of the alternatives
will run. The alternatives are called branches, because they are branches in the flow of
execution.
3.2.1.2 Chained Conditionals (IF-ELIF-ELSE Statement)

● Sometimes there are more than two possibilities and we need more than
two branches.
● The elif is short for else if. It allows us to check for multiple expressions.
● If the condition for if is False, it checks the condition of the next elif block
and so on.
● If all the conditions are False, body of else is executed.
● Only one block among the several if...elif...else blocks is executed according
to the condition.
● The if block can have only one else block. But it can have multiple elif
blocks.
The syntax of ‘if..elif..else’ statement:

if condition:
Body of if
elif condition:
Body of elif
else:
Body of else

Test Fals
Expressio e
n of if

Tru
e Test Fals
Expressio e
Body of n of elif
if
Tru
e
Body of Body of
elif else

Fig 3.4 – Operation of if..elif..else statement

Example 1:

if x < y:
print(‘x is less than y’)
elif x > y:
print(‘x is greater than y’)
else:
print(‘x and y are equal’)
elif is an abbreviation of ―else if . Again, exactly one branch will run. There is
no limit on the number of elif statements. If there is an else clause, it has to be at the
end, but there doesn‘t have to be one.
Example 2:

if choice == ‘a’:
draw_a()
elif choice == ‘b’:
draw_b()
elif choice == ‘c’:
draw_c()
Each condition is checked in order. If the first is false, the next is checked, and
so on. If one of them is true, the corresponding branch runs and the statement ends.
3.3 ITERATION
Iteration is repeating a set of instructions and controlling their execution for a
particular number of times. Iteration statements are also called as loops.
3.3.1 State
A new assignment makes an existing variable refer to a new value (and stop
referring to the old value).
>>> x = 5
>>> x
5
>>> x = 7
>>> x
7
The first time we display x, its value is 5; the second time, its value is 7. Python
uses the equal sign (=) for assignment. First, equality is a symmetric relationship and
assignment is not.
For example, in mathematics, if a = 7 then 7 = a. But in Python, the statement a
= 7 is legal and 7 = a is not. Also, in mathematics, a proposition of equality is either
true or false for all time. If a =b now, then a will always equal b. In Python, an
assignment statement can make two variables equal.
>>> a=5
>>> b = a # a and b are now equal
>>> a = 3 # a and b are no longer equal
>>> b
5

The third line changes the value of ―a but does not change the value of ―b , so
they are no longer equal. A common kind of reassignment is an update, where the
new value of the variable depends on the old.
>>> x = x + 1
This means ―get the current value of x, add one, and then update x with the
new value. If we try to update a variable that doesn‘t exist, you get an error, because
Python evaluates the right side before it assigns a value to x:
>>> x = x + 1
NameError: name ‘x’ is not defined, Before you can update a variable, you have
to initialize it, usually with a simple assignment:
>>>x = 0
>>>x = x + 1
Updating a variable by adding 1 is called an increment; subtracting 1 is called a
decrement.

3.3.2 While loop


● Repeats a statement or block of statements while a given condition is TRUE.
● Tests the condition before executing the body of loop.
Or
A while statement is an iterative control statement that repeatedly executes a
set of statements based on a provided Boolean expression (condition).
Syntax of While Loop:
while condition:
statements
Example:

while n > 0:
print(n)
n=n–1
The above while statement prints the value of n a number of times until n is
greater than zero.
The flow of execution for a while statement:

1. Determine whether the condition is true or false.


2. If false, exit the while statement and continue execution at the next statement.
3. If the condition is true, run the body and then go back to step 1

Enter while
loop

Test Fals
Expressio e

Tru
e

Body
of
while

Exit
loop

Fig 3.5 Operation of While Loop

The body of the loop should change the value of one or more variables so that
the condition becomes false eventually and the loop terminates. Otherwise the loop
will repeat forever, which is called an infinite loop. In the case of countdown, we can
prove that the loop terminates: if n is zero or negative, the loop never runs. Otherwise,
n gets smaller each time through the loop, so eventually we have to get to 0. For some
other loops, it is not so easy to tell.
Example: Python while Loop

# Program to add natural numbers up to sum = 1+2+3+...+n


# To take input from the user
n = 10
# initialize sum and counter
sum = 0
i=1
while i <= n:
sum = sum + i
i = i+1 # update counter
print(“The sum is”, sum) # print the sum
Output:
The sum is 55
In the above program, the test condition will be True as long as our counter
variable i is less than or equal to n. We need to increase the value of counter variable
in the body of the loop. This is very important (and mostly forgotten). Failing to do so
will result in an infinite loop (never ending loop). Finally the result is displayed.
While loop with else

We can have an optional else block with while loop as well. The else part is
executed if the condition in the while loop evaluates to False. The while loop can be
terminated with a break statement. In such case, the else part is ignored. Hence, a
while loop’s else part runs if no break occurs and the condition is false.
Example
# Program to illustrate the use of else statement with the while loop
counter = 0
while counter < 3:
print(“Inside loop”)
counter = counter + 1
else:
print(“Inside else”)
Output

Inside loop
Inside loop
Inside loop
Inside else
Here, we use a counter variable to print the string Inside loop three times. On the
forth iteration, the condition in while becomes False. Hence, the else part is executed.
3.3.3 For Loop
The for loop in Python is used to iterate over a sequence (list, tuple, string) or
other iterable objects. Iterating over a sequence is called traversal. The for loops are
used to construct definite loops.
Syntax of FOR LOOP:

for val in sequence:


Body of for
Here, val is the variable that takes the value of the item inside the sequence on
each iteration. Loop continues until we reach the last item in the sequence. The body
of for loop is separated from the rest of the code using indentation.
for each
item in
sequenc
e

Yes
Las
t

N
o
Body of for

Exit
loop
Fig: operation of for loop

Fig 3.6. Operation of FOR LOOP


Example 1:

for k in [4, 2 ,3, 1]:


print (k)
Output:
4
2
3
1
Example 2:

for k in [‘Apple’, ‘Banana’, ‘Pear’]:


print(k)
Output:

Apple
Banana
Pear
The range() function:

 We can generate a sequence of numbers using range() function. range(10)


will generate numbers from 0 to 9 (10 numbers).
 We can also define the start, stop and step size as range(start,stop,step size).
step size defaults to 1 if not provided.
 This function does not store all the values in memory, it would be inefficient.
So it remembers the start, stop, step size and generates the next number on
the go.
 To force this function to output all the items, we can use the function list().
Example:

sum = 0
for k in range(1, 11):
sum = sum + k
The values in the generated sequence include the starting value, up to but not
including the ending value. For example, range(1, 11) generates the sequence [1, 2, 3,
4, 5, 6, 7, 8,9, 10].
The range function is convenient when long sequences of integers are needed.
Actually, range does not create a sequence of integers. It creates a generator function
able to produce each next item of the sequence when needed.
for i in range(4):
print(‘Hello!’)
for loop with else

A for loop can have an optional else block as well. The else part is executed if
the items in the sequence used in for loop exhausts. break statement can be used to
stop a for loop. In such case, the else part is ignored. Hence, a for loop’s else part runs
if no break occurs.
Example:

digits = [0, 1, 5]
for i in digits:
print(i)
else:
print(“No items left.”)
Output:

0
1
5
No items left.
Here, the for loop prints items of the list until the loop exhausts. When the for
loop exhausts, it executes the block of code in the else and prints No items left.
3.3.4 Break
Break statement is used to break the loop. For example, suppose you want to
take input from the user until they type done.
Enter
loop

test Fals
expressio e
n of loop

Tru
e

Yes
break
?

N
Exit loop
o
Remaining
body of
loop
Fig 3.7 Flowchart of Break

You could write:


while True:
line = input(‘> ‘)
if line == ‘done’:
break
print(line)
print(‘Done!’)
The loop condition is True, which is always true, so the loop runs until it hits the
break statement. Each time through, it prompts the user with an angle bracket. If the
user types done, the break statement exits the loop. Otherwise the program echoes
whatever the user types and goes back to the top of the loop.
Here‘s a sample run:
> not done
not done
> done
Done!
This way of writing while loops is common because you can check the condition
anywhere in the loop (not just at the top) and you can express the stop condition
affirmatively (―stop when this happens ) rather than negatively (―keep going until
that happens ).
3.3.5 Continue statement
The continue statement is used to skip the rest of the code inside a loop for the
current iteration only. Loop does not terminate but continues on with the next iteration.
Example: Python continue

# Program to show the use of continue statement inside loops


for val in “string”:
if val == “i”:
continue
print(val)
print(“The end”)
Output

s
t
r
n
g
The end
This program is same as the above example except the break statement has been
replaced with continue. We continue with the loop, if the string is “i”, not executing
the rest of the block. Hence, we see in our output that all the letters except “i” gets
printed.
Enter
loop

Fals
test e
expressio
n of loop
Tru
e

Yes
continue
?

N
Exit loop
o
Remaining
body of
loop

Fig 3.8 Flowchart of Continue

3.3.6 Pass
It is used when a statement is required syntactically but you do not want any
command or code to execute. The pass statement is a null operation; nothing happens
when it executes. The pass is also useful in places where your code will eventually
go, but has not been written yet.
We generally use it as a placeholder.
Suppose we have a loop or a function that is not implemented yet, but we want
to implement it in the future. They cannot have an empty body. The interpreter would
complain. So, we use the pass statement to construct a body that does nothing.
Example:

for letter in ‘Python’:


if letter == ‘h’:
pass
print ‘This is pass block’
print ‘Current Letter :’, letter
print “Good bye!”
Output:

Current Letter : P
Current Letter : y
Current Letter : t
This is pass block
Current Letter : h
Current Letter : o
Current Letter : n
Good bye!
Difference between various iterations Pass Continue Break
Pass

● Statement simply means ‘do nothing’


When the python interpreter encounters the pass statement, it simply
continues with its execution
Continue

● Continue with the loop


resume execution at the top of the loop or goes to next iteration
Break

● Breaks the loop


When a break statement is encountered, it terminates the block and gets the
control out of the loop
While

● Indefinite Loops
The exit condition will be evaluated again, and execution resumes from the
top.
For

● Definite Loop
The item being iterated over will move to its next element.
3.4 FRUITFUL FUNCTIONS

3.4.1 Return Value


The functions with return values are called as fruitful functions. The built-in
functions we have used, such as abs, pow, and max, have produced results. Calling
each of these functions generates a value, which we usually assign to a variable or use
as part of an expression.
biggest = max(3, 7, 2, 5)
x = abs(3 - 11) + 10
But so far, none of the functions we have written has returned a value.
The first example is area, which returns the area of a circle with the given radius:
def area(radius):
temp = 3.14159 * radius**2
return temp
We have seen the return statement before, but in a fruitful function the return
statement includes a return value. This statement means: Return immediately from
this function and use the following expression as a return value. The expression
provided can be arbitrarily complicated, so we could have written this function more
concisely:
def area(radius):
return 3.14159 * radius**2
On the other hand, temporary variables like temp often make debugging easier.
Sometimes it is useful to have multiple return statements, one in each branch of a
conditional. We have already seen the built-in abs, now we see how to write our own:
def absolute_value(x):
if x < 0:
return -x
else:
return x
Since these return statements are in an alternative conditional, only one will be
executed. As soon as one is executed, the function terminates without executing any
subsequent statements. Another way to write the above function is to leave out the
else and just follow the if condition by the second return statement.
def absolute_value(x):
if x < 0:
return -x
return x

Think about this version and convince yourself it works the same as the first
one. Code that appears after a return statement, or any other place the flow of execution
can never reach, is called dead code.
In a fruitful function, it is a good idea to ensure that every possible path through
the program hits a return statement. The following version of absolute value fails to
do this:
def absolute_value(x):
if x < 0:
return -x
elif x > 0:
return x

This version is not correct because if x happens to be 0, neither condition is true,


and the function ends without hitting a return statement. In this case, the return value
is a special value called None:
>>> print
absolute_value(0)
None
None is the unique value of a type called the NoneType:
>>> type(None)
All Python functions return None whenever they do not return another value.
The scope of an identifier is the region of program code in which the identifier can be
accessed, or used.
3.4.2 Scope
There are three important scopes in Python:
● Local scope refers to identifiers declared within a function. These identifiers
are kept in the namespace that belongs to the function, and each function
has its own namespace.
● Global scope refers to all the identifiers declared within the current module,
or file.
● Built-in scope refers to all the identifiers built into Python—those like range
and min that can be used without having to import anything, and are (almost)
always available.
Python (like most other computer languages) uses precedence rules: the same
name could occur in more than one of these scopes, but the innermost, or local scope,
will always take precedence over the global scope, and the global scope always gets
used in preference to the built-in scope.
Let‘s start with a simple example:
def range(n):
return 123*n
print(range(10))
Using the scope lookup rules determines this: our own range function, not the
built-in one, is called, because our function range is in the global namespace, which
takes precedence over the built in names. So although names likes range and min are
built-in, they can be ―hidden from your use if you choose to define your own variables
or functions that reuse those names.
n = 10
2m=3
def f(n):
m=7
return 2*n+m
print(f(5), n, m)
This prints 17 10 3. The reason is that the two variables m and n in lines 1 and 2
are outside the function in the global namespace. Inside the function, new variables
called n and m are created just for the duration of the execution of f. These are created
in the local namespace of function f. Within the body of f, the scope lookup rules
determine that we use the local variables m and n. By contrast, after we‘ve returned
from f, the n and m arguments to the print function refer to the original variables on
lines 1 and 2, and these have not been changed in any way by executing function f.
Notice too that the def puts name f into the global namespace here. So it can be called
on line 7. What is the scope of the variable n on line 1? Its scope—the region in which
it is visible—is lines 1, 2, 6, 7. It is hidden from view in lines 3, 4, 5 because of the
local variable n.
3.4.3 Composition
You can call one function from within another. This ability is called composition.
Example:

Write a function that takes two points, the center of the circle and a point on the
perimeter, and computes the area of the circle. Assume that the center point is stored
in the variables xc and yc, and the perimeter point is in xp and yp. The first step is to
find the radius of the circle, which is the distance between the two points.
radius = distance(xc, yc, xp, yp)
The second step is to find the area of a circle with that radius and return it. Again
we will useone of our earlier functions:
result = area(radius)
return result
#Wrapping that up in a function, we get:
def area2(xc, yc, xp, yp):
radius = distance(xc, yc, xp, yp)
result = area(radius)
return result
We called this function area2 to distinguish it from the area function defined
earlier. The temporary variables radius and result are useful for development,
debugging, and single-stepping through the code to inspect what is happening, but once
the program is working, we can make it more concise by composing the function calls:
def area2(xc, yc, xp, yp):
return area(distance(xc, yc, xp, yp))
3.4.4 Recursion
Recursion is the process of calling the function that is currently executing. It is
legal for one function to call another; it is also legal for a function to call itself. An
example of recursive function to find the factorial of an integer.
Example:
0! = 1
n! = n(n - 1)!
This definition says that the factorial of 0 is 1, and the factorial of any other
value, n, is n multiplied by the factorial of n - 1.
So 3! is 3 times 2!, which is 2 times 1!, which is 1 times 0!. Putting it all together,
3! equals 3 times 2 times 1 times 1, which is 6.
The flow of execution for this program is similar to the flow of countdown. If
we call factorial with the value 3:
● Since 3 is not 0, we take the second branch and calculate the factorial of n-1...
● Since 2 is not 0, we take the second branch and calculate the factorial of n-1...
● Since 1 is not 0, we take the second branch and calculate the factorial of n-1...
● Since 0 equals 0, we take the first branch and return 1 without making any
more recursive calls.
● The return value, 1, is multiplied by n, which is 1, and the result is returned.
● The return value, 1, is multiplied by n, which is 2, and the result is returned.
● The return value (2) is multiplied by n, which is 3, and the result, 6, becomes
the return value of the function call that started the whole process.
● The return values are shown being passed back up the stack. In each frame,
the return value is the value of result, which is the product of n and recurse.
In the last frame, the local variables recurse and result do not exist, because
the branch that creates them does not run.
main

6
factorial n 3 recurse 2 result 6
2
factorial
n 2 recurse 1 result 2 1
factorial
1
factorial n 1 recurse 1 result 1

Example:
n 0
# An example of a recursive function to find the factorial of a number
def factorial(x):
“””This is a recursive functionto find the factorial of an integer”””
if x == 1:
return 1
else:
return (x * factorial(x-1))
num = 3
print(“The factorial of”, num, “is”, factorial(num))
Output:

The factorial of 3 is 6

# An example of to find the factorial of a number without using Recursion function


n=int(input(“Enter number:”))
fact=1
while(n>0):
fact=fact*n
n=n-1
print(“Factorial of the number is: “)
print(fact)
The Advantages of recursion

1. Recursive functions make the code look clean and elegant.


2. A complex task can be broken down into simpler sub-problems using
recursion.
3. Sequence generation is easier with recursion than using some nested iteration.
The Disadvantages of recursion

1. Sometimes the logic behind recursion is hard to follow through.


2. Recursive calls are expensive (inefficient) as they take up a lot of memory
and time.
3. Recursive functions are hard to debug.
3.5 STRINGS

A string is a sequence of characters. You can access the characters one at a time
with the bracket operator:
>>> fruit = ‘banana’
letter = fruit[1]
The second statement selects character number 1 from fruit and assigns it to
letter. The expression in brackets is called an index. The index indicates which
character in the sequence you want (hence the name).But you might not get what
you expect:
>>> letter
‘a’
For most people, the first letter of ‘banana’ is b, not a. But for computer scientists,
the index is an offset from the beginning of the string, and the offset of the first letter
is zero.
>>> letter = fruit[0]
>>> letter
‘b’
So b is the 0th letter (―zero-eth ) of ‘banana’, a is the 1th letter (―one-eth ),
and n is the 2th letter (―two-eth ). As an index you can use an expression that contains
variables and operators:
>>> i=1
>>> fruit[i]
‘a’
But the value of the index has to be an integer. Otherwise you get:
>>> letter = fruit[1.5]
TypeError: string indices must be integers
3.5.1 String slices
A segment of a string is called a slice. Selecting a slice is similar to selecting a
character:
>>> s = ‘Monty Python’
>>> s[0:5]
‘Monty’
>>> s[6:12]
‘Python’
The operator [n:m] returns the part of the string from the ―n-eth character to
the ―m-eth character, including the first but excluding the last. This behavior is
counter intuitive, butit might help to imagine the indices pointing between the
characters. If you omit the first index (before the colon), the slice starts at the beginning
of the string.
If you omit the second index, the slice goes to the end of the string:
>>> fruit = ‘banana’
>>> fruit[:3]
‘ban’
>>> fruit[3:]
‘ana’
If the first index is greater than or equal to the second the result is an empty
string, represented by two quotation marks:
>>> fruit = ‘banana’
>>> fruit[3:3]
‘’
An empty string contains no characters and has length 0, but other than that, it is
the same as any other string.

3.5.2 Immutability
It is tempting to use the [] operator on the left side of an assignment, with the
intention of changing a character in a string.
For example:

>>> greeting = ‘Hello, world!’


>>> greeting[0] = ‘J’
TypeError: ‘str’ object does not support item assignment
The ―object in this case is the string and the ―item is the character you tried to
assign. The reason for the error is that strings are immutable, which means you can‘t
change an existing string. The best you can do is create a new string that is a variation
on the original:
>>> greeting = ‘Hello, world!’
>>> new_greeting = ‘J’ + greeting[1:]
>>> new_greeting
‘Jello, world!’
This example concatenates a new first letter onto a slice of greeting. It has no
effect on the original string.
Length

The len function, when applied to a string, returns the number of characters in a
string:
>>> fruit = “banana”
>>> len(fruit)
6
The index starts counting form zero. In the above string, the index value in from
0 to 5.
To get the last character, we have to subtract 1 from the length of fruit:
size = len(fruit)
last = fruit[size-1]
Alternatively, we can use negative indices, which count backward from the end
of the string.
The expression fruit[-1] yields the last letter, fruit[-2] yields the second to last,
and so on.
3.5.3 String methods

Strings provide methods that perform a variety of useful operations. A method is


similar to a function—it takes arguments and returns a value—but the syntax is
different. For example, the method upper takes a string and returns a new string with
all uppercase letters.
Upper method:

Instead of the function syntax upper(word), it uses the method syntax


word.upper().
>>> word = ‘banana’
>>> new_word = word.upper()
>>> new_word
‘BANANA’
This form of dot notation specifies the name of the method, upper, and the name
of the string to apply the method to, word. The empty parentheses indicate that this
method takes no arguments. A method call is called an invocation; in this case, we
would say that we are invoking upper on word.
Find Method:

The find method can find character and sub strings in a string.
>>> word = ‘banana’
>>> index = word.find(‘a’)
>>> index
1
>>> word.find(‘na’)
2
By default, find starts at the beginning of the string, but it can take a second
argument, the index where it should start:
>>> word.find(‘na’, 3)
4
This is an example of an optional argument; find can also take a third argument,
the index where it should stop:
>>> name = ‘bob’
>>> name.find(‘b’, 1, 2)
-1
This search fails because b does not appear in the index range from 1 to 2, not
including 2.
Split Method:

One of the most useful methods on strings is the split method: it splits a single
multi-word string into a list of individual words, removing all the whitespace between
them. The input string can be read as a single string, and will be split.
>>> ss = “Well I never did said Alice”
>>> wds = ss.split()
>>> wds
[‘Well‘, ‘I‘, ‘never‘, ‘did‘, ‘said‘, ‘Alice‘]
String format method

The easiest and most powerful way to format a string in Python 3 is to use the
format method.
Program:

s1 = “His name is {0}!”.format(“Arthur”)


print(s1)
name = “Alice”
age = 10
s2 = “I am {1} and I am {0} years old.”.format(age, name)
Output:

His name is Arthur!


I am Alice and I am 10 years old.
The template string contains place holders, ... {0} ... {1} ... {2} ... etc. The
format method substitutes its arguments into the place holders. The numbers in the
place holders are indexes that determine which argument gets substituted. Each of the
replacement fields can also contain a format specification — it is always introduced
by the : symbol . This modifies how the substitutions are made into the template, and
can control things like: whether the field is aligned to the left <, center ^, or right > the
width allocated to the field within the result string (a number like 10) the type of
conversion if the type conversion is a float, you can also specify how many decimal
places are wanted.
print(“Pi to three decimal places is {0:.3f}”.format(3.1415926))
3.5.4 Looping and counting
The following program counts the number of times the letter a appears in a string:
Example:

word = ‘banana’
count = 0
for letter in word:
if letter == ‘a’:
count = count + 1
print(count)
This program demonstrates another pattern of computation called a counter.
The variable count is initialized to 0 and then incremented each time an a is found.
When the loop exits, count contains the result—the total number of a‘s.

3.5.5 String module


The Python Standard Library is a collection of built-in modules , each
providing specific functionality beyond what is included in the ―core part of
Python.
This string module contains a number of functions to process standard Python
strings.
Example: Using the string module

import string
text = “Monty Python’s Flying Circus”
print “upper”, “=>”, string.upper(text)
print “lower”, “=>”, string.lower(text)
print “split”, “=>”, string.split(text)
print “join”, “=>”, string.join(string.split(text), “+”)
print “replace”, “=>”, string.replace(text, “Python”, “Java”)
print “find”, “=>”, string.find(text, “Python”), string.find(text, “Java”)
print “count”, “=>”, string.count(text, “n”)
upper => MONTY PYTHON’S FLYING CIRCUS
lower => monty python’s flying circus
split => [‘Monty’, “Python’s”, ‘Flying’, ‘Circus’]
join => Monty+Python’s+Flying+Circus replace => Monty Java’s Flying Circus
find => 6 -1
count => 3
String Example Program:

1. Write a python program to count the number of vowels in a string


Program:
string=raw_input(“Enter string:”)
vowels=0
for i in string:
if(i==’a’ or i==’e’ or i==’i’ or i==’o’ or i==’u’ or i==’A’ or i==’E’ or i==’I’
or i==’O’ or i==’U’):
vowels=vowels+1
print(“Number of vowels are:”)
print(vowels)
Output 1:
Enter string:Hello world
Number of vowels are:
3
Output 2:
Enter string:WELCOME
Number of vowels are:
3
2. Write a Python program to count the occurrences of each word in a given
sentence
Program:
def word_count(str):
counts = dict()
words = str.split()
for word in words:
if word in counts:
counts[word] += 1
else:
counts[word] = 1
return counts
print( word_count(‘the quick brown fox jumps over the lazy dog.’))
Output:
{‘the’: 2, ‘jumps’: 1, ‘brown’: 1, ‘lazy’: 1, ‘fox’: 1, ‘over’: 1, ‘quick’: 1, ‘dog.’: 1}
3.6 LISTS AS ARRAYS
3.6.3 Arrays and lists are both used in Python to store data.
3.6.4 NumPy is used to create an array in python.
3.6.5 It is a module which contains array.
3.6.6 They are used to store any type of data and can be indexed.
3.6.7 The functions which can be performed in list and array are distinct.
Example 1:

x = array([3, 6, 9, 12])
x/3.0x
print(x)
Output:

array([1, 2, 3, 4])
Example 2:

y = [3, 6, 9, 12]
y/3.0
print(y)
The program will result in the error.Arithmetic calculations – can be done
in array.
Storing data efficiently – Array

3.7 ILLUSTRATIVE PROGRAMS


1. Compute the GCD of two numbers
Program:
O def gcd(m,n):
ut if m<n:
p (m,n)=(n,m)
ut while (m%n)==0:
:
return (m)
50 else:
return(gcd(n,m%n))
a=150
b=50
g=gcd(a,b)
print(g)
2. Compute the exponent of a number.
Program:

def exp(m,n):
return m**n
i=input(“Enter the base:”)
j=input(“Enter the pow:”)
d=exp(i,j)
print d
Output:

Enter the base: 40


Enter the pow: 2
1600
3. Linear Search in Python Programming
Program:

list = [4, 2, 8, 9, 3, 7]
x= int(input(“Enter number to search: )) found = False
for i in range(len(list)):
if(list[i] == x):
found = True
print(“%d found at %dth position”%(x,i))
break
if(found == False):
print(“%d is not in list”%x)
Output:

Enter number to search: 2


4. Binary Search using Python Programming
Program:

def binarySearch(alist, item):


first = 0
last = len(alist)-1
found = False
while first<=last and not found:
midpoint = (first + last)//2
if alist[midpoint] == item:
found = True
else:
if item < alist[midpoint]:
last = midpoint-1
else:
first = midpoint+1
return found
testlist = [0, 1, 2, 8, 13, 17, 19, 32, 42,]
print(binarySearch(testlist, 3))
print(binarySearch(testlist, 13))
Output:
False
True
5. Sum an array of N numbers
Program

x=[1,2,3,4,5]
sum=0
for s in range(0,len(x)):
sum=sum+x[s]
print(sum)
O
u
t
p
u
t
:

15
2MARKS QUESTION AND ANSWERS
1. What are the two Boolean values in python
A Boolean value is either True or False.
Python type – bool.
2. What is an operator?

Operator is used to perform operations between operands.


Eg: c+d
+ - operator
C,d – operands
3. Specify the three fundamental forms of control statement

The three forms of control statements are:


● Sequential control
● Iterative control
● Selective control
4. Write the difference between if and if else statement?

If statement – Its used to check a condition and execute the statements.


if(c==5):
print(“five”)
If else is ―alternative execution , in which there are two possibilities and the
condition determines which one runs.
if(c==5):
print(“five”)
else:
print(“not five”)
5. What is iteration?

Iteration is repeating a set of instructions and controlling their execution for a


particular number of times. Iteration statements are also called as loops.
6. Specify the use of range function in for loop.

The range function is generator and able to produce next item of the sequence
when needed.
It is used in a for loop.
Eg: for val in values: print(val)
7. Differentiate break and continue statement with example

The continue statement rejects all the remaining statements in the current
iteration of the loop and moves the control back to the top of the loop.
Break statement is used to break the loop.
Eg:

for number in range(1,5):


if(number==3):
continue
print(number)
Output:
1
2
4
for number in range(1,5):
if(number==3):
break
print(number)
Output:
1
2
3
8. What is the use of pass statement in python?

It is used when a statement is required syntactically but you do not want any
command or code to execute. The pass statement is a null operation; nothing
happens when it executes.
Eg:

for letter in ‘Python’:


if letter == ‘h’:
pass
9. Describe about dead code.

Code that ppears after a return statement, or any other place the flow of execution
can never reach, is called dead code.
def absolute_value(x):
if x < 0:
return -x
return x
10. What refers to local and global scope?

Local scope refers to identifiers declared within a function. These identifiers are
kept in the namespace that belongs to the function, and each function has its
own namespace.
Global scope refers to all the identifiers declared within the current module, or
file.
Built-in scope refers to all the identifiers built into Python
11. Which function is called composition?

A function calls one function with another is called composition.


Eg:
def val():
result = area(radius)
return result
12. What is a recursion? How it differs from loop?

The function which calls itself again and again is called recursion.
Eg:

def factorial(n):
if n == 0:
return 1
else:
recurse = factorial(n-1)
result = n * recurse
return result
13. What is a srting? Mention that how do we represent a string in python?

A string is a sequence, which means it is an ordered collection of other values.


Strings can be represented in python using single quotes, double quotes or triple
double quotes.
Eg: >>> fruit = ‘orange’
14. How does indexing differ from slice operation?

Indexing is assigning the address of every character in string.


Eg: s=”hello”
S[0]=h, s[1]=e, s[2]=l, s[3]=l,s[4]=o
A segment of a string is called a slice. Selecting a slice is similar to selecting a
character.
S=”hello”
S[2:]=”llo”
15. What is string immutability?

We cant exchange the characters of the string. This is called as immutable.


>>> greeting = ‘Hello, world!’
>>> greeting[0] = ‘J’
TypeError: ‘str’ object does not support item assignment
16. List out the methods in string type.

The methods are:


Upper, find, split, string format, etc..
17. Write a python program for exponent of a number

def exp(m,n):
return m**n
i=input(“Enter the base:”)
j=input(“Enter the pow:”)
d=exp(i,j)
print d
18. Define fruitful functions.

Functions which returns a value is called as fruitful function.


def sum(c,d):
e=c+d
return (e)
print(sum(2,3))
19. Define python array.

Arrays and lists are both used in Python to store data.


NumPy is used to create an array in python.
It is a module which contains array.
They are used to store any type of data and can be index
UNIT IV

LISTS, TUPLES, DICTIONARIES


4.1 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.
Example:

ps = [10, 20, 30, 40]


qs = [“spam”, “bungee”, “swallow”]
The first example is a list of four integers. The second is a list of three strings.
The elements of a list don t have to be the same type. The following list contains a
string, a float, an integer, and another list: zs = [“hello”, 2.0, 5, [10, 20]]
A list within another list is said to be nested. Finally, a list with no elements is
called an empty list, and is denoted [].
A list of Integers : [1951,1952,1953,1958,1957]
A list of Strings : [„orange , blue , yellow ]
An empty list : []
4.1.1 List Operations:

Operations Examples Description


create a list >>> a=[2,3,4,5,6,7,8,9,10] in this way we can create alist
>>> print(a) at compile time
[2, 3, 4, 5, 6, 7, 8, 9, 10]
Indexing >>> print(a[0]) Accessing the item in the
2 position 0
>>> print(a[8]) Accessing the item in the
10 position 8
>>> print(a[-1]) Accessing a last elementusing
10 negative indexing.
Slicing >>> print(a[0:3]) Printing a part of the list.
[2, 3, 4]
>>> print(a[0:])
[2, 3, 4, 5, 6, 7, 8, 9, 10]
Concatenation >>>b=[20,30] Adding and printing theitems of
>>> print(a+b) two lists.q
[2, 3, 4, 5, 6, 7, 8, 9, 10, 20, 30]
Repetition >>> print(b*3) Create a multiple copies ofthe
[20, 30, 20, 30, 20, 30] same list.
Updating >>> print(a[2]) Updating the list using index
4>>> a[2]=100 value.
>>> print(a)
[2, 3, 100, 5, 6, 7, 8, 9, 10]
Membership >>> a=[2,3,4,5,6,7,8,9,10] Returns True if element ispresent
>>> 5 in a in list. Otherwisereturns false.
True
>>> 100 in a
False
>>> 2 not in a
False
Comparison >>> a=[2,3,4,5,6,7,8,9,10] Returns True if all elementsin both
>>>b=[2,3,4] elements are same.Otherwise
>>> a==b returns false
False
>>> a!=b
True
4.1.2 List Slicing
The slice operation uses the square brackets. This is termed indexing, or slicing.
An index or slice returns a portion of a larger value. In a string this can be used to
produce a substring. Index values start at zero, and extend upwards to the number of
characters in the string minus one. When a single argument is given it is one character
out of the string. When two integers are written, separated by a colon, it is termed a
slice. The second value is an ending position. A portion of the string starting at the
given position up to but not including the ending position is produced.
Syntax:

Listname[start:stop]
Listname[start:stop:steps]
Example :

Slices Example Description


a[0:3] >>> a=[9,8,7,6,5,4] Printing a part of a list from 0 to 2.
>>> a[0:3]
[9, 8, 7]
a[:4] >>> a[:4] Default start value is 0. soprints from 0
[9, 8, 7, 6] to 3
a[1:] >>> a[1:] default stop value will ben-1. so prints
[8, 7, 6, 5, 4] from 1 to 5
a[:] >>> a[:] Prints the entire list.
[9, 8, 7, 6, 5, 4]
a[2:2] >>> a[2:2] print an empty slice
[]
a[0:6:2] >>> a[0:6:2] Slicing list values with stepsize 2.
[9, 7, 5]
a[::-1] >>> a[::-1] Returns reverse of given listvalues
[4, 5, 6, 7, 8, 9]
4.1.3 List Methods
Methods used in lists are used to manipulate the data quickly. These methods
work only on lists. They do not work on the other sequence types that are not mutable,
that is, the values they contain cannot be changed, added, or deleted.
Syntax:

List_name.method_name( element/index/list)
Syntax example description
a.append(element) >>> a=[1,2,3,4,5] Add an element to the end of the
>>> a.append(6) list
>>> print(a)
[1, 2, 3, 4, 5,
6]
a.insert(index,element) >>> a.insert(0,0) Insert an item at the defined
>>> print(a) index
[0, 1, 2, 3, 4, 5, 6]
a.extend(b) >>> b=[7,8,9] Add all elements of a list to the
>>> a.extend(b) another list
>>> print(a)
[0, 1, 2, 3, 4, 5, 6, 7, 8,9]
a.index(element) >>> a.index(8) Returns the index of the first
8 matched item
a.sort() >>> a.sort() Sort items in a list in ascending
>>> print(a) order
[0, 1, 2, 3, 4, 5, 6, 7, 8]
a.reverse() >>> a.reverse() Reverse the order of items in the
>>> print(a) list
[8, 7, 6, 5, 4, 3, 2, 1, 0]
a.pop() >>> a.pop() Removes and returns an
0 element at the last element
a.pop(index) >>> a.pop(0) Remove the particular element
8 and return it.
a.remove(element) >>> a.remove(1) Removes an item from the list
>>> print(a)
[7, 6, 5, 4, 3, 2]
a.count(element) >>> a.count(6) Returns the count of number of
1 items passed as an argument
a.copy() >>> b=a.copy() Returns a shallow copy of the
>>> print(b) list
[7, 6, 5, 4, 3, 2]
len(list) >>> len(a) Return the length of the length
6
min(list) >>> min(a) Return the minimum element in
2 a list
max(list) >>> max(a) Return the maximum element in
7 a list.

a.clear() >>> a.clear() Removes all items from the list.


>>> print(a)
[]

del(a) >>> del(a) Delete the entire list.


>>> print(a)
Error: name ‘a’ is not
defined

append():
Example 1:
animal = [‘cat’, ‘dog’, ‘rabbit’]
animal.append(‘goat’)
print(‘Updated animal list: ‘, animal)
Output:
Updated animal list: [‘cat’, ‘dog’, ‘rabbit’, ‘goat’]
Example 2:
animal = [‘cat’, ‘dog’, ‘rabbit’]
wild_animal = [‘tiger’, ‘fox’]
animal.append(wild_animal)
print(‘Updated animal list: ‘, animal)
Output:
Updated animal list: [‘cat’, ‘dog’, ‘rabbit’, [‘tiger’, ‘fox’]]
insert():
Example:
vowel = [‘a’, ‘e’, ‘i’, ‘u’]
vowel.insert(3, ‘o’)
print(‘Updated List: ‘, vowel)
Output:
Updated List: [‘a’, ‘e’, ‘i’, ‘u’, ‘o’]

extend():
Example:
language = [‘French’, ‘English’, ‘German’]
language1 = [‘Spanish’, ‘Portuguese’]
language.extend(language1)
print(‘Language List: ‘, language)
Output:
Language List: [‘French’, ‘English’, ‘German’, ‘Spanish’, ‘Portuguese’]

Index():
Example 1:
vowels = [‘a’, ‘e’, ‘i’, ‘o’, ‘i’, ‘u’]
index = vowels.index(‘e’)
print(‘The index of e:’, index)
index = vowels.index(‘i’)
print(‘The index of i:’, index)
Output:
The index of e: 1
The index of e: 2

Example 2:
vowels = [‘a’, ‘e’, ‘i’, ‘o’, ‘u’]
index = vowels.index(‘p’)
print(‘The index of p:’, index)
Output:
ValueError: ‘p’ is not in list

remove():
Example:
animal = [‘cat’, ‘dog’, ‘rabbit’]
animal.remove(‘rabbit’)
print(‘Updated animal list: ‘, animal)
Output:
Updated animal list: [‘cat’, ‘dog’]

clear():
Example:
list = [{1, 2}, (‘a’), [‘1.1’, ‘2.2’]]
list.clear()
print(‘List:’, list)
Output: List: []
Sort():
Example 1:
vowels = [‘e’, ‘a’, ‘u’, ‘o’, ‘i’]
vowels.sort()
print(‘Sorted list:’, vowels)
Output:
Sorted list: [‘a’, ‘e’, ‘i’, ‘o’, ‘u’]
Example 2:
vowels = [‘e’, ‘a’, ‘u’, ‘o’, ‘i’]
vowels.sort(reverse=True)
print(‘Sorted list (in Descending):’, vowels)
Output:
Updated List: [‘a’, ‘e’, ‘i’, ‘u’, ‘o’]
reverse():
Example:
os = [‘Windows’, ‘macOS’, ‘Linux’]
print(‘Original List:’, os)
os.reverse()
print(‘Updated List:’, os)
Output:
Original List: [‘Windows’, ‘macOS’, ‘Linux’]
Updated List: [‘Linux’, ‘macOS’, ‘Windows’]
Example:
os = [‘Windows’, ‘macOS’, ‘Linux’]
print(‘Original List:’, os)
reversed_list = os[::-1]
print(‘Updated List:’, reversed_list)
Output:
Original List: [‘Windows’, ‘macOS’, ‘Linux’]
Updated List: [‘Linux’, ‘macOS’, ‘Windows’]
Pop():
Example:
language = [‘Python’, ‘Java’, ‘C++’, ‘French’, ‘C’]
return_value = language.pop(3)
print(‘Return Value: ‘, return_value)
print(‘Updated List: ‘, language)
Output:

Return Value: French


Updated List: [‘Python’, ‘Java’, ‘C++’, ‘C’]
Example:

language = [‘Python’, ‘Java’, ‘C++’, ‘Ruby’, ‘C’]


print(‘When index is not passed:’)
print(‘Return Value: ‘, language.pop())
print(‘Updated List: ‘, language) print(‘\
nWhen -1 is passed:’) print(‘Return
Value: ‘, language.pop(-1))
print(‘Updated List: ‘, language) print(‘\
nWhen -3 is passed:’) print(‘Return
Value: ‘, language.pop(-3))
print(‘Updated List: ‘, language)
Output:

When index is not passed:


Return Value: C
Updated List: [‘Python’, ‘Java’, ‘C++’, ‘Ruby’]
When -1 is passed:
Return Value: Ruby
Updated List: [‘Python’, ‘Java’, ‘C++’]
When -3 is passed:
Return Value: Python
Updated List: [‘Java’, ‘C++’]
4.1.4 List loop
Python’s for statement provides a convenient means of iterating over lists.
For loop:

A for statement is an iterative control statement that iterates once for each element
in a specified sequence of elements. Thus, for loops are used to construct definite
loops.
Syntax:

for val in sequence:


Example1:

a=[10,20,30,40,50]
for i in a:
print(i)
Output :

1
2
3
4
5
Example 2 :

a=[10,20,30,40,50]
for i in range(0,len(a),1):
print(i)
Output :

0
1
2
3
4
Example 3 :

a=[10,20,30,40,50]
for i in range(0,len(a),1):
print(a[i])
Output ;

10
20
30
40
50
While loop:

The while loop in Python is used to iterate over a block of code as long as the
test expression (condition) is true.When the condition is tested and the result is false,
the loop body will be skipped and the first statement after the while loop will be
executed.
Syntax:

while (condition):
body of while
Example : Sum of Elements in a List

a=[1,2,3,4,5]
i=0
sum=0
while i<len(a):
sum=sum+a[i]
i=i+1
print(sum)
4.1.5 List Mutability
Lists are mutable. When the bracket operator appears on the left side of an
assignment, it Identifies the element of the list that will be assigned.
Example:

Changing Single Element


>>> a=[1,2,3,4,5]
>>> a[0]=100
>>> print(a)
[100, 2, 3, 4, 5]
Changing multiple element

>>> a=[1,2,3,4,5]
>>> a[0:3]=[100,100,100]
>>> print(a)
[100, 100, 100, 4, 5]
The elements from a list can also be removed by assigning the empty list to
them.

>>> a=[1,2,3,4,5]
>>> a[0:3]=[ ]
>>> print(a)
[4, 5]
The elements can be inserted into a list by squeezing them into an empty
slice at the desired location.

>>> a=[1,2,3,4,5]
>>> a[0:0]=[20,30,45]
>>> print(a)
[20,30,45,1, 2, 3, 4, 5]
4.1.6 List Aliasing
Creating a copy of a list is called aliasing. When you create a copy both list will
be having same memory location. Changes in one list will affect another list. Aliasing
refers to having different names for same list values.
Example :

a= [10,20,30,40]
b=a
print (b)
a is b
b[2]=35 10 20 30 40
print(a) a
a = [10, 20, 30]
print(b) 0 1 2
3

Output :

[10,20,30,40]
b
True
[10,20,30,40] 0
3
1 2

[10,20,35,40] b = [10, 20, 30] 10 20 30 40


a

0 1 2 3

0 1 2
b [2] = 35 3

10 20 30 40
a

0 1 2 3

In this a single list object is created and modified using the subscript operator.
When the first element of the list named “a” is replaced, the first element of the list
named “b” is also replaced. This type of change is what is known as a side effect. This
happens because after the assignment b=a, the variables a and b refer to the exact
same list object.
They are aliases for the same object. This phenomenon is known as aliasing. To
prevent aliasing, a new object can be created and the contents of the original can be
copied which is called cloning.
4.1.7 List Cloning
To avoid the disadvantages of copying we are using cloning. Creating a copy of
a same list of elements with two different memory locations is called cloning. Changes
in one list will not affect locations of another list.
Cloning is a process of making a copy of the list without modifying the original
list.

1. Slicing
2. list()method
3. copy() method
Cloning using Slicing

>>>a=[1,2,3,4,5]
>>>b=a[:]
>>>print(b)
[1,2,3,4,5]
>>>a is b
False
Cloning using List( ) method
>>>a=[1,2,3,4,5]
>>>b=list
>>>print(b)
[1,2,3,4,5]
>>>a is b
false
>>>a[0]=100
>>>print(a)
>>>a=[100,2,3,4,5]
>>>print(b)
>>>b=[1,2,3,4,5]
Cloning using copy() method

a=[1,2,3,4,5]
>>>b=a.copy()
>>> print(b) [1, 2, 3, 4, 5]
>>> a is b
False
4.2 List Parameters
In python, arguments are passed by reference. If any changes are done in the
parameter which refers within the function, then the changes also reflects back in the
calling function. When a list to a function is passed, the function gets a reference to
the list.
Passing a list as an argument actually passes a reference to the list, not a copy of
the list. Since lists are mutable, changes made to the elements referenced by the
parameter change the same list that the argument is referencing.
Example1 :

def remove(a):
a.remove(1)
a=[1,2,3,4,5]
remove(a)
print(a)
Output:

[2,3,4,5]
Example 2:

def inside(a):
for i in range(0,len(a),1):
a[i]=a[i]+10
print(“inside”,a)
a=[1,2,3,4,5]
inside(a)
print(“outside”,a)
Output

inside [11, 12, 13, 14, 15]


outside [11, 12, 13, 14, 15]
Example 3
def insert(a):
a.insert(0,30)
a=[1,2,3,4,5]
insert(a)
print(a)
Output

[30, 1, 2, 3, 4, 5]
Suggested links to Refer :

List :
https://www.tutorialspoint.com/videotutorials/
video_course_view.php?course=python_online_training&chapter=python_basic_list_operation
List Using for Loop:
https://www.youtube.com/watch?v=YT6ldZuBW4Y
Python List functions:
https://www.youtube.com/watch?v=96Wr1OO-4d8
Python Slicing: https://www.youtube.com/watch?
v=iD6a0G8MnjA

4.3 TUPLES
A tuple is an immutable linear data structure. Thus, in contrast to lists, once a
tuple is defined, it cannot be altered. Otherwise, tuples and lists are essentially the
same. To distinguish tuples from lists, tuples are denoted by parentheses instead of
square brackets.
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.
An empty tuple is represented by a set of empty parentheses, ().The elements
of tuples are accessed the same as lists, with square brackets, Any attempt to alter a
tuple is invalid. Thus, delete, update, insert, and append operations are not defined
on tuples.
4.3.1 Operations on Tuples
4.3.1.1 Indexing
4.3.1.2 Slicing
4.3.1.3 Concatenation
4.3.1.4 Repetitions
4.3.1.5 Membership
4.3.1.6 Comparison
Creating a tuple

>>>a=(20,40,60,”apple”,”ball”)
Indexing

>>>print(a[0])
20
>>> a[2]
60
Slicing
>>>print(a[1:3])
(40,60)
Concatenation

>>> b=(2,4)
>>>print(a+b)
>>>(20,40,60,”apple”,”ball”,2,4)
Repetition

>>>print(b*2)
>>>(2,4,2,4)
Membership

>>> a=(2,3,4,5,6,7,8,9,10)
>>> 5 in a
True
>>> 100 in a
False
>>> 2 not in a
False
Comparison

>>> a=(2,3,4,5,6,7,8,9,10)
>>>b=(2,3,4)
>>> a==b
False
>>> a!=b
True
4.3.2 Tuple methods
Tuple is immutable so changes cannot be done on the elements of a tuple once it
is assigned.
a.index(tuple)

>>> a=(1,2,3,4,5)
>>> a.index(5)
4
a.count(tuple)

>>>a=(1,2,3,4,5)
>>> a.count(3)
1
len(tuple)

>>> len(a)
5
min(tuple)

>>> min(a)
1
max(tuple)

>>> max(a)
5
del(tuple)

>>> del(a)
4.3.3 Tuple Assignment
Tuple assignment allows variables on the left of an assignment operator and
values of tuple on the right of the assignment operator.
Multiple assignment works by creating a tuple of expressions from the right
hand side, and a tuple of targets from the left, and then matching each expression to a
target.Because multiple assignments use tuples to work, it is often termed tuple
assignment.
Uses of Tuple assignment:

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


Example:

Swapping using temporary variable:


a=20
b=50
temp = a
a=b
b = temp
print(“value after swapping is”,a,b)
Swapping using tuple assignment:

a=20
b=50
(a,b)=(b,a)
print(“value after swapping is”,a,b)
Multiple assignments:

Multiple values can be assigned to multiple variables using tuple assignment.


>>>(a,b,c)=(1,2,3)
>>>print(a)
1
>>>print(b)
2
>>>print(c)
3
4.4 TUPLE AS RETURN VALUE
A Tuple is a comma separated sequence of items. It is created with or
without ( ). A function can return one value. if you want to return more than one value
from a function. We can use tuple as return value.
Example :

Example1: Output:
def div(a,b): enter a value:4
r=a%b enter b value:3
q=a//b reminder: 1
return(r,q) quotient: 1
a=eval(input(“enter a value:”))
b=eval(input(“enter b value:”))
r,q=div(a,b)
print(“reminder:”,r)
print(“quotient:”,q)
Example2: Output:
def min_max(a): smallest: 1
small=min(a) biggest: 6
big=max(a)
return(small,big)
a=[1,2,3,4,6]
small,big=min_max(a)
print(“smallest:”,small)
print(“biggest:”,big)
4.4.1 Tuple as argument
The parameter name that begins with * gathers argument into a tuple.
Example:

def printall(*args):
print(args)
printall(2,3,’a’)
Output :

(2, 3, ‘a’)
Suggested Links to Refer

Tuples : https://www.youtube.com/watch?v=R8mOaSIHT8U
Tuple as Paramerter : https://www.youtube.com/watch?v=sgnP62EXUtA
Tuple assignment : https://www.youtube.com/watch?v=AhSW1sEOzWY

4.5 DICTIONARIES
A dictionary organizes information by association, not position.
Example: when you use a dictionary to look up the definition of “mammal,”
you don t start at page 1; instead, you turn directly to the words beginning with “M.”
Phone books, address books, encyclopedias, and other reference sources also organize
information by association. In Python, a dictionary associates a set of keys with data
values. A Python dictionary is written as a sequence of key/value pairs separated by
commas. These pairs are sometimes called entries. The entire sequence of entries is
enclosed in curly braces ({ and }). A colon (:) separates a key and its value.
Note : Elements in Dictionaries are accessed via keys and not by their position.
Here are some example dictionaries:
dict = {‘Name’: ‘Zara’, ‘Age’: 7, ‘Class’: ‘First’}
print “dict[‘Name’]: “, dict[‘Name’]
print “dict[‘Age’]: “, dict[‘Age’]
Output:

dict[‘Name’]: Zara
dict[‘Age’]: 7
If we attempt to access a data item with a key, which is not part of the dictionary,
we get an error. We can even create an empty dictionary—that is, a dictionary that
contains no entries. We would create an empty dictionary in a program that builds a
dictionary from scratch.
Dictionary Operations

Operations on dictionary:
4.4.1.1 Accessing an element
4.4.1.2 Update
4.4.1.3 Add element
4.4.1.4 Membership
Creating a dictionary

>>> a={1:”one”,2:”two”}
>>> print(a)
{1: ‘one’, 2: ‘two’}
Accessing an element

>>> a[1]
‘one’
>>> a[0]
KeyError: 0
Update

>>> a[1]=”ONE”
>>> print(a)
{1: ‘ONE’, 2: ‘two’}
Add element

>>> a[3]=”three”
>>> print(a)
{1: ‘ONE’, 2: ‘two’, 3: ‘three’}
Membership

a={1: ‘ONE’, 2: ‘two’, 3: ‘three’}


>>> 1 in a
True
>>> 3 not in a
False
Dictionary Methods
Method Example Description
a.copy() a={l: ‘ONE’. 2: ‘two’. 3: ‘three’} It returns copy of the
>>> b=a.copy() dictionary, here copy of
>>> print(b) dictionary ‘a’ get stored in
{1: ‘ONE’, 2: ‘two’. 3: ‘three’} to dictionary ‘b’

a.items() >>> a.items() Return a new view of the


diet_items([(l, ‘ONE’). (2. ‘two’). dictionary’s it ems. It
(3. ‘three’)]) displays a list of
dictionary’s (key, value)
tuple pairs.
a.keys() >> a.keys() It displays list of keys in a
diet keys([1, 2,]) dictionary
a.values() >>> a.values() It displays list of values in
diet_valuesf ([‘ONE’. ‘two’, ‘three’]) dictionary
a.pop(key) >>> a.pop(3) Remove the element with
‘three’ key and return its value
>>> print(a) from the dictionary.
{1: ‘ONE’. 2: ‘two’}
setdefault >>> a.setdefault(3,“three”) If key is in the dictionary,
(key.value) ‘three’ return its value. If key is
>>> print(a) not present, insert key with
{1: ‘ONE’. 2: ‘two’, 3: ‘three’} a value of dictionary and
>>> a.setdefault(2) return dictionary.
‘two’
a.update >>> b={4:”four”} It will add the dictionary
(dictionary) >>> a.update(b) with the existing dictionary
>>> print(a)
{1: ‘ONE’, 2: ‘two’, 3: ‘three’, 4: ‘four’}
fromkeys() >>> key={“apple”.”ball”} It creates a dictionary from
>>> value=“for kids” key and values.
>>> d=dict.fromkeys(key,value)
>>> print(d)
{‘apple’: ‘for kids’, ‘ball’: ‘for kids’}
len(a) a={l: ‘ONE’, 2: ‘two’, 3: ‘three’} It returns the length of the
>>>lena(a) list
3
clear() a={1: ‘ONE’, 2: ‘two’. 3: ‘three’} Remove all elements form
>>>a.clear() the dictionary.
>>>print(a)
>>>{}
del(a) a={l: ‘ONE’, 2: ‘two’. 3: ‘three’} It will delete the entire
>>> del(a) dictionary.
4.6 ADVANCED LIST PROCESSING
1. 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 ]


Example 1:

>>>L=[x**2 for x in range(0,5)]


>>>print(L)
Output :
[0, 1, 4, 9, 16]
Example 2 :

>>>[x for x in range(1,10) if x%2==0]


Output :

[2, 4, 6, 8]
Example 3 :

>>>[x+3 for x in [1,2,3]]


Output :

[4, 5, 6]
Example 4 :

>>> [x*x for x in range(5)]


Output :

[0, 1, 4, 9, 16]
2. 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
1. Program for matrix addition

X = [[12,7,3],
[4 ,5,6],
[7 ,8,9]]

Y = [[5,8,1],
[6,7,3],
[4,5,9]]

result = [[0,0,0],
[0,0,0],
[0,0,0]]

# iterate through rows


for i in range(len(X)):
# iterate through columns
for j in range(len(X[0])):
result[i][j] = X[i][j] + Y[i][j]

for r in result:
print(r)
2. Program for matrix subtraction

X = [[12,7,3],
[4 ,5,6],
[7 ,8,9]]

Y = [[5,8,1],
[6,7,3],
[4,5,9]]

result = [[0,0,0],
[0,0,0],
[0,0,0]]
# iterate through rows
for i in range(len(X)):
# iterate through columns
for j in range(len(X[0])):
result[i][j] = X[i][j] - Y[i][j]
for r in result:
print(r)
TWO MARKS QUESTION AND ANSWERS

1. Define python list.

The list is written as a sequence of data values separated by commas. There are
several ways to create a new list; the simplest is to enclose the elements in
square brackets ([ and ]): ps = [10, 20, 30, 40]
2. Write the different ways to create the list.

List1=[4,5,6].
List2=[]
List2[0]=4
List2[1]=5
List2[2]=6
3. Give an example for nest list

A list within the another list is called as nested list.


Eg: zs = [“hello”, 2.0, 5, [10, 20]]
4. Write the syntax for accessing the list elements.

The way to access list elements is index operator.


Eg: List1=[4,5,6]
List1[0]=4
List1[1]=5
List1[2]=6
5. List out the methods used in list.

Append, Extend, Insert, Index, sort, reverse, pop, remove, clear


6. Write a python program for reversing a list.
vowels = [‘e’, ‘a’, ‘u’, ‘o’, ‘i’] vowels.sort(reverse=True)
print(‘Sorted list (in Descending):’, vowels)
7. Write a python program to add a single element to the end of the list.
vowels = [‘e’, ‘a’, ‘u’, ‘i’]
vowels.append(‘o’)
8. Write a python program to print the list elements using for loop.
num=[10,22,33,44,50,66]
for k in num: print (k)
9. Is list is mutable? Justify your answer.

List elements can be changed once after initializing the list. This is called as
mutability.
>>> numbers = [42, 123]
>>> numbers[1] = 5
>>> numbers[42, 5]
10. Write difference between list aliasing and cloning.

An object with more than one reference has more than one name, the object is
aliased. If the aliased object is mutable, changes made with one alias affect the
other. Clone changes are not being affected the other copy of list.
11. How tuple is differ from list?

Tuples are created by using ( ).


Tuples are immutable.
List is created by using [ ].
List is mutable.
12. Explain how tuples are used 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.
>>> t = divmod(7, 3)
>>> t (2,1)
13. What is a dictionary? Give an example.

Python dictionary is written as a sequence of key/value pairs separated by


commas. These pairs are sometimes called entries. The entire sequence of entries
is enclosed in curly braces ({ and }). A colon (:) separates a key and its value.
Eg: dict = {‘Name’: ‘Zara’, ‘Age’: 7}
14. List out the methods used in dictionary.

Get, fromkeys, clear, copy, items, pop,popitem, setdefault, update, etc. How do
we done the membership test in dictionary?
>>>C={1:1,2:2}
>>>2 in C True
15. Write a python program for iterating the dictionary elements.

squares = {1: 1, 3: 9, 5: 25, 7: 49}


for i in squares: print(squares[i])
16. What is called entries in dictionary?

Python dictionary is written as a sequence of key/value pairs separated by


commas. These pairs are sometimes called entries.
17. List out the built in functions of dictionary.

The functions in dictionary : len( ), any( ), all( ), comp( ), sorted( )


UNIT V

FILES, MODULES, PACKAGES

5.1. FILE AND ITS OPERATION


 File is a collection of record.
 A file stores related data, information, settings or commands in
secondary storage device like magnetic disk, magnetic tape, optical disk,
flash memory.
File Type
1. Text file

2. Binary file

Text file Binary file


Text file is a sequence of characters that Binary files store the data in the binary
can be sequentially processed by a format (i.e .0’s and 1’s)
computer in forward direction
It contains any type of data
Each line is terminated with a special (pdf,images,word doc,spreadsheet,zip
character called the E0L or end of line files,etc)
character
Mode in File

Module Description
r Read only
w mode Write
a only Appending
r+ Read and write only

Differentiate write and append mode:

Write mode Append mode


 It is used to write a string in a file  It is used to append (add) a
 If file is not exist it creates a new string into a file
file  If file is not exist it creates a new
 If file is exit in the specified file
name, the existing content will  It will add the string at the end of
overwrite in a file by the given the old file
string

File Operation:
 Open a file
 Reading a file
 Writing a file
 Closing a file

1. Open ( ) function:

 Pythons built in open function to get a file object.


 The open function opens a file.
 It returns a something called a file object.
 File objects can turn methods and attributes that can be used to collect
Syntax:
file_object=open(“file_name” , ”mode”)
Example:
fp=open(“a.txt”,”r”)
Create a text file
fp=open (“text.txt”,”w”)
2. Read ( ) function

Read functions contains different methods


 read() – return one big string
 readline() – return one line at a time
 readlines() – return a list of lines
Syntax:
file_name.read ()
Example:
fp=open(“a.txt”,”w
”)
print(fp.read())
print(fp.read(6))
print
(fp.readline())
print
(fp.readline(3))
print
(fp.readlines())
a.txt

A file stores related data, information,


settings or commands in secondary
storage device like magnetic disk,
magnetic tape, optical disk, flash
memory.
h
Output

Reading file using looping:


 Reading a line one by one in given file
fp=open(“a.txt”,”r”)
for line in fp:
print(line)
3. Write ( ) function
This method is used to add information or content to existing file.
Syntax:
file_name.write( )
Example:
fp=open(“a.txt”,”w”)
fp.write(“this file is
a.txt”) fp.write(“to add
more lines”) fp.close()
Output: a.txt

A file stores related data, information, settings


or commands in secondary storage device like
magnetic disk, magnetic tape, optical disk,
flash memory.
this file is a.txt to add more
lines
4. Close ( ) function

It is used to close the file.


Syntax:
File name.close()

Example: 1
fp=open(“a.txt”,”w”)
fp.write(“this file is
a.txt”) fp.write(“to add
more lines”) fp.close()

Example: 2
Splitting line in a text line:
fp=open(“a.txt”,”w) for
line in fp:
words=line.split( )
print(words)

Example:3
Python program to implement File handling operations – create, open, read and write a text
file
f=open('stud.txt','w')
str=input('Enter the file contents:')
f.write(str)
f=open('stud.txt','r')
str=f.read()
print('The file contents are:',str)
f=open('stud.txt','a')
str=input('new the file contents to append:')
f.write(str)
print("file content appended")
f.close()

OUTPUT:

Enter the file contents: cat mango hello cat cat


Stud.txt file created

SCREENSHOTS:

Stud.txt file
The file contents are: cat mango hello cat cat

new the file contents to append


there are five cats

file content appended

Example:4

Python program to perform copy operation from one file to another file

import shutil
print("Give file name that already exists")
sfile = input("Enter Source File's Name: ")
tfile = input("Enter Target File's Name: ")
shutil.copyfile(sfile, tfile)
print("File successfully copied")
OUTPUT:
Give file name that already exists
Enter Source File's Name: stud.txt
Enter Target File's Name: s1.txt
File successfully copied

Sourcefile – stud.txt
Targetfile – s1.txt
File Operations and Methods :
5.2. 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.

print("formatted string" % (variables list)

 The first operand is the format string, which specifies 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 ):

Format Conversion Rule

Format character Description


%c Character
%s String formatting
%d Decimal integer
%f Floating point real number

Example 1:
x=10
print('value =% i', %x)
Output will be:
Value = 10

Example 2:
name= 'Manivel'

print('Hai %s'% name)

Output will be:

name= 'Hai Manivel'

Example 3:

num=123.456123

print('The value is:%f %num)

Output will be:

The value is 123.456123

Example 4:

num =123.456123

print('The value is:%0.2f' %num)

Output will be:

The value is 123.45

5.3. COMMAND LINE ARGUMENTS

 The command line argument is used to pass input from the command line to your program
when they are started to execute.
 Handling command line arguments with Python need sys module.
 sys module provides information about constants, functions and methods of the pyhton
interpreter.

argv[ ] is used to access the command line argument. The argument list starts from 0.
argv[ ] the first argument always the file name
sys.argv[0]= gives file name
sys.argv[1]=provides access to the first input

Example 1 output
import sys python demo.py
print( the file name is %s %(sys.argv[0])) the file name is demo.py

addition of two num output


import sys sam@sam~$ python sum.py 2 3
a= sys.argv[1] sum is 5
b= sys.argv[2]
sum=int(a)+int(b)
print("sum is",sum)

Word count using comment line arg: Output


from sys import argv C:\Python34>python word.py
a = argv[1].split() "python is awesome lets program in
dict = {} python"
for i in a: {'lets': 1, 'awesome': 1, 'in': 1, 'python': 2,
if i in dict: 'program': 1, 'is': 1}
dict[i]=dict[i]+1 7
else:
dict[i] = 1
print(dict)
print(len(a))

To run a Python program, we execute the following command in the command prompt terminal of the
operating system.

For example, in windows, the following command is entered in Windows command prompt terminal.

$ python script.py arg1 arg2 arg3

Here Python script name is script.py and rest of the three arguments - arg1 arg2 arg3 are command
line arguments for the program.

If the program needs to accept input from the user, Python's input() function is used. When the
program is executed from command line, user input is accepted from the command terminal.

The program is run from the command prompt terminal as follows −


Passing Arguments at the Time of Execution
We also can to give the input data to be used by the program in the command line itself and use it
inside the program. An example of giving the data in the command line could be any DOS commands in
Windows or Linux.
In Windows, you use the following DOS command to rename a file hello.py to hi.py.
C:\Python311>ren hello.py hi.py
In Linux you may use the mv command −
$ mv hello.py hi.py
Here ren or mv are the commands which need the old and new file names. Since they are put in line with the
command, they are called command-line arguments.
You can pass values to a Python program from command line. Python collects the arguments in a list object.
Python's sys module provides access to any command- line arguments via the sys.argv variable. sys.argv is
the list of command-line arguments and sys.argv[0] is the program i.e. the script name.
Example
The hello.py script used input() function to accept user input after the script is run. Let us change it to accept
input from command line.

Run the program from command-line as shown in the following figure −

The output is shown below −


C:\Python311>python hello.py Rajan
argument list ['hello.py', 'Rajan']
Hello Rajan. How are you?
The command-line arguments are always stored in string variables. To use them as numerics, you can them
suitably with type conversion functions.
Example:
python program to word count in a file using command line argument
import sys file-open(sys.argv[1],”r+”)
wordcount={}
for word in file.read().split():
if word not in wordcount:
wordcount[word]=1
else:
wordcount[word]+=1
print(word,wordcount)
file.close()
OUTPUT:
C:\user\admin>cd desktop
C:\user\admin\Desktop>py command.py sys.txt
command('the':1, 'tale': 1,'of':1, 'naruto':1}

5.4. ERRORS AND EXCEPTION HANDLING

Errors
 Error is a mistake in python also referred as bugs .they are almost always
the fault of the programmer.
 The process of finding and eliminating errors is called debugging
Types of errors
o Syntax error or compile time error
o Run time error
o Logical error
Syntax errors
 Syntax errors are the errors which are displayed when the programmer do
mistakes when writing a program, when a program has syntax errors it
will not get executed
 Leaving out a keyword
 Leaving out a symbol, such as colon, comma, brackets
 Misspelling a keyword
 Incorrect indentation
Runtime errors
 If a program is syntactically correct-that is ,free of syntax errors-it will
be run by the python interpreter
 However, the program may exit unexpectedly during execution if it
encounters a runtime error.
 When a program has runtime error it will get executed but it will not produce output
 Division by zero
 Performing an operation on incompatible types
 Using an identifier which has not been defined
 Trying to access a file which doesn’t exit
Logical errors
 Logical errors are the most difficult to fix
 They occur when the program runs without crashing but produces incorrect result
 Using the wrong variable name
 Indenting a blocks to the wrong level
 Using integer division instead of floating point division
 Getting operator precedence wrong
Exception handling

Exceptions
 An exception is an error that happens during execution of a program. When
that Error occurs
Errors in python
S.No. Exception Name Description
1 FloatingPointError Raised when a floating point calculation fails.
ZeroDivisionError Raised when division or modulo by zero takes place for
2
all numeric types.

Exception Handling Mechanism

 Exception handling is done by try and catch block.


 Suspicious code that may raise an exception, this kind of code will be placed in try
block.
 A block of code which handles the problem is placed in except block.

1. try –except
2. try –multiple except
3. try –except-else
4. raise exception
5. try –except-finally

1. Try –Except Statements


 The try and except statements are used to handle runtime errors
Syntax:
try:
statements
except:
statements

The try statement works as follows: -


 First, the try clause (the statement(s) between the try and except keywords) is
executed.
 If no exception occurs, the except c l a u s e is skipped and execution
of the try statement is finished.
 If an exception occurs during execution of the try clause, the rest of the clause is
skipped. Then if its type matches the exception named after the except
keyword, the except clause is executed, and then execution continues after the
try statement.

Example:
try:
result = X / ( X – Y )
print(“result=”.result)
except ZeroDivisionError:
print(“Division by Zero”)

Output:1 Output : 2
Enter the value of X = 10 Enter the value of X = 10
Enter the value of Y = 5 Enter the value of Y = 10
Result = 2 Division by Zero

2. Try – Multiple except Statements


o Exception type must be different for except statements
Syntax:
try:
statements
except errors1:
statements
except errors2:
statements
except errors3:
statements

Example
X=int(input(“Enter the value of X”))
Y=int(input(“Enter the value of y”))
try:
sum = X +
Y divide =
X/Y
print (“ Sum of %d and %d = %d”, %(X,Y,sum))
print (“ Division of %d and %d = %d”, %(X,Y,divide))
except NameError:
print(“ The input must be number”)
except ZeroDivisionError:
print(“Division by Zero”)

Output:1 Output 2: Output 3:


Enter the value of X = 10 Enter the value of X = 10 Enter the value of X = 10
Enter the value of Y = 5 Enter the value of Y = 0 Enter the value of Y = a
Sum of 10 and 5 = 15 Sum of 10 and 0 = 10 The input must be number
Division of 10 and 5 = 2 Division by Zero

3. Try –Except-Else
o The else part will be executed only if the try block does not raise the exception.

o Python will try to process all the statements inside try block. If value
error occur, the flow of control will immediately pass to the except
block and remaining statements in try block will be skipped.
Syntax:
try:
statements
except:
statements
else:
statements

Example
X=int(input(“Enter the value
of X”)) Y=int(input(“Enter the
value of Y”)) try:
result = X / ( X – Y )
except ZeroDivisionError:
print(“Division by Zero”)
else:
print(“result=”.result)

Output:1 Output : 2
Enter the value of X = 10 Enter the value of X = 10
Enter the value of Y = 5 Enter the value of Y = 10
Result = 2 Division by Zero

4. Raise statement
 The raise statement allows the programmer to force a specified exception to occur.
Example:
>>> raise
NameError('HiThere')
Output:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: HiThere
 If you need to determine whether an exception was raised but don’t intend
to handle it, a simpler form of the raise statement allows you to re-raise
the exception:
Example
try:
... raise NameError('HiThere')
... except NameError:
... print('An exception flew by!')
...
raise
Outp
ut:
An exception flew by!
Traceback (most recent call
last):
File "<stdin>", line 2, in
<module> NameError: HiThere

5. Try –Except-Finally

 A finally clause is always executed before leaving the try statement,


whether an exception has occurred or not.
 The finally clause is also executed “on the way out” when any other clause of the
try statement is left via a break, continue or return statement.

Syntax

try:
statements
except:
statements
finally:
statements
Example:

X=int(input(“Enter the value of X”))


Y=int(input(“Enter the value of Y”))
try:
result = X / ( X – Y )
except Zero DivisionError:
print(“Division by Zero”)
else:
print(“result=”.result)
finally:
print (“executing finally clause”)
Output:1 Output : 2
Enter the value of X = 10 Enter the value of X = 10
Enter the value of Y = 5 Enter the value of Y = 10
Result = 2 Division by Zero
executing finally clause executing finally clause

Built-in Exceptions

 An exception(runtime time error)is an error, which occurs during the execution of a


program that disrupts the normal flow of the program's instructions.
 When a Python script raises an exception, it must either handle the exception
immediately otherwise it terminates or quit.

S.No. Exception Name Description


1 FloatingPointError Raised when a floating point calculation fails.
ZeroDivisionError Raised when division or modulo by zero takes place for
2
all numeric types.
AttributeError Raised in case of failure of attribute reference or
3
assignment.

4 ImportError Raised when an import statement fails.

KeyboardInterrupt Raised when the user interrupts program execution,


5
usually by pressing Ctrl+c.

6 IndexError Raised when an index is not found in a sequence

KeyError Raised when the specified key is not found in the


7
dictionary.

NameError Raised when an identifier is not found in the local or


8
global namespace

Raised when an input/ output operation fails, such as the


IOError
9 print statement or the open() function when trying to
open a file that does not exist.

10 SyntaxError Raised when there is an error in Python syntax.

11 IndentationError Raised when indentation is not specified properly.

Raised when the interpreter finds an internal problem,


SystemError
12 but when this error is encountered the Python
interpreter does not exit.

Raised when Python interpreter is quit by using the


SystemExit
13 sys.exit() function. If not handled in the code, causes the
interpreter to exit.

TypeError Raised when an operation or function is attempted that


14
is invalid for the specified data type.

Raised when the built-in function for a data type has the
ValueError
15 valid type of arguments, but the arguments have invalid
values specified.

RuntimeError Raised when a generated error does not fall into any
16
category.

5.5. MODULES IN PYTHON


 A python module is a file that consists of python definition and statements.
A module can define functions, classes and variables.
 It allows us to logically arrange related code and makes the code easier to
understand and use.
1.Import statement:
 An import statement is used to import python module in some python source file.
Syntax: import module1 [, module2 […module]]
Example:
>>>import math
>>>print (math.pi)
3.14159265

2.Import with renaming:


The import a module by renaming it as follows,
>>>import math as a
>>>print(“The value of pi is “,a.pi)
The value of pi is 3.14159265
Writing modules:
 Any python source code file can be imported as a module into another
python source file. For example, consider the following code named as
support.py, which is python source file defining two function add(),
display().
Support.py:
def add(a,b):
print(“The result is “,a+b)
return
def display(p):
print(“welcome “,p)
return
The support.py file can be imported as a module into another python source
file and its functions can be called from the new files as shown in the following
code:
3. Import file name

import support #import module support


support.add(3,4) #calling add() of support module with two integers
support.add (3.5,4.7) #calling add() of support module with two real values
support.add (‘a’,’b’) #calling add() of support module with two character
values support.add (“yona”,”alex”)#calling add() of support module with two
string values support.display (‘fleming’) #calling display() of support module
with a string value

Output:
The result is 7
The result is
8.2 The result
is ab
The result is
yonaalex Welcome,
fleming

4. from……import statement:

 It allows us to import specific attributes from a module into the


current namespace.
Syntax: from modulename import name1 [, name2[,……nameN]]
from support import add #import module support
support.add(3,4) #calling add() of support module with two integers
support.add(3.5,4.7) #calling add() of support module with two real
values support.add(‘a’,’b’) #calling add() of support module with two character
values support.add (“yona”,”alex”)#calling add() of support module with two
string values support.display (‘fleming’) #calling display() of support module
with a string value
Output:
The result is 7
The result is
8.2 The result
is ab
The result is
yonaalex Welcome,
fleming

5.OS Module

 The OS module in python provide function for interacting with operating


system
 To access the OS module have to import the OS module in our program

import os

Method example description


Name Osname ‘nt’ This function gives the
name of the operating
system
getcwd() Os,getcwd() Return the current working
,C;\\Python34’ directory(CWD)of the file
used to execute the code
mkdir(folder) Os.mkdir(“python”) Create a directory(folder)
with the given name
rename(oldname,newname) Os.rename(“python”,”pspp”) Rename the directory or
folder
remove(“folder”) Os.remove(“pspp”) Remove (delete)the
directory or folder
getuid() Os.getuid() Return the current process’s
user id
Environ Os.nviron Get the users environment

6. Sys Module

 Sys module provides information about constant, function and methods


 It provides access to some variables used or maintained by the interpreter

import sys
Methods example description
sys.argv sys.argv Provides the list of
command line arguments
passed to a python script
sys.argv(0) Provides to access the
file name
sys.argv(1) Provides to access the first
input
sys.path sys.path It provide the search path
for module
sys.path.append() sys.path.append() Provide the access to
specific path to our
program
sys.platform sys.platform Provide information
‘win32’ about the operating
system
platform
sys.exit sys.exit Exit from python
<built.in function exit>

Steps to Create the Own Module


 Here we are going to create a calc module ; our module contains four functions

i.e add(),sub(),mul(),div()

Program for calculator module output


Module import calculator
name ;calc.py def calculator.add(2,3)
add(a,b); print(a+b)
def sub(a,b);
print(a-b)
def Outcome
mul(a,b); >>>5
print(a*b)
def
div(a,b);
print(a/b)

5.6. PACKAGES IN PYTHON


 A package is a collection of python module. Module is a single python file containing
function definitions
 A package is a directory(folder)of python module containing an additional init py
file, to differentiate a package from a directory
 Packages can be nested to any depth, provided that the corresponding directories
contain their own init py file.
 init py file is a directory indicates to the python interpreter that the directory
should be treated like a python package init py is used to initialize the python
package

USER DEFINED PACKAGE


Steps to Create a Package

Step1: create the package directory

• Create the directory (folder)and give it your packages name


• Here the package name is calculator

Name Data modified Type


1. pycache 05-12-2017 File folder
2. calculator 08-12-2017 File folder
3. DLLs 10-12-2017 File folder
Step2: write module for calculator directory add save the module in calculator directory
 Here four module have create for calculator directory
Local Disk (C)>Python34>Calculator

Name Data modified Type Size


1. add 08-12-2017 File folder 1KB
2. div 08-12-2017 File folder 1KB
3. mul 08-12-2017 File folder 1KB
4. sub 08-12-2017 File folder 1KB

add.py div.py mul.py sub.py


def add(a,b); def div(a,b); def mul(a,b); def sub(a,b);
print(a+b) print(a/b) print(a*b) print(a-b)

Step3: add the init.py file in the calculator directory


 A directory must contain the file named init.py in order for python to consider it
as a package

Add the following code in the init .py file

from * add import


add from * sub import
sub from * mul
import mul from * div
import div

Local Disk (C):/Python34>Calculator

Name Data modified Type Size


1. init 08-12-2017 File folder 1KB
2. add 08-12-2017 File folder 1KB
3. div 08-12-2017 File folder 1KB
4. mul 08-12-2017 File folder 1KB
5. sub 08-12-2017 File folder 1KB

Step4: To test your package


 Import calculator package in your program and add the path of your
package in your program by using sys.path.append()
Example
import calculator
import sys
sys.path.append(“C:/Python34”)
print ( calculator.add(10,5))
print ( calculator.sub(10,5))

Output :
>>> 15
5
50
2

Built-in Package Example:

NumPy

NumPy stands for Numerical Python, is an open-source Python library that provides
support for large, multi-dimensional arrays and matrices. NumPy is the fundamental package for
scientific computing in Python. It also have a collection of high-level mathematical functions to
operate on arrays. It was created by Travis Oliphant in 2005.

What is NumPy?
 NumPy is a general-purpose array-processing package.
 It provides a high-performance multidimensional array object and tools for working with
these arrays.
 It is the fundamental package for scientific computing with Python. It is open-source
software.

Features of NumPy

NumPy has various features which make them popular over lists.

Some of these important features include:

 A powerful N-dimensional array object

 Sophisticated (broadcasting) functions

 Tools for integrating C/C++ and Fortran code

 Useful linear algebra, Fourier transform, and random number capabilities

NumPy in Python can also be used as an efficient multi-dimensional container of generic


data. Arbitrary data types can be defined using Numpy which allows NumPy to seamlessly and
speedily integrate with a wide variety of databases.

Install Python NumPy

Numpy can be installed for Mac and Linux users via the following pip command:

pip install numpy

Arrays in NumPy

NumPy’s main object is the homogeneous multidimensional array.

 It is a table of elements (usually numbers), all of the same type, indexed by a tuple of positive
integers.

 In NumPy, dimensions are called axes. The number of axes is rank.

 NumPy’s array class is called ndarray. It is also known by the alias array.

Simple Example :

import numpy as np
# Creating array object
arr = np.array( [[ 1, 2, 3],[ 4, 2, 5]] )
# Printing type of arr object
print("Array is of type: ", type(arr))
# Printing array dimensions (axes)
print("No. of dimensions: ", arr.ndim)

# Printing shape of array


print("Shape of array: ", arr.shape)

# Printing size (total number of elements) of array


print("Size of array: ", arr.size)

# Printing type of elements in array


print("Array stores elements of type: ", arr.dtype)

OUTPUT:

Array is of type: <class 'numpy.ndarray'>


No. of dimensions: 2
Shape of array: (2, 3)
Siz e of array: 6
Array stores elements of type: int64
TWO MARKS QUESTION AND ANSWERS
1. Define a file

Files are collection of data. It is stored in computer memory and can be taken
any time we require it. Each file is identified by a unique name. In general a text
file is a file that contains printable characters and whitespace, organized into
lines separated by newline characters.
Eg: file.txt
2. List the two methods used for installing python pacakage.

There are two standard methods for installing a package.


pip install

The pip install script is available within our scientific Python installation.
python setup.py install

3. What python package refers to?


A Python package refers to a directory of Python module.
To import a package :
import mypackage.mymodule
4. How do we import the packages in python? Give and example.

We can then import the package by:


import mypackage.mymodule
or
from mypackage.mymodule import myclass
5. What is the use of dot(.) operator?

Variables defined inside a module are called attributes of the module. Attributes
are accessed using the dot operator (.)
6. Define namespaces in python.

A namespace is a collection of identifiers that belong to a module, or to a function.


Each module has its own name space.
7. Write a program to generate a numbers using random module.

import random
rng = random.Random()
dice_throw = rng.randrange(1,7)
8. What is called exception?

Exception is an event , which occurs during the execution of program and distrupts
the normal flow of programs instructions.
9. What are the two ways to handle the exceptions.

The two ways to handle exception is:


try.....catch
try...finally
10. What is syntax error ? Give an example.

This is an error, Raised when there is an error in Python syntax.


Example:

if a<5
File “<interactive input>”, line 1
if a < 5
^
SyntaxError: invalid syntax
11. Describe about the command line arguments.

The sys.argv is a list in Python, which contains the command-line arguments


passed to the script. With the len(sys.argv) function you can count the number of
arguments.
12. Discover the format operator available in files.

A format sequence can appear anywhere in the string,so we can embed a value
in a sentence: print(‘In %d years I have spotted %g %s.’ % (3, 0.1, ‘camels’))
‘{} {}’.format(1,2)
12
13. Write a program to write a data in a file.

Eg:
f = open(“pec.dat”,”w”)
f.write(“Welcome to PEC”)
f.close()
Eg:
Text=f.read()
Print text
TWO MARKS QUESTION AND ANSWERS

1. Why do we go for file?


File can a persistent object in a computer. When an object or state is created and needs
to be persistent, it is saved in a non-volatile storage location, like a hard drive.

2. What are the three different mode of operations of a file?


The three mode of operations of a file are,
i. Open – to open a file to perform file operations
ii. Read – to open a file in read mode
iii. Write – to open a file in write mode

3. State difference between read and write in file operations.

Read Write
A "Read" operation occurs when a A "Write" operation occurs when a
computer program reads information computer program adds new information, or
from a computer file/table (e.g. to be changes existing information in a computer
displayed on a screen). file/table.
The "read" operation
gets information out of
a file.
After a "read", the information from the After a "write", the information from the
file/table is available to the computer file/table is available to the computer
program but none of the information that program but the information that was read
was read from the file/table is changed in from the file/table can be changed in any
any way. way.

4. Differentiate error and exception. Errors

 Error is a mistake in python also referred as bugs . they are almost always the
fault of the programmer.
 The process of finding and eliminating errors is called debugging
 Types of errors
 Syntax error or compile time error
 Run time error
 Logical error
Exceptions
An exception is an error that happens during execution of a program. When that Error occurs

5. Give the methods of exception handling.


 try –except
 try –multiple except
 try –except-else
 raise exception
 try –except-finally
6. State the syntax for try…except block
The try and except statements are used to handle runtime errors

Syntax:
try :
statements
except :
statements

7. Write a program to add some content to existing file without effecting the existing content.
file=open(“newfile.txt”,a)
file.write(“hello”)

newfile.txt newfile.txt(after updating)


Hello!!World!!! Hello!!!World!!!hello 8. What is
package?
 A package is a collection of python module. Module is a single python file containing function
definitions
 A package is a directory(folder)of python module containing an additional init py file, to differentiate a
package from a directory
 Packages can be nested to anydepth, provided that the corresponding directories contain their own init
py file

9. What is module?
A python module is a file that consists of python definition and statements. A module can define
functions, classes and variables. It allows us to logically arrange related code and makes the code easier to
understand and use

10. Write the snippet to find the current working directory.


Import os
Print(os.getcwd)

Output:
C:\\Users\\Mano\\Desktop

11. Give the use of 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'
The result is the string '42', which is not to be confused with the integer value 42.

12. Write the snippet to find the absolute path of a file.

Import os
os.path.abspath('w rite.py')
Output:
'C:\\Users\\Mano\\Desktop\\write.py'

13. What is the use of os.path.isdir() function.


os.path.isdir() is a function defined in the package os. The main function of isdir(“some input”)
function is to check whether the passed parameter is directory or not. isdir() function will only
return only true or false.

14. What is the use of os.path.isfile() function.


os.path.isfile () is a function defined in the package os. The main function of isfile (“some input”)
function is to check whether the passed parameter is file or not. isfile () function will only return
only true or false.

15. What is command line argument?


sys.argv is the list of command line arguments passed to the Python program.
Argv represents all the items that come along via the command line input, it's basically an array
holding the command line arguments of an array holding the command line arguments of our
program.

16. What is Numpy ?

NumPy is the fundamental package for scientific computing in Python. NumPy is a general-purpose
array-processing package. It provides a high-performance multidimensional array object and tools for
working with these arrays. It is the fundamental package for scientific computing with Python. It is
open-source software.

You might also like