0% found this document useful (0 votes)
23 views131 pages

Python Full Material

Uploaded by

SATHISHKUMAR
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
23 views131 pages

Python Full Material

Uploaded by

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

UNIT I

What is an Algorithm?
An algorithm is a finite line of code developed to be executed in the defined
sequence to solve problems and produce the desired outcomes. An algorithm is
generally written in a common language (pseudo-code) and then implemented in
any programming language. It is recommended to write the pseudo-code of the
algorithm on paper and test using some test cases before the implementation.

BUILDING BLOCKS OF ALGORITHMS (statements, state, control flow,


functions)
Algorithms can be constructed from basic building blocks namely, sequence,
selection and iteration.
Statements:
Statement is a single action in a computer.
In a computer statements might include some of the following actions
 Input data-information given to the program
 Process data-perform operation on a given input
 Output data-processed result
State:
Transition from one process to another process under specified condition
with in a time is called state.
Control flow:
The process of executing the individual statements in a given order is called
control flow
The control can be executed in three ways
 sequence
 selection
 iteration
Sequence:
All the instructions are executed one after another is called sequence
execution.
Example:
Add two numbers:
Step 1: Start
Step 2: get a,b
Step 3: calculate c=a+b
Step 4: Display c
Step 5: Stop
Selection:
A selection statement causes the program control to be transferred to a
specific part of the program based upon the condition.
If the conditional test is true, one part of the program will be executed,
otherwise it will execute the other part of the program.
Example
Write an algorithm to check whether he is eligible to vote?
Step 1: Start
Step 2: Get age
Step 3: if age >= 18 print “Eligible to vote”
Step 4: else print “Not eligible to vote”
Step 6: Stop
Iteration:
In some programs, certain set of statements are executed again and again
based upon conditional test. i.e. executed more than one time. This type of
execution is called looping or iteration.
Example
Write an algorithm to print all natural numbers up to n
Step 1: Start
Step 2: get n value.
Step 3: initialize i=1
Step 4: if (i<=n) go to step 5 else go to step 7
Step 5: Print i value and increment i value by 1
Step 6: go to step 4
Step 7: Stop
Functions:
Function is a sub program which consists of block of code (set of
instructions) that performs a particular task.
For complex problems, the problem is been divided into smaller and
simpler tasks during algorithm design.
Benefits of Using Functions
 Reduction in line of code
 code reuse
 Better readability
 Information hiding
 Easy to debug and test
 Improved maintainability
Example:
Algorithm for addition of two numbers using function
Main function ()
Step 1: Start
Step 2: Call the function add ()
Step 3: Stop
Sub function adds ()
Step 1: Function start
Step 2: Get a, b Values
Step 3: add c=a+b
Step 4: Print c
Step 5: Return

NOTATIONS
Flow chart is defined as graphical representation of the logic for
problem solving.
The purpose of flowchart is making the logic of the program clear in a
visual representation.
Rules for drawing a flowchart
 The flowchart should be clear, neat and easy to follow.
 The flowchart must have a logical start and finish.
 Only one flow line should come out from a process symbol.

 Only one flow line should enter a decision symbol. However, two or three
flow lines may leave the decision symbol.
 Only one flow line is used with a terminal symbol.

 Within standard symbols, write briefly and precisely.


 Intersection of flow lines should be avoided.
Advantages of flowchart:
Communication: - Flowcharts are better way of communicating the logic of
a system to all concerned.
Effective analysis: - With the help of flowchart, problem can be analyzed in
more effective way.
Proper documentation: - Program flowcharts serve as a good program
documentation, which is needed for various purposes
Efficient Coding: - The flowcharts act as a guide or blueprint during the
systems analysis and program development phase.
Proper Debugging: - The flowchart helps in debugging process
Efficient Program Maintenance: - The maintenance of operating program
becomes easy with the help of flowchart. It helps the programmer to put
efforts more efficiently on that part.
Disadvantages of flow chart:
 Complex logic: - Sometimes, the program logic is quite complicated. In that
case, flowchart becomes complex and clumsy.
 Alterations and Modifications: - If alterations are required the flowchart may
require re-drawing completely.
 Reproduction: - As the flowchart symbols cannot be typed, reproduction of
flowchart becomes a problem.
 Cost: For large application the time and cost of flowchart drawing becomes
costly.
PSEUDO CODE:
 Pseudo code consists of short, readable and formally styled English
languages used for explain an algorithm.
 It does not include details like variable declaration, subroutines.
 It is easier to understand for the programmer or non programmer to
understand the general working of the program, because it is not based on
any programming language.
 It gives us the sketch of the program before actual coding.
 It is not a machine readable
 Pseudo code can’t be compiled and executed.
 There is no standard syntax for pseudo code.
Guidelines for writing pseudo code:
 Write one statement per line
 Capitalize initial keyword
 Indent to hierarchy
 End multiline structure
 Keep statements language independent
Common keywords used in pseudo code
The following gives common keywords used in pseudo codes.
 //: This keyword used to represent a comment.
 BEGIN, END: Begin is the first statement and end is the last statement.
 INPUT, GET, and READ: The keyword is used to inputting data
 COMPUTE, CALCULATE: used for calculation of the result of the given
expression. 5. ADD, SUBTRACT, INITIALIZE used for addition,
subtraction and initialization.
 OUTPUT, PRINT, DISPLAY: It is used to display the output of the
program.
 IF, ELSE, ENDIF: used to make decision.
 WHILE, ENDWHILE: used for iterative statements.
 FOR, ENDFOR: Another iterative incremented/decremented tested
automatically.
Syntax for if else:
IF (condition) THEN
statement
...
ELSE
statement
...
ENDIF
Example: Greatest of two numbers
BEGIN
READ a,b
IF (a>b) THEN
DISPLAY a is greater
ELSE
DISPLAY b is greater
END IF
END
Syntax for For:
FOR (start-value to end-value) DO
statement
...
ENDFOR
Example: Print n natural numbers
 BEGIN
 GET n
 INITIALIZE i=1
 FOR (i<=n) DO
 PRINT i
 i=i+1
 ENDFOR
 END
Syntax for While:
WHILE (condition) DO
statement
...
ENDWHILE
Example: Print n natural numbers
BEGIN
GET n
INITIALIZE i=1
WHILE(i<=n) DO
PRINT i
i=i+1
ENDWHILE
END
Advantages:
 Pseudo is independent of any language; it can be used by most programmers.
 It is easy to translate pseudo code into a programming language.
 It can be easily modified as compared to flowchart.
 Converting a pseudo code to programming language is very easy as
compared with converting a flowchart to programming language.
Disadvantages:
 It does not provide visual representation of the program’s logic.
 There are no accepted standards for writing pseudo codes.
 It cannot be compiled nor executed.
 For a beginner, It is more difficult to follow the logic or write pseudo code
as compared to flowchart.
Example:
Addition of two numbers:
BEGIN
GET a,b
ADD c=a+b
PRINT c
END
PROGRAMMING LANGUAGE
A programming language is a set of symbols and rules for instructing a
computer to perform specific tasks. The programmers have to follow all the
specified rules before writing program using programming language. The user has
to communicate with the computer using language which it can understand.
Types of programming language
 Machine language
 Assembly language
 High level language
 Machine language:
The computer can understand only machine language which uses 0’s and 1’s. In
machine language the different instructions are formed by taking different
combinations of 0’s and 1’s.
Advantages:
Translation free:
Machine language is the only language which the computer understands. For
executing any program written in any programming language, the conversion to
machine language is necessary. The program written in machine language can be
executed directly on computer. In this case any conversion process is not required.
High speed
The machine language program is translation free. Since the conversion time
is saved, the execution of machine language program is extremely fast.
Disadvantage:
 It is hard to find errors in a program written in the machine language.
 Writhing program in machine language is a time consuming process.
Machine dependent: According to architecture used, the computer differs from
each other. So machine language differs from computer to computer. So a program
developed for a particular type of computer may not run on other type of computer.
Assembly language:
 To overcome the issues in programming language and make the
programming process easier, an assembly language is developed which is
logically equivalent to machine language but it is easier for people to read,
write and understand.
 Assembly language is symbolic representation of machine language.
Assembly languages are symbolic programming language that uses symbolic
notation to represent machine language instructions. They are called low
level language because they are so closely related to the machines.
Assembler
 Assembler is the program which translates assembly language instruction in
to a machine language.
 Easy to understand and use.
 It is easy to locate and correct errors.
Disadvantage
Machine dependent
The assembly language program which can be executed on the machine
depends on the architecture of that computer.
Hard to learn
It is machine dependent, so the programmer should have the hardware
knowledge to create applications using assembly language.
Less efficient
Execution time of assembly language program is more than machine
language program.
Because assembler is needed to convert from assembly language to machine
language
High level language
 High level language contains English words and symbols. The
specified rules are to be followed while writing program in high level
language. The interpreter or compilers are used for converting these
programs in to machine readable form.
 Translating high level language to machine language
 The programs that translate high level language in to machine
language are called interpreter or compiler.
Compiler:
A compiler is a program which translates the source code written in a high
level language in to object code which is in machine language program. Compiler
reads the whole program written in high level language and translates it to machine
language. If any error is found it display error message on the screen.
Interpreter
Interpreter translates the high level language program in line by line manner.
The interpreter translates a high level language statement in a source program to a
machine code and executes it immediately before translating the next statement.
When an error is found the execution of the program is halted and error message is
displayed on the screen.
Advantages
 Readability : High level language is closer to natural language so they are
easier to learn and understand
 Machine independent: High level language program have the advantage of
being portable between machines.
 Easy debugging : Easy to find and correct error in high level language
Disadvantages
Less efficient: The translation process increases the execution time of the
program. Programs in high level language require more memory and take
more execution time to execute.
They are divided into following categories:
 Interpreted programming languages
 Functional programming languages
 Compiled programming languages
 Procedural programming languages
 Scripting programming language
 Markup programming language
 Concurrent programming language
 Object oriented programming language
 Interpreted programming languages:
An interpreted language is a programming language for which most of its
implementation executes instructions directly, without previously compiling a
program into machine language instructions. The interpreter executes the program
directly translating each statement into a sequence of one or more subroutines
already compiled into machine code.
Examples:
 Pascal
 Python
Functional programming language:
Functional programming language defines every computation as a
mathematical evaluation. They focus on the programming languages are bound to
mathematical calculations
Examples:
 Clean
 Haskell
Compiled Programming language:
o A compiled programming is a programming language whose
implementation is typically compilers and not interpreters.
o It will produce a machine code from source code.
Examples:
 C
 C++
 C#
 JAVA
Procedural programming language:
 Procedural (imperative) programming implies specifying the steps that the
programs should take to reach to an intended state
 A procedure is a group of statements that can be referred through a
procedure call. Procedures help in the reuse of code. Procedural
programming makes the programs structured and easily traceable for
program flow.
Examples:
 Hyper talk
 MATLAB
Scripting language:
Scripting language are programming languages that control an application.
Scripts can execute independent of any other application. They are mostly
embedded in the application that they control and are used to automate frequently
executed tasks like communicating with external program.
Examples:
 Apple script
 VB script
Markup languages:
A markup language is an artificial language that uses annotations to text that
define hoe the text is to be displayed.
Examples:
 HTML
 XML
Concurrent programming language
Concurrent programming is a computer programming technique that
provides for the execution of operation concurrently, either with in a single
computer or across a number of systems.
Examples:
 Joule
 Limbo
Object oriented programming language:
Object oriented programming is a programming paradigm based on the
concept of objects which may contain data in the form of procedures often known
as methods.
Examples:
 Lava
 Moto

ALGORITHMIC PROBLEM SOLVING:


Algorithmic problem solving is solving problem that require the formulation
of an algorithm for the solution.
Understanding the Problem
 It is the process of finding the input of the problem that the algorithm solves.
 It is very important to specify exactly the set of inputs the algorithm needs to
handle.
 A correct algorithm is not one that works most of the time, but one that
works correctly for all legitimate inputs
Ascertaining the Capabilities of the Computational Device
 If the instructions are executed one after another, it is called sequential
algorithm.
 If the instructions are executed concurrently, it is called parallel algorithm.
 Choosing between Exact and Approximate Problem Solving
 The next principal decision is to choose between solving the problem exactly
or solving it approximately
 Based on this, the algorithms are classified as exact algorithm and
approximation algorithm.
Deciding a data structure:
 Data structure plays a vital role in designing and analysis the algorithms.
 Some of the algorithm design techniques also depend on the structuring data
specifying a problem’s instance
Algorithm+ Data structure=programs.
Algorithm Design Techniques
 An algorithm design technique (or “strategy” or “paradigm”) is a general
approach to solving problems algorithmically that is applicable to a variety
of problems from different areas of computing
 Learning these techniques is of utmost importance for the following reasons.
 First, they provide guidance for designing algorithms for new problems,
 Second, algorithms are the cornerstone of computer science
Methods of Specifying an Algorithm
 Pseudo code is a mixture of a natural language and programming language-
like constructs. Pseudo code is usually more precise than natural language,
and its usage often yields more succinct algorithm descriptions.
 In the earlier days of computing, the dominant vehicle for specifying
algorithms was a flowchart, a method of expressing an algorithm by a
collection of connected geometric shapes containing descriptions of the
algorithm’s steps Programming language can be fed into an electronic
computer directly. Instead, it needs to be converted into a computer program
written in a particular computer language. We can look at such a program as
yet another way of specifying the algorithm, although it is preferable to
consider it as the algorithm’s implementation.
Proving an Algorithm’s Correctness
 Once an algorithm has been specified, you have to prove its correctness.
That is, you have to prove that the algorithm yields a required result for
every legitimate input in a finite amount of time.
 A common technique for proving correctness is to use mathematical
induction because an algorithm’s iterations provide a natural sequence of
steps needed for such proofs.
 It might be worth mentioning that although tracing the algorithm’s
performance for a few specific inputs can be a very worthwhile activity, it
cannot prove the algorithm’s correctness conclusively.
1. Efficiency.
 Time efficiency, indicating how fast the algorithm runs,
 Space efficiency, indicating how much extra memory it uses.
2. Simplicity.
 An algorithm should be precisely defined and investigated with
mathematical expressions.
 Simpler algorithms are easier to understand and easier to program.
 Simple algorithms usually contain fewer bugs.
Coding an Algorithm
 Most algorithms are destined to be ultimately implemented as computer
programs. Programming an algorithm presents both a peril and an
opportunity
 A working program provides an additional opportunity in allowing an
empirical analysis of the underlying algorithm. Such an analysis is based on
timing the program on several inputs and then analyzing the results obtained.
SIMPLE STRATEGIES FOR DEVELOPING ALGORITHMS:
 iteration
 Recursions
1. Iterations:
A sequence of statements is executed until a specified condition is true is called
iterations.
 for loop
 While loop
Syntax for For:
FOR (start-value to end-value) DO
Statement
...
ENDFOR
Example: Print n natural numbers
BEGIN
GET n
INITIALIZE i=1
FOR (i<=n) DO
PRINT i
i=i+1
ENDFOR
END
Syntax for While:
WHILE (condition) DO
Statement
...
ENDWHILE
Example: Print n natural numbers
BEGIN
GET n
INITIALIZE i=1
WHILE(i<=n) DO
PRINT i
i=i+1
ENDWHILE
END
Recursions:
 A function that calls itself is known as recursion.
 Recursion is a process by which a function calls itself repeatedly until some
specified condition has been satisfied.
Algorithm for factorial of n numbers using recursion:
Main function:
 Step1: Start
 Step2: Get n
 Step3: call factorial (n)
 Step4: print fact
 Step5: Stop
Sub function factorial (n):
 Step1: if(n==1) then fact=1 return fact
 Step2: else fact=n*factorial (n-1) and return fact
Pseudo code for factorial using recursion:
Main function:
BEGIN
GET n
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)
UNIT II
DATA, EXPRESSIONS, STATEMENTS
Python interpreter and interactive mode; values and types: int, float, boolean, string,
and list; variables, expressions, statements, tuple assignment, precedence of operators,
comments; Modules and functions, function definition and use, flow of execution,
parameters and arguments; Illustrative programs: exchange the values of two
variables, circulate the values of n variables, distance between two points.

1. INTRODUCTION TO PYTHON:
Python is a general-purpose interpreted, interactive, object-oriented, and high-
level programming language.
It was created by Guido van Rossum during 1985- 1990.
Python got its name from “Monty Python’s flying circus”. Python was released in the
year 2000.
 Python is interpreted: Python is processed at runtime by the interpreter. You
 do not need to compile your program before executing it.
 Python is Interactive: You can actually sit at a Python prompt and interact with
 the interpreter directly to write your programs.
 Python is Object-Oriented: Python supports Object-Oriented style or technique
of programming that encapsulates code within objects.
 Python is a Beginner's Language: Python is a great language for the beginner-
level programmers and supports the development of a wide range of
applications.

Easy-to-learn:Python is clearly defined and easily readable. The structure of


the program is very simple. It uses few keywords.

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


 Portable: Python can run on a wide variety of hardware platforms and has the
 same interface on all platforms.
 Interpreted: Python is processed at runtime by the interpreter. So, there is no
 need to compile a program before executing it. You can simply run the program.
 Extensible: Programmers can embed python within their C,C++,Java script
 ,ActiveX, etc.
 Free and Open Source: Anyone can freely distribute it, read the source code, and
 edit it.
 High Level Language: When writing programs, programmers concentrate on
 solutions of the current problem, no need to worry about the low level details.
 Scalable: Python provides a better structure and support for large programs
than shell scripting.

  Bit Torrent file sharing


 Google search engine, Youtube
 Intel, Cisco, HP, IBM
  i–Robot
 NASA

1 Unit 2: Data ,expressions, Statements


 Facebook, Drop box

1.3. Python interpreter:


Interpreter: To execute a program in a high-level language by translating it one line at
a time.
Compiler: To translate a program written in a high-level language into a low-level
language all at once, in preparation for later execution.

Compiler Interpreter
Interpreter Takes Single instruction as
Compiler Takes Entire program as input
input
No Intermediate Object Code
Intermediate Object Code is Generated
is Generated
Conditional Control Statements are Conditional Control Statements are
Executes faster Executes slower
Memory Requirement is More(Since Object Memory Requirement is Less
Code is Generated)
Every time higher level program is
Program need not be compiled every time
converted into lower level program
Errors are displayed after entire Errors are displayed for every
program is checked instruction interpreted (if any)
Example : C Compiler Example : PYTHON

1.4 MODES OF PYTHON INTERPRETER:


Python Interpreter is a program that reads and executes Python code. It uses 2 modes
of Execution.
1. Interactive mode
2. Script mode
Interactive mode:
  Interactive Mode, as the name suggests, allows us to interact with OS.
 When we type Python statement, interpreter displays the result(s)
 immediately.
 Advantages:
  Python, in interactive mode, is good enough to learn, experiment or explore.
 Working in interactive mode is convenient for beginners and for testing small
 pieces of code.
 Drawback:
 We cannot save the statements and have to retype all the statements once again to
re-run them.
In interactive mode, you type Python programs and the interpreter displays the result:
>>> 1 + 1
2
The chevron, >>>, is the prompt the interpreter uses to indicate that it is ready for you
to enter code. If you type 1 + 1, the interpreter replies 2.
>>> print ('Hello, World!')
Hello, World!

2 Unit 2: Data ,expressions, Statements


This is an example of a print statement. It displays a result on the screen. In this case,
the result is the words.

Script mode:
 In script mode, we type python program in a file and then use interpreter to
 execute the content of the file.
 Scripts can be saved to disk for future use. Python scripts have the extension
 .py, meaning that the filename ends with .py
 Save the code with filename.py and run the interpreter in script mode to execute
the script.

Interactive mode Script mode


A way of using the Python interpreter by A way of using the Python interpreter to
typing commands and expressions at the read and execute statements in a script.
prompt.
Cant save and edit the code Can save and edit the code
If we want to experiment with the code, If we are very clear about the code, we can
we can use interactive mode. use script mode.
we cannot save the statements for further we can save the statements for further use
use and we have to retype and we no need to retype
all the statements to re-run them. all the statements to re-run them.
We can see the results immediately. We cant see the code immediately.

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.

3 Unit 2: Data ,expressions, Statements


 Auto completion with smart indentation.
 Python shell to display output with syntax highlighting.

2.VALUES AND DATA TYPES

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

2.1Numbers:
  Number data type stores Numerical Values.
  This data type is immutable [i.e. values/items cannot be changed].
 Python supports integers, floating point numbers and complex numbers. They
are defined as,

2.2 Sequence:
  A sequence is an ordered collection of items, indexed by positive integers.
 It is a combination of mutable (value can be changed) and immutable (values
cannot be changed) data types.

4 Unit 2: Data ,expressions, Statements


 There are three types of sequence data type available in Python, they are
1. Strings
2. Lists
3. Tuples

 A String in Python consists of a series or sequence of characters - letters,


 numbers, and special characters.
 Strings are marked by quotes:
 single quotes (' ') Eg, 'This a string in single quotes'
 double quotes (" ") Eg, "'This a string in double quotes'"
 triple quotes(""" """) Eg, This is a paragraph. It is made up of multiple
 lines and sentences."""
  Individual character in a string is accessed using a subscript (index).
 Characters can be accessed using indexing and slicing operations
Strings are immutable i.e. the contents of the string cannot be changed after it is
created.
Indexing:

 Positive indexing helps in accessing the string from the beginning


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

i. Indexing
ii. Slicing
iii. Concatenation
iv. Repetitions
v. Member ship
Creating a string >>> s="good morning" Creating the list with elements of
different data types.
Indexing >>> print(s[2]) Accessing the item in the
o position 0
>>> print(s[6]) Accessing the item in the
O position 2
Slicing( ending >>> print(s[2:]) - Displaying items from 2nd till
position -1) od morning last.

5 Unit 2: Data ,expressions, Statements


Slice operator is >>> print(s[:4]) - Displaying items from 1st
used to extract Good position till 3rd .
part of a data
type
Concatenation >>>print(s+"friends") -Adding and printing the
good morningfriends characters of two strings.

Repetition >>>print(s*2) Creates new strings,


good morninggood concatenating multiple copies of
morning the same string
in, not in >>> s="good morning" Using membership operators to
(membership >>>"m" in s check a particular character is in
operator) True string or not. Returns true if
>>> "a" not in s present.
True

2.2.2 Lists
  List is an ordered sequence of items. Values in the list are called elements / items.
 It can be written as a list of comma-separated items (values) between square
 brackets[ ].
 Items in the lists can be of different data types.

Operations on list:
Indexing
Slicing
Concatenation
Repetitions
Updation, Insertion, Deletion

Creating a list >>>list1=["python", 7.79, 101, Creating the list with


"hello”] elements of different data
>>>list2=["god",6.78,9] types.
Indexing >>>print(list1[0])  Accessing the item in
python the position 0
>>> list1[2]  Accessing the item in
101
the position 2
Slicing( ending >>> print(list1[1:3]) - Displaying items from 1st
position -1) [7.79, 101] till 2nd.
Slice operator is >>>print(list1[1:]) - Displaying items from 1st
used to extract [7.79, 101, 'hello'] position till last.
part of a string, or
some part of a list
Python
Concatenation >>>print( list1+list2) -Adding and printing the
['python', 7.79, 101, 'hello', 'god', items of two lists.

6 Unit 2: Data ,expressions, Statements


6.78, 9]
Repetition >>> list2*3 Creates new strings,
['god', 6.78, 9, 'god', 6.78, 9, 'god', concatenating multiple
6.78, 9] copies of the same string
Updating the list >>> list1[2]=45 Updating the list using index
>>>print( list1) value
[‘python’, 7.79, 45, ‘hello’]
Inserting an >>> list1.insert(2,"program") Inserting an element in 2nd
element >>> print(list1) position
['python', 7.79, 'program', 45,
'hello']
Removing an >>> list1.remove(45) Removing an element by
element >>> print(list1) giving the element directly
['python', 7.79, 'program', 'hello']

2.2.4Tuple:
 A tuple is same as list, except that the set of elements is enclosed in parentheses
 instead of square brackets.
 A tuple is an immutable list. i.e. once a tuple has been created, you can't add
 elements to a tuple or remove elements from the tuple.
  Benefit of Tuple:
 Tuples are faster than lists.
 If the user wants to protect the data from accidental changes, tuple can be used.
 Tuples can be used as keys in dictionaries, while lists can't.

Basic Operations:
Creating a tuple >>>t=("python", 7.79, 101, Creating the tuple with elements
"hello”) of different data types.
Indexing >>>print(t[0])  Accessing the item in the
python position 0
>>> t[2]  Accessing the item in the
101
position 2
Slicing( ending >>>print(t[1:3])  Displaying items from 1st
position -1) (7.79, 101) till 2nd.

Concatenation >>> t+("ram", 67)  Adding tuple elements at


('python', 7.79, 101, 'hello', 'ram', the end of another tuple
67) elements
Repetition >>>print(t*2)  Creates new strings,
('python', 7.79, 101, 'hello', concatenating multiple copies of
'python', 7.79, 101, 'hello') the same string

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

7 Unit 2: Data ,expressions, Statements


>>> t[0]="a"
Trace back (most recent call last):
File "<stdin>", line 1, in <module>
Type Error: 'tuple' object does not support item
assignment
2.3 Mapping
-This data type is unordered and mutable.
-Dictionaries fall under Mappings.
2.3.1Dictionaries:
  Lists are ordered sets of objects, whereas dictionaries are unordered sets.
 Dictionary is created by using curly brackets. i,e. {}
  Dictionaries are accessed via keys and not via their position.
 A dictionary is an associative array (also known as hashes). Any key of the
 dictionary is associated (or mapped) to a value.
 The values of a dictionary can be any Python data type. So dictionaries are
unordered key-value-pairs(The association of a key and a value is called a key-
value pair )
Dictionaries don't support the sequence operation of the sequence data types like
strings, tuples and lists.

Creating a >>> food = {"ham":"yes", "egg" : Creating the dictionary with


dictionary "yes", "rate":450 } elements of different data
>>>print(food) types.
{'rate': 450, 'egg': 'yes', 'ham':
'yes'}
Indexing >>>> print(food["rate"]) Accessing the item with keys.
450
Slicing( ending >>>print(t[1:3]) Displaying items from 1st till
position -1) (7.79, 101) 2nd.

If you try to access a key which doesn't exist, you will get an error message:
>>> words = {"house" : "Haus", "cat":"Katze"}
>>> words["car"]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'car'

Data type Compile time Run time


int a=10 a=int(input(“enter a”))
float a=10.5 a=float(input(“enter a”))
string a=”panimalar” a=input(“enter a string”)
list a=[20,30,40,50] a=list(input(“enter a list”))
tuple a=(20,30,40,50) a=tuple(input(“enter a tuple”))
8 Unit 2: Data ,expressions, Statements
3.Variables,Keywords Expressions, Statements, Comments, Docstring ,Lines And
Indentation, Quotation In Python, Tuple Assignment:

3.1VARIABLES:
 A variable allows us to store a value by assigning it to a name, which can be used
later.
  Named memory locations to store values.
 Programmers generally choose names for their variables that are meaningful.
  It can be of any length. No space is allowed.
 We don't need to declare a variable before using it. In Python, we simply assign a
value to a variable and it will exist.

Assigning value to variable:


Value should be given on the right side of assignment operator(=) and variable on left
side.
>>>counter =45
print(counter)

Assigning a single value to several variables simultaneously:

>>> a=b=c=100
Assigning multiple values to multiple variables:

>>> a,b,c=2,4,"ram"

3.2KEYWORDS:
  Keywords are the reserved words in Python.
We cannot use a keyword as variable name, function name or any other
identifier.
  They are used to define the syntax and structure of the Python language.
  Keywords are case sensitive.















3.3IDENTIFIERS:

Identifier is the name given to entities like class, functions, variables etc. in
Python.

 Identifiers can be a combination of letters in lowercase (a to z) or uppercase (A
to Z) or digits (0 to 9) or an underscore (_).

9 Unit 2: Data ,expressions, Statements
 all are valid example.
  An identifier cannot start with a digit.
 Keywords cannot be used as identifiers.
  Cannot use special symbols like !, @, #, $, % etc. in our identifier.
 Identifier can be of any length.
Example:
Names like myClass, var_1, and this_is_a_long_variable

Valid declarations Invalid declarations


Num Number 1
Num num 1
Num1 addition of program
_NUM 1Num
NUM_temp2 Num.no
IF if
Else else

3.4 STATEMENTS AND EXPRESSIONS:


3.4.1 Statements:
-Instructions that a Python interpreter can executes are called statements.
-A statement is a unit of code like creating a variable or displaying a value.
>>> n = 17
>>> print(n)
Here, The first line is an assignment statement that gives a value to n.
The second line is a print statement that displays the value of n.
3.4.2Expressions:
-An expression is a combination of values, variables, and operators.
- A value all by itself is considered an expression, and also a variable.
- So the following are all legal expressions:
>>> 42
42
>>> a=2
>>> a+3+2
7
>>> z=("hi"+"friend")
>>> print(z)
hifriend

3.5 INPUT AND OUTPUT

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


In python, input () function is available for input.
Syntax for input() is:
variable = input (“data”)

10 Unit 2: Data ,expressions, Statements


Example:
>>> x=input("enter the name:")
enter the name: george
>>>y=int(input("enter the number"))
enter the number 3
#python accepts string as default data type. conversion is required for type.

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


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

3.6 COMMENTS:
 A hash sign (#) is the beginning of a comment.
 Anything written after # in a line is ignored by interpreter.
Eg:percentage = (minute * 100) / 60 # calculating percentage of an hour
 Python does not have multiple-line commenting feature. You have to
comment each line individually as follows :
Example:
# This is a comment.
# This is a comment, too.
# I said that already.

3.7 DOCSTRING:
  Docstring is short for documentation string.
 It is a string that occurs as the first statement in a module, function, class, or
 method definition. We must write what a function/class does in the docstring.
 Triple quotes are used while writing docstrings.
Syntax:
functionname__doc.__
Example:
def double(num):
"""Function to double the value"""
return 2*num
>>> print(double.__doc__)
Function to double the value

3.8 LINES AND INDENTATION:


 Most of the programming languages like C, C++, Java use braces { } to define a
 block of code. But, python uses indentation.
  Blocks of code are denoted by line indentation.
 It is a space given to the block of codes for class and function definitions or flow
control.

11 Unit 2: Data ,expressions, Statements


Example:
a=3
b=1
if a>b:
print("a is greater")
else:
print("b is greater")

3.9 QUOTATION IN PYTHON:


Python accepts single ('), double (") and triple (''' or """) quotes to denote string literals.
Anything that is represented using quotations are considered as string.

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."""

3.10 TUPLE ASSIGNMENT

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


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

Example:
-It is useful to swap the values of two variables. With conventional assignment
statements, we have to use a temporary variable. For example, to swap a and b:

Swap two numbers Output:


a=2;b=3
print(a,b) (2, 3)
temp = a (3, 2)
a=b >>>
b = temp
print(a,b)

12 Unit 2: Data ,expressions, Statements


-Tuple assignment solves this problem neatly:

(a, b) = (b, a)

-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 = ("George", 25, "20000") # tuple packing

-In tuple unpacking, the values in a tuple on the right are ‘unpacked’ into the
variables/names on the right:

>>> b = ("George", 25, "20000") # tuple packing >>>


(name, age, salary) = b # tuple unpacking
>>> name
'George'
>>> age
25
>>> salary
'20000'

-The right side can be any kind of sequence (string,list,tuple)


Example:
-To split an email address in to user name and a domain
>>> mailid='god@abc.org'
>>> name,domain=mailid.split('@')
>>> print name
god
>>> print
(domain) abc.org

4.OPERATORS:
  Operators are the constructs which can manipulate the value of operands.
 Consider the expression 4 + 5 = 9. Here, 4 and 5 are called operands and + is
 called operator
 Types of Operators:
-Python language supports the following types of operators
  Arithmetic Operators
 Comparison (Relational) Operators
  Assignment Operators
  Logical Operators
 Bitwise Operators
  Membership Operators
 Identity Operators
13 Unit 2: Data ,expressions, Statements
4.1 Arithmetic operators:
They are used to perform mathematical operations like addition, subtraction,
multiplication etc. Assume, a=10 and b=5

Operator Description Example

+ Addition Adds values on either side of the operator. a + b = 30

- Subtraction Subtracts right hand operand from left hand a – b = -10


operand.

* Multiplies values on either side of the operator a * b = 200


Multiplication

/ Division Divides left hand operand by right hand operand b/a=2

% Modulus Divides left hand operand by right hand operand b%a=0


and returns remainder

** Exponent Performs exponential (power) calculation on a**b =10 to the


operators power 20

// Floor Division - The division of operands where the 5//2=2


result is the quotient in which the digits after the
decimal point are removed

Examples Output:
a=10 a+b= 15
b=5 a-b= 5
print("a+b=",a+b) a*b= 50
print("a-b=",a-b) a/b= 2.0
print("a*b=",a*b) a%b= 0
print("a/b=",a/b) a//b= 2
print("a%b=",a%b) a**b= 100000
print("a//b=",a//b)
print("a**b=",a**b)

4.2 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 Description Example

== If the values of two operands are equal, then the condition (a == b) is


14 Unit 2: Data ,expressions, Statements
becomes true. not true.

!= If values of two operands are not equal, then condition (a!=b) is


becomes true. true

> If the value of left operand is greater than the value of right (a > b) is
operand, then condition becomes true. not true.

< If the value of left operand is less than the value of right (a < b) is
operand, then condition becomes true. true.

>= If the value of left operand is greater than or equal to the (a >= b) is
value of right operand, then condition becomes true. not true.

<= If the value of left operand is less than or equal to the value (a <= b) is
of right operand, then condition becomes true. true.

Example
a=10 Output:
b=5 a>b=> True
print("a>b=>",a>b) a>b=> False
print("a>b=>",a<b) a==b=> False
print("a==b=>",a==b) a!=b=> True
print("a!=b=>",a!=b) a>=b=> False
print("a>=b=>",a<=b) a>=b=> True
print("a>=b=>",a>=b)

4.3 Assignment Operators:


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

= Assigns values from right side operands to left side c=a+b


operand assigns
value of a +
b into c

+= Add AND It adds right operand to the left operand and assign c += a is
the result to left operand equivalent
to c = c + a

-= Subtract It subtracts right operand from the left operand and c -= a is


AND assign the result to left operand equivalent
to c = c - a

15 Unit 2: Data ,expressions, Statements


*= Multiply It multiplies right operand with the left operand and c *= a is
AND assign the result to left operand equivalent
to c = c * a

/= Divide It divides left operand with the right operand and c /= a is


AND assign the result to left operand equivalent
to c = c / ac
/= a is
equivalent
to c = c / a

%= Modulus It takes modulus using two operands and assign the c %= a is


AND result to left operand equivalent
to c = c % a

**= Exponent Performs exponential (power) calculation on c **= a is


AND operators and assign value to the left operand equivalent
to c = c ** a

//= Floor It performs floor division on operators and assign c //= a is


Division value to the left operand equivalent
to c = c // a

Example Output
a = 21 Line 1 - Value of c is 31
b = 10 Line 2 - Value of c is 52
c=0 Line 3 - Value of c is 1092
c=a+b Line 4 - Value of c is 52.0
print("Line 1 - Value of c is ", c) Line 5 - Value of c is 2
c += a Line 6 - Value of c is 2097152
print("Line 2 - Value of c is ", c) Line 7 - Value of c is 99864
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)

16 Unit 2: Data ,expressions, Statements


4.4 Logical Operators:
-Logical operators are the and, or, not operators.

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

4.5 Bitwise Operators:


 A bitwise operation operates on one or more bit patterns at the level of individual
bits
Example: Let x = 10 (0000 1010 in binary) and
y = 4 (0000 0100 in binary)

Example Output
a = 60 # 60 = 0011 1100 Line 1 - Value of c is 12
b = 13 # 13 = 0000 1101 Line 2 - Value of c is 61
c=0 Line 3 - Value of c is 49
c = a & b; # 12 = 0000 1100 Line 4 - Value of c is -61
print "Line 1 - Value of c is ", c Line 5 - Value of c is 240
c = a | b; # 61 = 0011 1101 Line 6 - Value of c is 15
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
17 Unit 2: Data ,expressions, Statements
print "Line 4 - Value of c is ", c
c = a << 2; # 240 = 1111 0000
print "Line 5 - Value of c is ", c
c = a >> 2; # 15 = 0000 1111
print "Line 6 - Value of c is ", c

4.6 Membership Operators:

 Evaluates to find a value or a variable is in the specified sequence of string, list,


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

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

4.7 Identity Operators:


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

Example
x=5 Output
y=5 False
x2 = 'Hello' True
y2 = 'Hello'
print(x1 is not y1)
print(x2 is y2)
18 Unit 2: Data ,expressions, Statements
5.OPERATOR PRECEDENCE:
When an expression contains more than one operator, the order of evaluation
depends on the order of operations.
Operator Description

** Exponentiation (raise to the power)

~+- Complement, unary plus and minus (method


names for the last two are +@ and -@)

* / % // Multiply, divide, modulo and floor division

+- Addition and subtraction

>> << Right and left bitwise shift

& Bitwise 'AND'

^| Bitwise exclusive `OR' and regular `OR'

<= < > >= Comparison operators

<> == != Equality operators

= %= /= //= -= += *= **= Assignment operators

is is not Identity operators

in not in Membership operators

not or and Logical operators


-For mathematical operators, Python follows mathematical convention.
-The acronym PEMDAS (Parentheses, Exponentiation, Multiplication, Division,
Addition, Subtraction) is a useful way to remember the rules:
 Parentheses have the highest precedence and can be used to force an expression
to evaluate in the order you want. Since expressions in parentheses are evaluated
 first, 2 * (3-1)is 4, and (1+1)**(5-2) is 8.
  You can also use parentheses to make an expression easier to read, as in (minute
* 100) / 60, even if it doesn’t change the result.
 Exponentiation has the next highest precedence, so 1 + 2**3 is 9, not 27, and 2
 *3**2 is 18, not 36.
 Multiplication and Division have higher precedence than Addition and
 Subtraction. So 2*3-1 is 5, not 4, and 6+4/2 is 8, not 5.
 Operators with the same precedence are evaluated from left to right (except
exponentiation).

19 Unit 2: Data ,expressions, Statements


Example:
a=9-12/3+3*2-1 A=2*3+4%5-3/2+6
a=? A=6+4%5-3/2+6 find m=?
a=9-4+3*2-1 A=6+4-3/2+6 m=-43||8&&0||-2
a=9-4+6-1 A=6+4-1+6 m=-43||0||-2
a=5+6-1 A=10-1+6 m=1||-2
a=11-1 A=9+6 m=1
a=10 A=15

a=2,b=12,c=1 a=2*3+4%5-3//2+6
d=a<b>c a=2,b=12,c=1 a=6+4-1+6
d=2<12>1 d=a<b>c-1 a=10-1+6
d=1>1 d=2<12>1-1 a=15
d=0 d=2<12>0
d=1>0
d=1

6.Functions, Function Definition And Use, Function call, Flow Of Execution,


Function Prototypes, Parameters And Arguments, Return statement,
Argumentstypes,Modules

6.1 FUNCTIONS:
 Function is a sub program which consists of set of instructions used to
perform a specific task. A large program is divided into basic building
blocks called function.
Need For Function:
 When the program is too complex and large they are divided into parts. Each part
is separately coded and combined into single program. Each subprogram is called
 as function.
 Debugging, Testing and maintenance becomes easy when the program is divided
 into subprograms.
 Functions are used to avoid rewriting same code again and again in a program.
 Function provides code re-usability
 The length of the program is reduced.
Types of function:
Functions can be classified into two categories:
i) user defined function
ii) Built in function
i) Built in functions
  Built in functions are the functions that are already created and stored in python.
 These built in functions are always available for usage and accessed by a
programmer. It cannot be modified.
Built in function Description
20 Unit 2: Data ,expressions, Statements
>>>max(3,4) # returns largest element
4
>>>min(3,4) # returns smallest element
3
>>>len("hello") #returns length of an object
5
>>>range(2,8,1) #returns range of given values
[2, 3, 4, 5, 6, 7]
>>>round(7.8) #returns rounded integer of the given number
8.0
>>>chr(5) #returns a character (a string) from an integer
\x05'
>>>float(5) #returns float number from string or integer
5.0
>>>int(5.0) # returns integer from string or float
5
>>>pow(3,5) #returns power of given number
243
>>>type( 5.6) #returns data type of object to which it belongs
<type 'float'>
>>>t=tuple([4,6.0,7]) # to create tuple of items from list
(4, 6.0, 7)
>>>print("good morning") # displays the given object
Good morning
>>>input("enter name: ") # reads and returns the given string
enter name : George

ii)User Defined Functions:


 User defined functions are the functions that programmers create for their
 requirement and use.
 These functions can then be combined to form module which can be used in
 other programs by importing them.
  Advantages of user defined functions:
 Programmers working on large project can divide the workload by making
 different functions.
 If repeated code occurs in a program, function can be used to include those
codes and execute when needed by calling that function.
6.2 Function definition: (Sub program)
  def keyword is used to define a function.
 Give the function name after def keyword followed by parentheses in which
 arguments are given.
 End with colon (:)
  Inside the function add the program statements to be executed
 End with or without return statement
21 Unit 2: Data ,expressions, Statements
Syntax:
def fun_name(Parameter1,Parameter2…Parameter n):
statement1
statement2…
statement n
return[expression]
Example:
def my_add(a,b):
c=a+b
return c

6.3Function Calling: (Main Function)


 Once we have defined a function, we can call it from another function, program
 or even the Python prompt.
 To call a function we simply type the function name with appropriate
arguments.
Example:
x=5
y=4
my_add(x,y)

6.4 Flow of Execution:

 The order in which statements are executed is called the flow of execution
 Execution always begins at the first statement of the program.
 Statements are executed one at a time, in order, from top to bottom.
 Function definitions do not alter the flow of execution of the program, but
remember that statements inside the function are not executed until the function
 is called.
 Function calls are like a bypass in the flow of execution. Instead of going to the
next statement, the flow jumps to the first line of the called function, executes all
the statements there, and then comes back to pick up where it left off.
Note: When you read a program, don’t read from top to bottom. Instead, follow the
flow of execution. This means that you will read the def statements as you are scanning
from top to bottom, but you should skip the statements of the function definition until
you reach a point where that function is called.

6.5 Function Prototypes:

i. Function without arguments and without return type


ii. Function with arguments and without return type
iii. Function without arguments and with return type
iv. Function with arguments and with return type

22 Unit 2: Data ,expressions, Statements


i) Function without arguments and without return type
o In this type no argument is passed through the function call and no output
is return to main function
o The sub function will read the input values perform the operation and print
the result in the same block
ii) Function with arguments and without return type
o Arguments are passed through the function call but output is not return to
the main function
iii) Function without arguments and with return type
o In this type no argument is passed through the function call but output is
return to the main function.
iv) Function with arguments and with return type
o In this type arguments are passed through the function call and output is
return to the main function
Without Return Type
Without argument With argument
def add(): def add(a,b):
a=int(input("enter a")) c=a+b
b=int(input("enter b")) print(c)
c=a+b a=int(input("enter a"))
print(c) b=int(input("enter b"))
add() add(a,b)
OUTPUT: OUTPUT:
enter a 5 enter a 5
enter b 10 enter b 10
15 15

With return type


Without argument With argument
def add(): def add(a,b):
a=int(input("enter a")) c=a+b
b=int(input("enter b")) return c
c=a+b a=int(input("enter a"))
return c b=int(input("enter b"))
c=add() c=add(a,b)
print(c) print(c)

OUTPUT: OUTPUT:
enter a 5 enter a 5
enter b 10 enter b 10
15 15

23 Unit 2: Data ,expressions, Statements


6.6 Parameters And Arguments:
Parameters:
 Parameters are the value(s) provided in the parenthesis when we write function
 header.
  These are the values required by function to work.
 If there is more than one value required, all of them will be listed in parameter
 list separated by comma.
 Example: def my_add(a,b):
Arguments :
  Arguments are the value(s) provided in function call/invoke statement.
  List of arguments should be supplied in same way as parameters are listed.
 Bounding of parameters to arguments is done 1:1, and so there should be same
 number and type of arguments as mentioned in parameter list.
 Example: my_add(x,y)
6.7 RETURN STATEMENT:
 The return statement is used to exit a function and go back to the place from
 where it was called.
 If the return statement has no arguments, then it will not return any values. But
exits from function.
Syntax:
return[expression]

Example:
def my_add(a,b):
c=a+b
return c
x=5
y=4
print(my_add(x,y))
Output:
9
6.8 ARGUMENTS TYPES:
1. Required Arguments
2. Keyword Arguments
3. Default Arguments
4. Variable length Arguments
 Required Arguments: The number of arguments in the function call should
match exactly with the function definition.
def my_details( name, age ):
print("Name: ", name)
print("Age ", age)
return
my_details("george",56)

24 Unit 2: Data ,expressions, Statements


Output:
Name: george
Age 56
 Keyword Arguments:
Python interpreter is able to use the keywords provided to match the values with
parameters even though if they are arranged in out of order.

def my_details( name, age ):


print("Name: ", name)
print("Age ", age)
return
my_details(age=56,name="george")
Output:
Name: george
Age 56

 Default Arguments:
Assumes a default value if a value is not provided in the function call for that argument.
def my_details( name, age=40 ):
print("Name: ", name)
print("Age ", age)
return
my_details(name="george")
Output:
Name: george
Age 40

 Variable length Arguments


If we want to specify more arguments than specified while defining the function,
variable length arguments are used. It is denoted by * symbol before parameter.
def my_details(*name ):
print(*name)
my_details("rajan","rahul","micheal",
ärjun")
Output:
rajan rahul micheal ärjun

6.9 MODULES:
 A module is a file containing Python definitions ,functions, statements and
 instructions.
  Standard library of Python is extended as modules.
 To use these modules in a program, programmer needs to import the
module.

25 Unit 2: Data ,expressions, Statements


 Once we import a module, we can reference or use to any of its functions or
 variables in our code.
 o There is large number of standard modules also available in python.
o Standard modules can be imported the same way as we import our user-
 defined modules.
o Every module contains many function.
o To access one of the function , you have to specify the name of the module and
the name of the function separated by dot . This format is called dot
notation.
Syntax:
import module_name
module_name.function_name(variable)
Importing Builtin Module: Importing User Defined Module:
import math import cal
x=math.sqrt(25) x=cal.add(5,4)
print(x) print(x)

Built-in python modules are,


1.math – mathematical functions:
some of the functions in math module is,
math.ceil(x) - Return the ceiling of x, the smallest integer greater
26 Unit 2: Data ,expressions, Statements
than or equal to x
math.floor(x) - Return the floor of x, the largest integer less than or
equal to x.
math.factorial(x) -Return x factorial. math.gcd(x,y)- Return the
greatest common divisor of the integers a and b
math.sqrt(x)- Return the square root of x
math.log(x)- return the natural logarithm of x
math.log10(x) – returns the base-10 logarithms
math.log2(x) - Return the base-2 logarithm of x.
math.sin(x) – returns sin of x radians
math.cos(x)- returns cosine of x radians
math.tan(x)-returns tangent of x radians math.pi - The
mathematical constant π = 3.141592 math.e – returns The
mathematical constant e = 2.718281

2 .random-Generate pseudo-random numbers


random.randrange(stop)
random.randrange(start, stop[, step])
random.uniform(a, b)
-Return a random floating point number

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

Program to find distance between two Output


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

Program to circulate n numbers Output:


a=list(input("enter the list")) enter the list '1234'
27 Unit 2: Data ,expressions, Statements
print(a) ['1', '2', '3', '4']
for i in range(1,len(a),1): ['2', '3', '4', '1']
print(a[i:]+a[:i]) ['3', '4', '1', '2']
['4', '1', '2', '3']

Part A:
1. What is interpreter?
2. What are the two modes of python?
3. List the features of python.
4. List the applications of python
5. List the difference between interactive and script mode
6. What is value in python?
7. What is identifier? and list the rules to name identifier.
8. What is keyword?
9. How to get data types in compile time and runtime?
10. What is indexing and types of indexing?
11. List out the operations on strings.
12. Explain slicing?
13. Explain below operations with the example
(i)Concatenation (ii)Repetition
14. Give the difference between list and tuple
15. Differentiate Membership and Identity operators.
16. Compose the importance of indentation in python.
17. Evaluate the expression and find the result
(a+b)*c/d
a+b*c/d
18. Write a python program to print ‘n’ numbers.
19. Define function and its uses
20. Give the various data types in Python
21. Assess a program to assign and access variables.
22. Select and assign how an input operation was done in python.
23. Discover the difference between logical and bitwise operator.
24. Give the reserved words in Python.
25. Give the operator precedence in python.
26. Define the scope and lifetime of a variable in python.
27. Point out the uses of default arguments in python
28. Generalize the uses of python module.
29. Demonstrate how a function calls another function. Justify your answer.
30. List the syntax for function call with and without arguments.
31. Define recursive function.
32. What are the two parts of function definition? give the syntax.
33. Point out the difference between recursive and iterative technique.
34. Give the syntax for variable length arguments.

28 Unit 2: Data ,expressions, Statements


Part B
1. Explain in detail about various data types in Python with an example?
2. Explain the different types of operators in python with an example.
3. Discuss the need and importance of function in python.
4. Explain in details about function prototypes in python.
5. Discuss about the various type of arguments in python.
6. Explain the flow of execution in user defined function with example.
7. Illustrate a program to display different data types using variables and literal constants.
8. Show how an input and output function is performed in python with an example.
9. Explain in detail about the various operators in python with suitable examples.
10. Discuss the difference between tuples and list
11. Discuss the various operation that can be performed on a tuple and Lists (minimum
5)with an example program
12. What is membership and identity operators.
13. Write a program to perform addition, subtraction, multiplication, integer division,
floor division and modulo division on two integer and float.
14. Write a program to convert degree Fahrenheit to Celsius
15. Discuss the need and importance of function in python.
16. Illustrate a program to exchange the value of two variables with temporary variables
17. Briefly discuss in detail about function prototyping in python. With suitable example
program
18. Analyze the difference between local and global variables.
19. Explain with an example program to circulate the values of n variables
20. Analyze with a program to find out the distance between two points using python.
21. Do the Case study and perform the following operation in tuples i) Maxima minima
iii)sum of two tuples iv) duplicate a tuple v)slicing operator vi) obtaining a list from a
tuple vii) Compare two tuples viii)printing two tuples of different data types
22. Write a program to find out the square root of two numbers.
Basic python programs:

Addition of two numbers Output


a=eval(input(“enter first no”)) enter first no
b=eval(input(“enter second no”)) 5
c=a+b enter second no
print(“the sum is “,c) 6
the sum is 11
Area of rectangle Output
l=eval(input(“enter the length of rectangle”)) enter the length of rectangle 5
b=eval(input(“enter the breath of rectangle”)) enter the breath of rectangle 6
a=l*b 30
print(a)
Area & circumference of circle output
r=eval(input(“enter the radius of circle”)) enter the radius of circle4
a=3.14*r*r the area of circle 50.24
c=2*3.14*r the circumference of circle
print(“the area of circle”,a) 25.12
print(“the circumference of circle”,c)
Calculate simple interest Output
p=eval(input(“enter principle amount”)) enter principle amount 5000
n=eval(input(“enter no of years”)) enter no of years 4
r=eval(input(“enter rate of interest”)) enter rate of interest6
si=p*n*r/100 simple interest is 1200.0
print(“simple interest is”,si)

Calculate engineering cutoff Output


p=eval(input(“enter physics marks”)) enter physics marks 100
c=eval(input(“enter chemistry marks”)) enter chemistry marks 99
m=eval(input(“enter maths marks”)) enter maths marks 96
cutoff=(p/4+c/4+m/2) cutoff = 97.75
print(“cutoff =”,cutoff)

Check voting eligibility output


age=eval(input(“enter ur age”)) Enter ur age
If(age>=18): 19
print(“eligible for voting”) Eligible for voting
else:
print(“not eligible for voting”)

31
Find greatest of three numbers output
a=eval(input(“enter the value of a”)) enter the value of a 9
b=eval(input(“enter the value of b”)) enter the value of a 1
c=eval(input(“enter the value of c”)) enter the value of a 8
if(a>b): the greatest no is 9
if(a>c):
print(“the greatest no is”,a)
else:
print(“the greatest no is”,c)
else:
if(b>c):
print(“the greatest no is”,b)
else:
print(“the greatest no is”,c)
Programs on for loop
Print n natural numbers Output

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

print(i)
Print n odd numbers Output
for i in range(1,10,2):
13579
print(i)

Print n even numbers Output


for i in range(2,10,2):
2468
print(i)
Print squares of numbers Output

for i in range(1,5,1): 1 4 9 16

print(i*i)

Print squares of numbers Output

for i in range(1,5,1): 1 8 27 64

print(i*i*i)

Programs on while loop

32
Print n natural numbers Output
i=1 1
while(i<=5): 2
print(i) 3
i=i+1 4
5
Print n odd numbers Output
i=2 2
while(i<=10): 4
print(i) 6
i=i+2 8
10
Print n even numbers Output
i=1 1
while(i<=10): 3
print(i) 5
i=i+2 7
9
Print n squares of numbers Output
i=1 1
while(i<=5): 4
print(i*i) 9
i=i+1 16
25

Print n cubes numbers Output


i=1 1
while(i<=3): 8
print(i*i*i) 27
i=i+1

find sum of n numbers Output


i=1 55
sum=0
while(i<=10):
sum=sum+i
i=i+1
print(sum)

33
factorial of n numbers/product of n numbers Output
i=1 3628800
product=1
while(i<=10):
product=product*i
i=i+1
print(product)

sum of n numbers Output


def add(): enter a value
a=eval(input(“enter a value”)) 6
b=eval(input(“enter b value”)) enter b value
c=a+b 4
print(“the sum is”,c) the sum is 10
add()

area of rectangle using function Output


def area(): enter the length of
l=eval(input(“enter the length of rectangle”)) rectangle 20
b=eval(input(“enter the breath of rectangle”)) enter the breath of
a=l*b rectangle 5
print(“the area of rectangle is”,a) the area of rectangle is
area() 100

swap two values of variables Output


def swap(): enter a value3
a=eval(input("enter a value")) enter b value5
b=eval(input("enter b value")) a= 5 b= 3
c=a
a=b
b=c
print("a=",a,"b=",b)
swap()

34
check the no divisible by 5 or not Output
def div(): enter n value10
n=eval(input("enter n value")) the number is divisible by
if(n%5==0): 5
print("the number is divisible by 5")
else:
print("the number not divisible by 5")
div()

find reminder and quotient of given no Output


def reminder(): enter a 6
a=eval(input("enter a")) enter b 3
b=eval(input("enter b")) the reminder is 0
R=a%b enter a 8
print("the reminder is",R) enter b 4
def quotient(): the reminder is 2.0
a=eval(input("enter a"))
b=eval(input("enter b"))
Q=a/b
print("the reminder is",Q)
reminder()
quotient()

convert the temperature Output


enter temperature in
def ctof(): centigrade 37
c=eval(input("enter temperature in centigrade")) the temperature in
f=(1.8*c)+32 Fahrenheit is 98.6
print("the temperature in Fahrenheit is",f) enter temp in Fahrenheit
def ftoc(): 100
f=eval(input("enter temp in Fahrenheit")) the temperature in
c=(f-32)/1.8 centigrade is 37.77
print("the temperature in centigrade is",c)
ctof()
ftoc()

35
program for basic calculator Output
def add(): enter a value 10
a=eval(input("enter a value")) enter b value 10
b=eval(input("enter b value")) the sum is 20
c=a+b enter a value 10
print("the sum is",c) enter b value 10
def sub(): the diff is 0
a=eval(input("enter a value")) enter a value 10
b=eval(input("enter b value")) enter b value 10
c=a-b the mul is 100
print("the diff is",c) enter a value 10
def mul(): enter b value 10
a=eval(input("enter a value")) the div is 1
b=eval(input("enter b value"))
c=a*b
print("the mul is",c)
def div():
a=eval(input("enter a value"))
b=eval(input("enter b value"))
c=a/b
print("the div is",c)
add()
sub()
mul()
div()
UNIT III
CONTROL FLOW, FUNCTIONS
Conditionals: Boolean values and operators, conditional (if), alternative (if-else),
chained conditional (if-elif-else); Iteration: state, while, for, break, continue, pass;
Fruitful functions: return values, parameters, scope: local and global, composition,
recursion; Strings: string slices, immutability, string functions and methods, string
module; Lists as arrays. Illustrative programs: square root, gcd, exponentiation, sum the
array of numbers, linear search, binary search.

BOOLEAN VALUES:
Boolean:
 Boolean data type have two values. They are 0 and 1.
 0 represents False
 1 represents True
 True and False are keyword.

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

OPERATORS:
 Operators are the constructs which can manipulate the value of operands.
 Consider the expression 4 + 5 = 9. Here, 4 and 5 are called operands and + is
called operator.

Types of Operators:
1. Arithmetic Operators
2. Comparison (Relational) Operators
3. Assignment Operators
4. Logical Operators
5. Bitwise Operators
6. Membership Operators
7. Identity Operators

1 Unit 3:control flow, functions


Arithmetic operators:
They are used to perform mathematical operations like addition, subtraction,
multiplication etc.
Operator Description Example
a=10,b=20
+ Addition Adds values on either side of the operator. a + b = 30
- Subtraction Subtracts right hand operand from left hand operand. a – b = -10
* Multiplication Multiplies values on either side of the operator a * b = 200
/ Division Divides left hand operand by right hand operand b/a=2
% Modulus Divides left hand operand by right hand operand and b % a = 0
returns remainder
** Exponent Performs exponential (power) calculation on a**b =10 to the
operators power 20
// Floor Division - The division of operands where the 5//2=2
result is the quotient in which the digits after the
decimal point are removed

Comparison (Relational) Operators:


 Comparison operators are used to compare values.
 It either returns True or False according to the condition.
Operator Description Example
a=10,b=20
== If the values of two operands are equal, then the condition (a == b) is not
becomes true. true.
!= If values of two operands are not equal, then condition becomes
(a!=b) is true
true.
> If the value of left operand is greater than the value of right (a > b) is not
operand, then condition becomes true. true.
< If the value of left operand is less than the value of right (a < b) is true.
operand, then condition becomes true.
>= If the value of left operand is greater than or equal to the value (a >= b) is not
of right operand, then condition becomes true. true.
<= If the value of left operand is less than or equal to the value of (a <= b) is
right operand, then condition becomes true. true.
Assignment Operators:
Assignment operators are used in Python to assign values to variables.
Operator Description Example
= Assigns values from right side operands to left c = a + b assigns
side operand value of a + b into c
+= Add AND It adds right operand to the left operand and c += a is equivalent
assign the result to left operand to c = c + a
-= Subtract AND It subtracts right operand from the left operand c -= a is equivalent
and assign the result to left operand to c = c - a
2 Unit 3:control flow, functions
*= Multiply AND It multiplies right operand with the left operand c *= a is equivalent
and assign the result to left operand to c = c * a
/= Divide AND It divides left operand with the right operand and c /= a is equivalent
assign the result to left operand to c = c / ac /= a is
equivalent to c = c
/a
%= Modulus AND It takes modulus using two operands and assign c %= a is
the result to left operand equivalent to c = c
%a
**= Exponent AND Performs exponential (power) calculation on c **= a is
operators and assign value to the left operand equivalent to c = c
** a
//= Floor Division It performs floor division on operators and c //= a is
assign value to the left operand equivalent to c = c
// a
Logical Operators:
Logical operators are and, or, not operators.

Bitwise Operators:
Let x = 10 (0000 1010 in binary) and y = 4 (0000 0100 in binary)

Membership Operators:
 Evaluates to find a value or a variable is in the specified sequence of string,
list, tuple, dictionary or not.
 To check particular element is available in the list or not.
 Operators are in and not in.

3 Unit 3:control flow, functions


Example:
x=[5,3,6,4,1]
>>> 5 in x
True
>>> 5 not in x
False
Identity Operators:
They are used to check if two values (or variables) are located on the same part of
the memory.

Example
x=5
y=5
a = 'Hello'
b = 'Hello'
print(x is not y) // False
print(a is b)//True
CONDITIONALS
 Conditional if
 Alternative if… else
 Chained if…elif…else
 Nested if….else

Conditional (if):
conditional (if) is used to test a condition, if the condition is true the statements
inside if will be executed.
syntax:

Flowchart:

4 Unit 3:control flow, functions


Example:
1. Program to provide flat rs 500, if the purchase amount is greater than 2000.
2. Program to provide bonus mark if the category is sports.
Program to provide flat rs 500, if the purchase amount output
is greater than 2000.
purchase=eval(input(“enter your purchase amount”)) enter your purchase
if(purchase>=2000): amount
purchase=purchase-500 2500
print(“amount to pay”,purchase) amount to pay
2000
Program to provide bonus mark if the category is output
sports
m=eval(input(“enter ur mark out of 100”)) enter ur mark out of 100
c=input(“enter ur categery G/S”) 85
if(c==”S”): enter ur categery G/S
m=m+5 S
print(“mark is”,m) mark is 90

alternative (if-else)
In the alternative the condition must be true or false. In this else statement can
be combined with if statement. The else statement contains the block of code that
executes when the condition is false. If the condition is true statements inside the if get
executed otherwise else part gets executed. The alternatives are called branches,
because they are branches in the flow of execution.
syntax:

Flowchart:

Examples:
1. odd or even number
2. positive or negative number
3. leap year or not

5 Unit 3:control flow, functions


4. greatest of two numbers
5. eligibility for voting
Odd or even number Output
n=eval(input("enter a number")) enter a number4
if(n%2==0): even number
print("even number")
else:
print("odd number")
positive or negative number Output
n=eval(input("enter a number")) enter a number8
if(n>=0): positive number
print("positive number")
else:
print("negative number")
leap year or not Output
y=eval(input("enter a yaer")) enter a yaer2000
if(y%4==0): leap year
print("leap year")
else:
print("not leap year")

greatest of two numbers Output


a=eval(input("enter a value:")) enter a value:4
b=eval(input("enter b value:")) enter b value:7
if(a>b): greatest: 7
print("greatest:",a)
else:
print("greatest:",b)
eligibility for voting Output
age=eval(input("enter ur age:")) enter ur age:78
if(age>=18): you are eligible for vote
print("you are eligible for vote")
else:
print("you are eligible for vote")

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

6 Unit 3:control flow, functions


 The if block can have only one else block. But it can have
multiple elif blocks.
 The way to express a computation like that is a chained conditional.
syntax:

Flowchart:

Example:
1. student mark system
2. traffic light system
3. compare two numbers
4. roots of quadratic equation

7 Unit 3:control flow, functions


student mark system Output
mark=eval(input("enter ur mark:")) enter ur mark:78
if(mark>=90): grade:B
print("grade:S")
elif(mark>=80):
print("grade:A")
elif(mark>=70):
print("grade:B")
elif(mark>=50):
print("grade:C")
else:
print("fail")
traffic light system Output
colour=input("enter colour of light:") enter colour of light:green
if(colour=="green"): GO
print("GO")
elif(colour=="yellow"):
print("GET READY")
else:
print("STOP")
compare two numbers Output
x=eval(input("enter x value:")) enter x value:5
y=eval(input("enter y value:")) enter y value:7
if(x == y): x is less than y
print("x and y are equal")
elif(x < y):
print("x is less than y")
else:
print("x is greater than y")
Roots of quadratic equation output
a=eval(input("enter a value:")) enter a value:1
b=eval(input("enter b value:")) enter b value:0
c=eval(input("enter c value:")) enter c value:0
d=(b*b-4*a*c) same and real roots
if(d==0):
print("same and real roots")
elif(d>0):
print("diffrent real roots")
else:
print("imaginagry roots")
Nested conditionals
One conditional can also be nested within another. Any number of condition can
be nested inside one another. In this, if the condition is true it checks another if
condition1. If both the conditions are true statement1 get executed otherwise
statement2 get execute. if the condition is false statement3 gets executed
8 Unit 3:control flow, functions
Syntax:

Flowchart:

Example:
1. greatest of three numbers
2. positive negative or zero
greatest of three numbers output
a=eval(input(“enter the value of a”)) enter the value of a 9
b=eval(input(“enter the value of b”)) enter the value of a 1
c=eval(input(“enter the value of c”)) enter the value of a 8
if(a>b): the greatest no is 9
if(a>c):
print(“the greatest no is”,a)
else:
print(“the greatest no is”,c)
9 Unit 3:control flow, functions
else:
if(b>c):
print(“the greatest no is”,b)
else:
print(“the greatest no is”,c)
positive negative or zero output
n=eval(input("enter the value of n:")) enter the value of n:-9
if(n==0): the number is negative
print("the number is zero")
else:
if(n>0):
print("the number is positive")
else:
print("the number is negative")
ITERATION/CONTROL STATEMENTS:
 state
 while
 for
 break
 continue
 pass
State:
Transition from one process to another process under specified condition with in
a time is called state.
While loop:
 While loop statement in Python is used to repeatedly executes set of
statement as long as a given condition is true.
 In while loop, test expression is checked first. The body of the loop is
entered only if the test_expression is True. After one iteration, the test
expression is checked again. This process continues until
the test_expression evaluates to False.
 In Python, the body of the while loop is determined through indentation.
 The statements inside the while starts with indentation and the first
unindented line marks the end.

Syntax:

10 Unit 3:control flow, functions


Flowchart:

Examples:
1. program to find sum of n numbers:
2. program to find factorial of a number
3. program to find sum of digits of a number:
4. Program to Reverse the given number:
5. Program to find number is Armstrong number or not
6. Program to check the number is palindrome or not
Sum of n numbers: output
n=eval(input("enter n")) enter n
i=1 10
sum=0 55
while(i<=n):
sum=sum+i
i=i+1
print(sum)

Factorial of a numbers: output


n=eval(input("enter n")) enter n
i=1 5
fact=1 120
while(i<=n):
fact=fact*i
i=i+1
print(fact)

Sum of digits of a number: output


n=eval(input("enter a number")) enter a number
sum=0 123
while(n>0): 6
a=n%10

11 Unit 3:control flow, functions


sum=sum+a
n=n//10
print(sum)

Reverse the given number: output


n=eval(input("enter a number")) enter a number
sum=0 123
while(n>0): 321
a=n%10
sum=sum*10+a
n=n//10
print(sum)

Armstrong number or not output


n=eval(input("enter a number")) enter a number153
org=n The given number is Armstrong number
sum=0
while(n>0):
a=n%10
sum=sum+a*a*a
n=n//10
if(sum==org):
print("The given number is Armstrong
number")
else:
print("The given number is not
Armstrong number")

Palindrome or not output


n=eval(input("enter a number")) enter a number121
org=n The given no is palindrome
sum=0
while(n>0):
a=n%10
sum=sum*10+a
n=n//10
if(sum==org):
print("The given no is palindrome")
else:
print("The given no is not palindrome")

12 Unit 3:control flow, functions


For loop:
 for in range:
 We can generate a sequence of numbers using range() function.
range(10) will generate numbers from 0 to 9 (10 numbers).

 In range function have to define the start, stop and step size
as range(start,stop,step size). step size defaults to 1 if not provided.

syntax

Flowchart:

For in sequence
 The for loop in Python is used to iterate over a sequence (list, tuple, string).
Iterating over a sequence is called traversal. Loop continues until we reach the
last element in the sequence.
 The body of for loop is separated from the rest of the code using indentation.

Sequence can be a list, strings or tuples

s.no sequences example output


R
1. For loop in string for i in "Ramu": A
print(i) M
U
13 Unit 3:control flow, functions
2
2. For loop in list for i in [2,3,5,6,9]: 3
print(i) 5
6
9
for i in (2,3,1): 2
3. For loop in tuple print(i) 3
1
Examples:
1. print nos divisible by 5 not by 10:
2. Program to print fibonacci series.
3. Program to find factors of a given number
4. check the given number is perfect number or not
5. check the no is prime or not
6. Print first n prime numbers
7. Program to print prime numbers in range

print nos divisible by 5 not by 10 output


n=eval(input("enter a")) enter a:30
for i in range(1,n,1): 5
if(i%5==0 and i%10!=0): 15
print(i) 25

Fibonacci series output


a=0 Enter the number of terms: 6
b=1 Fibonacci Series:
n=eval(input("Enter the number of terms: ")) 01
print("Fibonacci Series: ") 1
print(a,b) 2
for i in range(1,n,1): 3
c=a+b 5
print(c) 8
a=b
b=c
find factors of a number Output
n=eval(input("enter a number:")) enter a number:10
for i in range(1,n+1,1): 1
if(n%i==0): 2
print(i) 5
10

14 Unit 3:control flow, functions


check the no is prime or not output
n=eval(input("enter a number")) enter a no:7
for i in range(2,n): The num is a prime number.
if(n%i==0):
print("The num is not a prime")
break
else:
print("The num is a prime number.")

check a number is perfect number or not Output


n=eval(input("enter a number:")) enter a number:6
sum=0 the number is perfect number
for i in range(1,n,1):
if(n%i==0):
sum=sum+i
if(sum==n):
print("the number is perfect number")
else:
print("the number is not perfect number")
Program to print first n prime numbers Output
number=int(input("enter no of prime enter no of prime numbers to be
numbers to be displayed:")) displayed:5
count=1 2
n=2 3
while(count<=number): 5
for i in range(2,n): 7
if(n%i==0): 11
break
else:
print(n)
count=count+1
n=n+1
Program to print prime numbers in range output:
lower=eval(input("enter a lower range")) enter a lower range50
upper=eval(input("enter a upper range")) enter a upper range100
for n in range(lower,upper + 1): 53
if n > 1: 59
for i in range(2,n): 61
if (n % i) == 0: 67
break 71
else: 73
print(n) 79
83
89
97

15 Unit 3:control flow, functions


Loop Control Structures
BREAK
 Break statements can alter the flow of a loop.
 It terminates the current
 loop and executes the remaining statement outside the loop.
 If the loop has else statement, that will also gets terminated and come out of the
loop completely.
Syntax:
break

Flowchart

example Output
for i in "welcome": w
if(i=="c"): e
break l
print(i)

16 Unit 3:control flow, functions


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

Flowchart

Example: Output
for i in "welcome": w
if(i=="c"): e
continue l
print(i) o
m
e
PASS
 It is used when a statement is required syntactically but you don’t want any code
to execute.
 It is a null statement, nothing happens when it is executed.

17 Unit 3:control flow, functions


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

Difference between break and continue


break continue
It terminates the current loop and It terminates the current iteration and
executes the remaining statement outside transfer the control to the next iteration in
the loop. the loop.
syntax: syntax:
break continue
for i in "welcome": for i in "welcome":
if(i=="c"): if(i=="c"):
break continue
print(i) print(i)
w w
e e
l l
o
m
e
else statement in loops:
else in for loop:
 If else statement is used in for loop, the else statement is executed when the loop
has reached the limit.
 The statements inside for loop and statements inside else will also execute.
example output
for i in range(1,6): 1
print(i) 2
else: 3
print("the number greater than 6") 4
5 the number greater than 6

18 Unit 3:control flow, functions


else in while loop:
 If else statement is used within while loop , the else part will be executed when
the condition become false.
 The statements inside for loop and statements inside else will also execute.
Program output
i=1 1
while(i<=5): 2
print(i) 3
i=i+1 4
else: 5
print("the number greater than 5") the number greater than 5

Fruitful Function
 Fruitful function
 Void function
 Return values
 Parameters
 Local and global scope
 Function composition
 Recursion
Fruitful function:
A function that returns a value is called fruitful function.
Example:
Root=sqrt(25)
Example:
def add():
a=10
b=20
c=a+b
return c
c=add()
print(c)

Void Function
A function that perform action but don’t return any value.
Example:
print(“Hello”)
Example:
def add():
a=10
b=20
19 Unit 3:control flow, functions
c=a+b
print(c)
add()

Return values:
return keywords are used to return the values from the function.
example:
return a – return 1 variable
return a,b– return 2 variables
return a,b,c– return 3 variables
return a+b– return expression
return 8– return value
PARAMETERS / ARGUMENTS:
 Parameters are the variables which used in the function definition. Parameters
are inputs to functions. Parameter receives the input from the function call.
 It is possible to define more than one parameter in the function definition.
Types of parameters/Arguments:
1. Required/Positional parameters
2. Keyword parameters
3. Default parameters
4. Variable length parameters
Required/ Positional Parameter:

The number of parameter in the function definition should match exactly with
number of arguments in the function call.

Example Output:
def student( name, roll ): George 98
print(name,roll)
student(“George”,98)
Keyword parameter:
When we call a function with some values, these values get assigned to the parameter
according to their position. When we call functions in keyword parameter, the order of the
arguments can be changed.
Example Output:
def student(name,roll,mark): 90 102 bala
print(name,roll,mark)
student(90,102,"bala")

20 Unit 3:control flow, functions


Default parameter:

Python allows function parameter to have default values; if the function is called
without the argument, the argument gets its default value in function definition.

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

Variable length parameter

 Sometimes, we do not know in advance the number of arguments that will


be passed into a function.

 Python allows us to handle this kind of situation through function calls


with number of arguments.

 In the function definition we use an asterisk (*) before the parameter name
to denote this is variable length of parameter.

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

Local and Global Scope


Global Scope
 The scope of a variable refers to the places that you can see or access a variable.
 A variable with global scope can be used anywhere in the program.
 It can be created by defining a variable outside the function.
Example output
a=50
def add():
Global Variable
b=20 70
c=a+b
print© Local Variable
def sub():
b=30
c=a-b 20
print©
print(a) 50

21 Unit 3:control flow, functions


Local Scope A variable with local scope can be used only within the function .
Example output
def add():
b=20
c=a+b 70
Local Variable
print©
def sub():
b=30 20
c=a-b Local Variable
print©
print(a) error
print(b) error
Function Composition:
 Function Composition is the ability to call one function from within another
function
 It is a way of combining functions such that the result of each function is passed
as the argument of the next function.
 In other words the output of one function is given as the input of another function
is known as function composition.

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

find sum and average using function output


composition
def sum(a,b): enter a:4
sum=a+b enter b:8
return sum the avg is 6.0
def avg(sum):
avg=sum/2
return avg
a=eval(input("enter a:"))
b=eval(input("enter b:"))
sum=sum(a,b)
avg=avg(sum)
22 Unit 3:control flow, functions
print("the avg is",avg)
Recursion
A function calling itself till it reaches the base value - stop point of function call.
Example: factorial of a given number using recursion
Factorial of n Output
def fact(n): enter no. to find fact:5
if(n==1): Fact is 120
return 1
else:
return n*fact(n-1)

n=eval(input("enter no. to find


fact:"))
fact=fact(n)
print("Fact is",fact)
Explanation

Examples:
1. sum of n numbers using recursion
2. exponential of a number using recursion
Sum of n numbers Output
def sum(n): enter no. to find sum:10
if(n==1): Fact is 55
return 1
else:
return n*sum(n-1)

n=eval(input("enter no. to find


sum:"))
sum=sum(n)
print("Fact is",sum)
23 Unit 3:control flow, functions
Strings:
 Strings
 String slices
 Immutability
 String functions and methods
 String module

Strings:
 String is defined as sequence of characters represented in quotation marks
(either single quotes ( ‘ ) or double quotes ( “ ).
 An individual character in a string is accessed using a index.
 The index should always be an integer (positive or negative).
 A index starts from 0 to n-1.
 Strings are immutable i.e. the contents of the string cannot be changed after it is
created.
 Python will get the input at run time by default as a string.
 Python does not support character data type. A string of size 1 can be treated as
characters.
1. single quotes (' ')
2. double quotes (" ")
3. triple quotes(“”” “”””)

Operations on string:
1. Indexing
2. Slicing
3. Concatenation
4. Repetitions
5. Member ship

>>>a=”HELLO”  Positive indexing helps in accessing


indexing >>>print(a[0]) the string from the beginning
>>>H  Negative subscript helps in accessing
>>>print(a[-1]) the string from the end.
>>>O
24 Unit 3:control flow, functions
Print[0:4] – HELL The Slice[start : stop] operator extracts
Slicing: Print[ :3] – HEL sub string from the strings.
Print[0: ]- HELLO A segment of a string is called a slice.

a=”save” The + operator joins the text on both


Concatenation b=”earth” sides of the operator.
>>>print(a+b)
saveearth

a=”panimalar ” The * operator repeats the string on the


Repetitions: >>>print(3*a) left hand side times the value on right
panimalarpanimalar hand side.
panimalar

Membership: >>> s="good morning" Using membership operators to check a


>>>"m" in s particular character is in string or not.
True Returns true if present
>>> "a" not in s
True
String slices:
 A part of a string is called string slices.
 The process of extracting a sub string from a string is called slicing.
Print[0:4] – HELL The Slice[n : m] operator extracts sub
Slicing: Print[ :3] – HEL string from the strings.
a=”HELLO” Print[0: ]- HELLO A segment of a string is called a slice.

Immutability:
 Python strings are “immutable” as they cannot be changed after they are created.
 Therefore [ ] operator cannot be used on the left side of an assignment.
operations Example output
element assignment a="PYTHON" TypeError: 'str' object does
a[0]='x' not support element
assignment

element deletion a=”PYTHON” TypeError: 'str' object


del a[0] doesn't support element
deletion
delete a string a=”PYTHON” NameError: name 'my_string'
del a is not defined
25 Unit 3:control flow, functions
print(a)
string built in functions and methods:
A method is a function that “belongs to” an object.

Syntax to access the method

Stringname.method()

a=”happy birthday”
here, a is the string name.
syntax example description
1 a.capitalize() >>> a.capitalize() capitalize only the first letter
' Happy birthday’ in a string
2 a.upper() >>> a.upper() change string to upper case
'HAPPY BIRTHDAY’
3 a.lower() >>> a.lower() change string to lower case
' happy birthday’
4 a.title() >>> a.title() change string to title case i.e.
' Happy Birthday ' first characters of all the
words are capitalized.
5 a.swapcase() >>> a.swapcase() change lowercase characters
'HAPPY BIRTHDAY' to uppercase and vice versa
6 a.split() >>> a.split() returns a list of words
['happy', 'birthday'] separated by space
7 a.center(width,”fillchar >>>a.center(19,”*”) pads the string with the
”) '***happy birthday***' specified “fillchar” till the
length is equal to “width”
8 a.count(substring) >>> a.count('happy') returns the number of
1 occurences of substring
9 a.replace(old,new) >>>a.replace('happy', replace all old substrings
'wishyou happy') with new substrings
'wishyou happy
birthday'
10 a.join(b) >>> b="happy" returns a string concatenated
>>> a="-" with the elements of an
>>> a.join(b) iterable. (Here “a” is the
'h-a-p-p-y' iterable)
11 a.isupper() >>> a.isupper() checks whether all the case-
False based characters (letters) of
the string are uppercase.
12 a.islower() >>> a.islower() checks whether all the case-
True based characters (letters) of
the string are lowercase.
13 a.isalpha() >>> a.isalpha() checks whether the string
False consists of alphabetic
characters only.
26 Unit 3:control flow, functions
14 a.isalnum() >>> a.isalnum() checks whether the string
False consists of alphanumeric
characters.
15 a.isdigit() >>> a.isdigit() checks whether the string
False consists of digits only.
16 a.isspace() >>> a.isspace() checks whether the string
False consists of whitespace only.
17 a.istitle() >>> a.istitle() checks whether string is title
False cased.
18 a.startswith(substring) >>> a.startswith("h") checks whether string starts
True with substring
19 a.endswith(substring) >>> a.endswith("y") checks whether the string
True ends with the substring
20 a.find(substring) >>> a.find("happy") returns index of substring, if
0 it is found. Otherwise -1 is
returned.
21 len(a) >>>len(a) Return the length of the
>>>14 string
22 min(a) >>>min(a) Return the minimum
>>>’ ‘ character in the string
23 max(a) max(a) Return the maximum
>>>’y’ character in the string

String modules:
 A module is a file containing Python definitions, functions, statements.
 Standard library of Python is extended as modules.
 To use these modules in a program, programmer needs to import the module.
 Once we import a module, we can reference or use to any of its functions or
variables in our code.
 There is large number of standard modules also available in python.
 Standard modules can be imported the same way as we import our user-defined
modules.
Syntax:
import module_name
Example output
import string
print(string.punctuation) !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
print(string.digits) 0123456789
print(string.printable) 0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJ
print(string.capwords("happ KLMNOPQRSTUVWXYZ!"#$%&'()*+,-
y birthday")) ./:;<=>?@[\]^_`{|}~
print(string.hexdigits) Happy Birthday
print(string.octdigits) 0123456789abcdefABCDEF
01234567
27 Unit 3:control flow, functions
Escape sequences in string
Escape Description example
Sequence
\n new line >>> print("hai \nhello")
hai
hello
\\ prints Backslash (\) >>> print("hai\\hello")
hai\hello
\' prints Single quote (') >>> print("'")
'
\" prints Double quote >>>print("\"")
(") "
\t prints tab sapace >>>print(“hai\thello”)
hai hello
\a ASCII Bell (BEL) >>>print(“\a”)

List as array:
Array:
Array is a collection of similar elements. Elements in the array can be accessed by
index. Index starts with 0. Array can be handled in python by module named array.
To create array have to import array module in the program.
Syntax :
import array
Syntax to create array:
Array_name = module_name.function_name(‘datatype’,[elements])
example:
a=array.array(‘i’,[1,2,3,4])
a- array name
array- module name
i- integer datatype

Example
Program to find sum of Output
array elements

import array 10
sum=0
a=array.array('i',[1,2,3,4])
for i in a:
sum=sum+i
print(sum)

28 Unit 3:control flow, functions


Convert list into array:
fromlist() function is used to append list to array. Here the list is act like a array.
Syntax:
arrayname.fromlist(list_name)
Example
program to convert list Output
into array

import array 35
sum=0
l=[6,7,8,9,5]
a=array.array('i',[])
a.fromlist(l)
for i in a:
sum=sum+i
print(sum)

Methods in array
a=[2,3,4,5]

Syntax example Description


1 array(data type, array(‘i’,[2,3,4,5]) This function is used to create
value list) an array with data type and
value list specified in its
arguments.
2 append() >>>a.append(6) This method is used to add the
[2,3,4,5,6] at the end of the array.
3 insert(index,element >>>a.insert(2,10) This method is used to add the
) [2,3,10,5,6] value at the position specified in
its argument.

4 pop(index) >>>a.pop(1) This function removes the


[2,10,5,6] element at the position
mentioned in its argument, and
returns it.
5 index(element) >>>a.index(2) This function returns the index
0 of value
6 reverse() >>>a.reverse() This function reverses the
[6,5,10,2] array.
7 count() a.count() This is used to count number of

29 Unit 3:control flow, functions


4 elements in an array

ILLUSTRATIVE PROGRAMS:
Square root using newtons method: Output:
def newtonsqrt(n): enter number to find Sqrt: 9
root=n/2 3.0
for i in range(10):
root=(root+n/root)/2
print(root)
n=eval(input("enter number to find Sqrt: "))
newtonsqrt(n)
GCD of two numbers output
n1=int(input("Enter a number1:")) Enter a number1:8
n2=int(input("Enter a number2:")) Enter a number2:24
for i in range(1,n1+1): 8
if(n1%i==0 and n2%i==0):
gcd=i
print(gcd)
Exponent of number Output:
def power(base,exp): Enter base: 2
if(exp==1): Enter exponential value:3
return(base) Result: 8
else:
return(base*power(base,exp-1))
base=int(input("Enter base: "))
exp=int(input("Enter exponential value:"))
result=power(base,exp)
print("Result:",result)
sum of array elements: output:
a=[2,3,4,5,6,7,8] the sum is 35
sum=0
for i in a:
sum=sum+i
print("the sum is",sum)
Linear search output
a=[20,30,40,50,60,70,89] [20, 30, 40, 50, 60, 70, 89]
print(a) enter a element to search:30
search=eval(input("enter a element to search:")) element found at 2
for i in range(0,len(a),1):
if(search==a[i]):
print("element found at",i+1)
break
else:
print("not found")

30 Unit 3:control flow, functions


Binary search output
a=[20, 30, 40, 50, 60, 70, 89] [20, 30, 40, 50, 60, 70, 89]
print(a) enter a element to search:30
search=eval(input("enter a element to search:")) element found at 2
start=0
stop=len(a)-1
while(start<=stop):
mid=(start+stop)//2
if(search==a[mid]):
print("elemrnt found at",mid+1)
break
elif(search<a[mid]):
stop=mid-1
else:
start=mid+1
else:
print("not found")

Part A:
1. What are Boolean values?
2. Define operator and operand?
3. Write the syntax for if with example?
4. Write the syntax and flowchart for if else.
5. Write the syntax and flowchart for chained if.
6. define state
7. Write the syntax for while loop with flowchart.
8. Write the syntax for for loopwith flowchart.
9. Differentiate break and continue.
10. mention the use of pass
11. what is fruitful function
12. what is void function
13. mention the different ways of writing return statement
14. What is parameter and list down its type?
15. What is local and global scope?
16. Differentiate local and global variable?
17. What is function composition, give an example?
18. Define recursion.
19. Differentiate iteration and recursion.
20. Define string. How to get a string at run time.

31 Unit 3:control flow, functions


21. What is slicing? Give an example.
22. What is immutability of string?
23. List out some string built in function with example?
24. Define string module?
25. How can list act as array?
26. write a program to check the number is odd or even.
27. write a program to check the number positive or negative
28. write a program to check the year is leap year or not
29. write a program to find greatest of two numbers
30. write a program for checking eligibility for vote
31. write a program to find sum of n numbers
32. write a program to find factorial of given numbers
33. write a program to find sum of digits of a number
34. Write a program to reverse the given number.
35. Write a program to check the given number is palindrome or not.
36. write a program to check the given number is Armstrong or not
37. how can you use for loop in sequence.
38. how can you use else statement if loops.
39. What is the use of map() function?
Part B:
1. Explain conditional statements in detail with example(if, if..else, if..elif..else)
2. explain in detail about operators in detail
3. Explain in detail about iterations with example.(for, while)
4. Explain the usage of else statements in loops
5. Explain in detail about using for loop in sequence.
6. Explain in detail about string built in function with suitable examples?
7. Explain about loop control statement(break, continue, pass)
8. Breifly discuss about fruitful function.
9. Discuss with an example about local and global variable
10. Discuss with an example about function composition
11. Explain in detail about recursion with example.
12. Explain in detail about strings and its operations(slicing,immutablity)
13. Program to find square root of a given number using newtons method
14. program to find gcd of given nnumber
15. program to find exponentiation of given number using recursion
16. program to find sum of array elements.
17. program to search an element using linear search.
18. program to search an element using binary element.
19. program to find factorial of a given number using recursion

32 Unit 3:control flow, functions


UNIT – 4
UNIT IV LISTS, TUPLES, DICTIONARIES 9
Lists: list operations, list slices, list methods, list loop, mutability, aliasing, cloning lists, list
parameters; Tuples: tuple assignment, tuple as return value; Dictionaries: operations and
methods; advanced list processing - list comprehension; Illustrative programs: selection sort,
insertion sort, merge sort, histogram.

LISTS, TUPLES, DICTIONARIES


4.1 LISTS:

A list is a sequence of values. In a string, the values are characters but in a list, list values
can be any type.
Elements or Items:
The values in a list are called elements or items. list must be enclosed in square brackets
([and]).
Examples:
>>>[10,20,30]
>>>[‘hi’,’hello’,’welcome’]
Nested List:
A list within another list is called nested list.
Example:
[‘good’,10,[100,99]]
Empty List:
A list that contains no elements is called empty list. It can be created with empty
brackets, [].
Assigning List Values to Variables:
Example:
>>>numbers=[40,121]
>>>characters=[‘x’,’y’]
>>>print(numbers,characters)
Output:
[40,12][‘x’,’y’]
4.1.1 LIST OPERATIONS:
Example 1: The + operator concatenates lists:
>>>a=[1,2,3]
>>>b=[4,5,6]
>>>c=a+b
>>>c
Output: [1,2,3,4,5,6]
Example 2:
The * operator repeats a list given number of times:
>>>[0]*4
Output:
[0,0,0,0]

>>>[1,2,3]*3
Output:
[1,2,3,1,2,3,1,2,3]
The first example repeats [0] four times.The second example repeats [1,2,3] three
times.
4.1.2 LIST SLICES:
List slicing is a computationally fast way to methodically access parts of given data.
Syntax:
Listname[start:end:step]where :end represents the first value that is not in the
selected slice. The differencebetween end and start is the numbe of elements selected (if step is
1, the default).The start and end may be a negative number. For negative numbers, the count
starts from the end of the array instead of the beginning.
Example:
>>>t=[‘a’,’b’,’c’,’d’,’e’,’f’]
Lists are mutable, so it is useful to make a copy before performing operations that
modify this. A slice operator on the left side of an assignment can update multiple
elements.
Example:
>>>t[1:3]=[‘x’,’y’]
>>>t
Output:
[‘a’,’x’,’y’,’d’,’e’,’f’]

4.1.3 LIST METHODS:


Python provides methods that operate on lists.
Example:
1. append adds a new element to the end of a list.
>>>t=[‘a’,’b’,’c’,’d’]
>>>t.append(‘e’)
>>>t
Output:
[‘a’,’b’,’c’,’d’,’e’]
2. extend takes a list as an argument and appends all the elements.
>>>t1=[‘a’,’b’]
>>>t2=[‘c’,’d’]
>>>t1.extend(t2)
>>>t1
Output:
[‘a’,’b’,’c’,’d’]
t2 will be unmodified.
4.1.4 LIST LOOP:
List loop is traversing the elements of a list with a for loop.
Example 1:
>>>mylist=[[1,2],[4,5]]
>>>for x in mylist:
if len(x)==2:
print x
Output:
[1,2]
[4,5]

Example 2:
>>>for i in range(len(numbers)):
Numbers[i]=numbers[i]*2
Above example is used for updating values in numbers variables.Above loop traverses
the list and updates each element. Len returns number of elements in the list. Range returns a list
of indices from 0 to n-1, where n is the length of the list.Each time through the loop i gets the
index of next element. A for loop over an empty list never runs the body:
Example:
for x in []:
print(‘This won’t work’)
A list inside another list counts as a single element. The length of the below list is four:
[‘spam’,1,[‘x’,’y’],[1,2,3]]
Example 3:
colors=[“red”,”green”,”blue”,”purple”]
for i in range(len(colors)):
print(colors[i])
Output:
red
green
blue
purple
4.1.5 MUTABILITY:
Lists are mutable. Mutable means, we can change the content without changing the
identity. Mutability is the ability for certain types of data to be changed without entirely
recreating it.Using mutable data types can allow programs to operate quickly and efficiently.

Example for mutable data types are:


List, Set and Dictionary

Example 1:
>>>numbers=[42,123]
>>>numbers[1]=5
>>>numbers
[42,5]

Here, the second element which was 123 is now turned to be 5.

Figure 4.1 shows the state diagram for cheeses, numbers and empty:

Lists are represented by boxes with the word “list” outside and the elements of the list
inside. cheeses refers to a list with three elements indexed 0, 1 and 2.
numbers contains two elements; the diagram shows that the value of the second element
has been reassigned from 123 to 5. empty refers to a list with no elements.
The in operator also works on lists.
>>> cheeses = ['Cheddar', 'Edam', 'Gouda']
>>> 'Edam' in cheeses
True
>>> 'Brie' in cheeses
False
4.1.6 ALIASING

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

The state diagram looks like Figure 4.2.

Figure 4.2 State Diagram


The association of a variable with an object is called a reference. In this example, there
are two references to the same object.An object with more than one reference has more than one
name, so we say that the object is aliased.If the aliased object is mutable, changes made with one
alias affect the other:
4.1.7 CLONING LISTS Copy list v Clone list
veggies=["potatoes","carrots","pepper","parsnips","swedes","onion","minehead"]
veggies[1]="beetroot"
# Copying a list gives it another name
daniel=veggies
# Copying a complete slice CLONES a list
david=veggies[:]
daniel[6]="emu"
# Daniel is a SECOND NAME for veggies so that changing Daniel also changes veggies.
# David is a COPY OF THE CONTENTS of veggies so that changing Daniel (or
veggies) does NOT change David.
# Changing carrots into beetroot was done before any of the copies were made, so will
affect all of veggies, daniel and david
for display in (veggies, daniel, david):
print(display)
Output:
['potatoes', 'beetroot', 'pepper', 'parsnips', 'swedes', 'onion', 'emu']
['potatoes', 'beetroot', 'pepper', 'parsnips', 'swedes', 'onion', 'emu']
['potatoes', 'beetroot', 'pepper', 'parsnips', 'swedes', 'onion', 'minehead']
4.1.8 LIST PAPRAMETERS
When we pass a list to a function, the function gets a reference to the list. If the function
modifies the list, the caller sees the change. For example, delete_head removes the first element
from a list:
Example:
def delete_head(t):
del t[0]
Here’s how it is used:
>>> letters = ['a', 'b', 'c']
>>> delete_head(letters)
>>> letters
Output:
['b', 'c']
The parameter t and the variable letters are aliases for the same object. The stack diagram
looks like Figure 4.3.Since the list is shared by two frames, I drew it between them. It is
important to distinguish between operations that modify lists and operations that create new lists.
For example, the append method modifies a list, but the + operator creates a new list.
Example 1:
>>> t1 = [1, 2]
>>> t2 = t1.append(3)
>>> t1
Output:
[1, 2, 3]

Example 2:
>>> t2
Output:
None

Figure 4.3 Stack Diagram

4.2. TUPLES
 A tuple is a sequence of values.
 The values can be any type and are indexed by integers, unlike lists.
 Tuples are immutable.
Syntactically, a tuple is a comma-separated list of values:
>>> t = 'a', 'b', 'c', 'd', 'e'
Although it is not necessary, it is common to enclose tuples in parentheses:
>>> t = ('a', 'b', 'c', 'd', 'e')
To create a tuple with a single element, we have to include a final comma:
>>> t1 = 'a',
>>> type(t1)
Output:
<class 'tuple'>
A value in parentheses is not a tuple:
>>> t2 = ('a')
>>> type(t2)
Output:
<class 'str'>
Another way to create a tuple is the built-in function tuple. With no argument, it creates
an empty tuple.
Example:
>>> t = tuple()
>>> t
Output: ()
If the argument is a sequence (string, list or tuple), the result is a tuple with the elements
of the sequence:
Example:
>>> t = tuple('lupins')
>>> t
Output: ('l', 'u', 'p', 'i', 'n', 's')
Because tuple is the name of a built-in function, we should avoid using it as a variable
name. Most list operators also work on tuples. The bracket operator indexes an element:
Example:
>>> t = ('a', 'b', 'c', 'd', 'e')
>>> t[0]
Output: 'a' And the slice operator selects a range of elements.
Example:
>>> t[1:3] Output:('b', 'c')But if we try to modify one of the elements of the
tuple, we get an error:
>>> t[0] = 'A'
TypeError: object doesn't support item assignmentBecause tuples are immutable, we
can’t modify the elements. But we can replace one
tuple with another: Example:
>>> t = ('A',) + t[1:]
>>> t
Output:
('A', 'b', 'c', 'd', 'e')This statement makes a new tuple and then makes t refer to it.
The relational operators work with tuples and other sequences; Python starts by
comparing the first element from each sequence. If they are equal, it goes on to the next
elements, and so on, until it finds elements that differ. Subsequent elements are not considered
(even if they are really big).
Example 1:
>>> (0, 1, 2) < (0, 3, 4)
Output:
True
Example 2:
>>> (0, 1, 2000000) < (0, 3, 4)
Output:
True
4.2.1 TUPLE ASSIGNMENT
It is often useful to swap the values of two variables. With conventional assignments, we
have to use a temporary variable. For example, to swap a and b:
Example:
>>> temp = a
>>> a = b
>>> b = temp
This solution is cumbersome; tuple assignment is more elegant:
>>> a, b = b, a
The left side is a tuple of variables; the right side is a tuple of expressions. Each value is
assigned to its respective variable. All the expressions on the right side are evaluated before any
of the assignments.The number of variables on the left and the number of values on the right
have to be the same:
>>> a, b = 1, 2, 3
ValueError: too many values to unpack
More generally, the right side can be any kind of sequence (string, list or tuple). For
example, to split an email address into a user name and a domain, we could write:
>>> addr = 'monty@python.org'
>>> uname, domain = addr.split('@')
The return value from split is a list with two elements; the first element is assigned to
uname, the second to domain.
>>> uname
'monty'
>>> domain
'python.org'
4.2.2 TUPLE AS RETURN VALUES
A function can only return one value, but if the value is a tuple, the effect is the same as
returning multiple values. For example, if we want to divide two integers and compute the
quotient and remainder, it is inefficient to compute x/y and then x%y. It is better to compute
them both at the same time. The built-in function divmod takes two arguments and returns a
tuple of two values, the quotient and remainder. We can store the result as a tuple:
Example:
>>> t = divmod(7, 3)
>>> t
Ouput:
(2, 1)
Or use tuple assignment to store the elements separately:
Example:
>>> quot, rem = divmod(7, 3)
>>> quot
Output:
2
Example:
>>> rem
Output:
1
Here is an example of a function that returns a tuple:
def min_max(t):
return min(t), max(t)
max and min are built-in functions that find the largest and smallest elements of a
sequence. min_max computes both and returns a tuple of two values.
4.3 DICTIONARIES
Dictionaries have a method called items that returns a sequence of tuples, where each
tuple is a key-value pair.
4.3.1 OPERATIONS AND METHODS
Example:
>>> d = {'a':0, 'b':1, 'c':2}
>>> t = d.items()
>>> t
Output:
dict_items([('c', 2), ('a', 0), ('b', 1)])
The result is a dict_items object, which is an iterator that iterates the key-value pairs. We
can use it in a for loop like this:
Example:
>>> for key, value in d.items():
... print(key, value)
Output:
c2
a0
b1
As we should expect from a dictionary, the items are in no particular order.
Going in the other direction, we can use a list of tuples to initialize a new dictionary:
Example:
>>> t = [('a', 0), ('c', 2), ('b', 1)]
>>> d = dict(t)
>>> d
Output:
{'a': 0, 'c': 2, 'b': 1}
Combining dict with zip yields a concise way to create a dictionary:
Example:
>>> d = dict(zip('abc', range(3)))
>>> d
Output:
{'a': 0, 'c': 2, 'b': 1}
The dictionary method update also takes a list of tuples and adds them, as key-value
pairs, to an existing dictionary. It is common to use tuples as keys in dictionaries (primarily
because we can’t use lists). For example, a telephone directory might map from last-name, first-
name pairs to telephone numbers. Assuming that we have defined last, first and number, we
could write: directory [last, first] = number
The expression in brackets is a tuple. We could use tuple assignment to traverse this
dictionary. For last, first in directory:
print(first, last, directory[last,first])
This loop traverses the keys in directory, which are tuples. It assigns the elements of each
tuple to last and first, then prints the name and corresponding telephone number.

There are two ways to represent tuples in a state diagram. The more detailed version
shows the indices and elements just as they appear in a list. For example, the tuple('Cleese',
'John') would appear as in Figure 4.4. But in a larger diagram we might want to leave out the
details. For example, a diagram of the telephone directory might appear as in Figure 4.5.
Here the tuples are shown using Python syntax as a graphical shorthand. The telephone
number in the diagram is the complaints line for the BBC, so please don’t call it.

4.4 State Diagram


4.5 State Diagram
4.4 ADVANCED LIST PROCESSING
List processing is a list of programming codes, including abstract data structure, used to
calculate specified variables in a certain order. A value may repeat more than once.
4.4.1 LIST COMPREHENSION
The function shown below takes a list of strings, maps the string method capitalize to the
elements, and returns a new list of strings:
def capitalize_all(t):
res = []
for s in t:
res.append(s.capitalize())
return res
We can write this more concisely using a list comprehension:
def capitalize_all(t):
return [s.capitalize() for s in t]
The bracket operators indicate that we are constructing a new list. The expression inside
the brackets specifies the elements of the list, and the ‘for’ clause indicates what sequence we are
traversing.The syntax of a list comprehension is a little awkward because the loop variable, s in
this example, appears in the expression before we get to the definition.
List comprehensions can also be used for filtering. For example, this function selects only
the elements of t that are upper case, and returns a new list:
def only_upper(t):
res = []
for s in t:
if s.isupper():
res.append(s)
return res
We can rewrite it using a list comprehension
def only_upper(t):
return [s for s in t if s.isupper()]
List comprehensions are concise and easy to read, at least for simple expressions. And
they are usually faster than the equivalent for loops, sometimes much faster.
But, list comprehensions are harder to debug because we can’t put a print statement
inside the loop. We can use them only if the computation is simple enough that we are likely to
get it right the first time.
4.5 ILLUSTRATIVE PROGRAMS SELECTION SORT
Selection sort is one of the simplest sorting algorithms. It is similar to the hand picking
where we take the smallest element and put it in the first position and the second smallest at the
second position and so on. It is also similar. We first check for smallest element in the list and
swap it with the first element of the list. Again, we check for the smallest number in a sub list,
excluding the first element of the list as it is where it should be (at the first position) and put it in
the second position of the list. We continue repeating this process until the list gets sorted.
ALGORITHM:
1. Start from the first element in the list and search for the smallest element in the list.
2. Swap the first element with the smallest element of the list.
3. Take a sub list (excluding the first element of the list as it is at its place) and
search for the smallest number in the sub list (second smallest number of the entire list)
and swap it with the first element of the list (second element of the entire list).
4. Repeat the steps 2 and 3 with new subsets until the list gets sorted.
PROGRAM:
a = [16, 19, 11, 15, 10, 12, 14]
i=0
while i<len(a):
#smallest element in the sublist
smallest = min(a[i:])
#index of smallest element
index_of_smallest = a.index(smallest)
#swapping
a[i],a[index_of_smallest] = a[index_of_smallest],a[i]
i=i+1
print (a)
Output
>>>
[10, 11, 12, 14, 15, 16, 19]
4.5.2 INSERTION SORT
Insertion sort is similar to arranging the documents of a bunch of students in order of
their ascending roll number. Starting from the second element, we compare it with the first
element and swap it if it is not in order. Similarly, we take the third element in the next iteration
and place it at the right place in the sub list of the first and second elements (as the sub list
containing the first and second elements is already sorted). We repeat this step with the fourth
element of the list in the next iteration and place it at the right position in the sub list containing
the first, second and the third elements. We repeat this process until our list gets sorted.

ALGORITHM:
1. Compare the current element in the iteration (say A) with the previous adjacent element
to it. If it is in order then continue the iteration else, go to step 2.
2. Swap the two elements (the current element in the iteration (A) and the previous adjacent
element to it).
3. Compare A with its new previous adjacent element. If they are not in order, then proceed
to step 4.
4. Swap if they are not in order and repeat steps 3 and 4.
5. Continue the iteration.
PROGRAM:
a = [16, 19, 11, 15, 10, 12, 14]
#iterating over a
for i in a:
j = a.index(i)
#i is not the first element
while j>0:
#not in order
if a[j-1] > a[j]:
#swap
a[j-1],a[j] = a[j],a[j-1]
else:
#in order
break
j = j-1
print (a)
Output
>>>
[10, 11, 12, 14, 15, 16, 19]
4.5.3 MERGE SORT
Merge Sort is a Divide and Conquer algorithm. It divides input array in two halves, calls
itself for the two halves and then merges the two sorted halves. The merge() function is used for
merging two halves. The merge(arr, l, m, r) is key process that assumes that arr[l..m] and
arr[m+1..r] are sorted and merges the two sorted sub-arrays into one. See following C
implementation for details.
The following diagram shows the complete merge sort process for an example array {38,
27, 43, 3, 9, 82, 10}. If we take a closer look at the diagram, we can see that the array is
recursively divided in two halves till the size becomes 1. Once the size becomes 1, the merge
processes comes into action and starts merging arrays back till the complete array is merged.

ALGORITHM:

MergeSort(arr[], l, r)
If r > l
1. Find the middle point to divide the array into two halves:
middle m = (l+r)/2
2. Call mergeSort for first half:
Call mergeSort(arr, l, m)
3. Call mergeSort for second half:
Call mergeSort(arr, m+1, r)
4. Merge the two halves sorted in step 2 and 3:
Call merge(arr, l, m, r)
PROGRAM:
def mergeSort(alist):
print("Splitting ",alist)
if len(alist)>1:
mid = len(alist)//2
lefthalf = alist[:mid]
righthalf = alist[mid:]
mergeSort(lefthalf)
mergeSort(righthalf)
i=0
j=0
k=0
while i < len(lefthalf) and j < len(righthalf):
if lefthalf[i] < righthalf[j]:
alist[k]=lefthalf[i]
i=i+1
else:
alist[k]=righthalf[j]
j=j+1
k=k+1
while i < len(lefthalf):
alist[k]=lefthalf[i]
i=i+1
k=k+1
while j < len(righthalf):
alist[k]=righthalf[j]
j=j+1
k=k+1
print("Merging ",alist)
n = input("Enter the size of the list: ")
n=int(n);
alist = []
for i in range(n):
alist.append(input("Enter %dth element: "%i))
mergeSort(alist)
print(alist)
Input:
a = [16, 19, 11, 15, 10, 12, 14]
Output:
>>>
[10, 11, 12, 14, 15, 16, 19]
4.5.5 HISTOGRAM
 A histogram is a visual representation of the Distribution of a Quantitative variable.
 Appearance is similar to a vertical bar graph, but used mainly for continuous
distribution
 It approximates the distribution of variable being studied
 A visual representation that gives a discretized display of value counts.
Example:

def histogram(s):
d = dict()
for c in s:
if c not in d:
d[c] = 1
else:
d[c] += 1
return d

The name of the function is histogram, which is a statistical term for a collection of
counters (or frequencies).
The first line of the function creates an empty dictionary. The for loop traverses the
string.Each time through the loop, if the character c is not in the dictionary, we create a new item
with key c and the initial value 1 (since we have seen this letter once). If c is already in the
dictionary we increment d[c]. Here’s how it works:
Example:
>>> h = histogram('brontosaurus')
>>> h
Output:
{'a': 1, 'b': 1, 'o': 2, 'n': 1, 's': 2, 'r': 2, 'u': 2, 't': 1}
The histogram indicates that the letters 'a' and 'b' appear once; 'o' appears twice, and so
on. Dictionaries have a method called get that takes a key and a default value. If the key appears
in the dictionary, get returns the corresponding value; otherwise it returns the default value. For
example:
>>> h = histogram('a')
>>> h
{'a': 1}
>>> h.get('a', 0)
1
>>> h.get('b', 0)
0
As an exercise, use get to write histogram more concisely. We should be able to eliminate
the if statement.
If we use a dictionary in a for statement, it traverses the keys of the dictionary. For
example, print_hist prints each key and the corresponding value:
def print_hist(h):
for c in h:
print(c, h[c])
Here’s what the output looks like:
>>> h = histogram('parrot')
>>> print_hist(h)
a1
p1
r2
t1
o1
Again, the keys are in no particular order. To traverse the keys in sorted order, we can use
the built-in function sorted:
>>> for key in sorted(h):
... print(key, h[key])
a1
o1
p1
r2
t1
Write a function named choose_from_hist that takes a histogram as defined in Histogram
given above and returns a random value from the histogram, chosen with probability in
proportion to frequency. For example, for this histogram:
>>> t = ['a', 'a', 'b']
>>> hist = histogram(t)
>>> hist
{'a': 2, 'b': 1}
The function should return 'a' with probability 2/3 and 'b' with probability 1/3.
TWO MARKS
1. What are elements in a list? Give example.
The values in a list are called elements or items.
A list must be enclosed in square brackets ([and]).
Examples:
>>>[10,20,30]
>>>[‘hi’,’hello’,’welcome’]
2. What is a nested list? Give example.
A list within another list is called nested list.
Example:
[‘good’,10,[100,99]]
3. What is a empty list?
A list that contains no elements is called empty list. It can be created with empty
brackets, [].

4. What is list slicing? Write its syntax.


List slicing is a computationally fast way to methodically access parts of given
data. Syntax:
Listname [start:end:step]
5. What is mutability? What is its use?
Mutability is the ability for certain types of data to be changed without entirely
recreating it. Using mutable data types can allow programs to operate quickly and
efficiently.
6. List any three mutable data types. Give example for mutability.
Example for mutable data types are:
List, Set and Dictionary
Example 1:
>>>numbers=[42,123]
>>>numbers[1]=5
>>>numbers
Output: [42,5]
7. What is aliasing? Give example.
An object with more than one reference has more than one name, so we say that
the object is aliased.
If the aliased object is mutable, changes made with one alias affect the other.
Example:
If a refers to an object and we assign b = a, then both variables refer to the same object:
>>> a = [1, 2, 3]
>>> b = a
>>> b is a True
8. What is the difference between copying and cloning lists?
Copying a list gives it another name but copying a complete slice clones a list.
9. Give example for copying and cloning lists.
Example:
veggies=["potatoes","carrots","pepper","parsnips","swedes","onion","min
ehead"]
veggies[1]="beetroot"
Copying a list
daniel=veggies
CLONES a list
david=veggies[:]
daniel[6]="emu"
10. Define Dictionaries. Give example.
A dictionary is an associative array (also known as hashes). Any key of the
dictionary is associated (or mapped) to a value. The values of a dictionary can be
any Python data type.
Example:
>>> d = {'a':0, 'b':1, 'c':2}
>>> t = d.items()
>>> t
Output:
dict_items([('c', 2), ('a', 0), ('b', 1)])

11. What is list processing?


List processing is a list of programming codes, including abstract data structure,
used to calculate specified variables in a certain order. A value may repeat more than
once.
lOMoARcPSD|36471140

UNIT 5 Python Programming

Python Programming (Chhatrapati Shahu Ji Maharaj University)

Scan to open on Studocu

Studocu is not sponsored or endorsed by any college or university


Downloaded by SK (mspanther1991@gmail.com)
lOMoARcPSD|36471140

UNIT – V
FILES, EXCEPTIONS, MODULES, PACKAGES

Files and exception: text files, reading and writing files, command line arguments,
errors
and exceptions, handling exceptions, modules (datetime, time, OS , calendar, math
module),
Explore packages.
Files, Exceptions, Modules, Packages:
Files and exception:
A file is some information or data which stays in the computer storage devices.
Python gives
you easy ways to manipulate these files. Generally files divide in two categories,
text file and binary file. Text files are simple text where as the binary files contain
binary
data which is only readable by computer.
Text files: In this type of file, Each line of text is terminated with a special
character
called EOL (End of Line), which is the new line character („\n‟) in python by
default.
Binary files: In this type of file, there is no terminator for a line and the data is
stored
after converting it into machine understandable binary language.
An exception is an event, which occurs during the execution of a program that
disrupts the
normal flow of the program's instructions. In general, when a Python script
encounters a
situation that it cannot cope with, it raises an exception. An exception is a Python
object
that represents an error.
Text files:
We can create the text files by using the syntax:
Variable name=open (“file.txt”, file mode)
For ex: f= open ("hello.txt","w+")
We declared the variable f to open a file named hello.txt. Open takes 2
arguments, the
file that we want to open and a string that represents the kinds of permission or
operation we want to do on the file

Downloaded by SK (mspanther1991@gmail.com)
lOMoARcPSD|36471140

Here we used "w" letter in our argument, which indicates write and the plus sign
that
means it will create a file if it does not exist in library

104
The available option beside "w" are "r" for read and "a" for append and plus sign
means if it is not there then create it
File Modes in Python:
Mode Description
'r'
This is the default mode. It Opens file for reading.
'w'
This Mode Opens file for writing.
If file does not exist, it creates a new file.
If file exists it truncates the file.
'x'
Creates a new file. If file already exists, the operation fails.
'a'
Open file in append mode.
If file does not exist, it creates a new file.
't'
This is the default mode. It opens in text mode.
'b'
This opens in binary mode.
'+'
This will open a file for reading and writing (updating)
Reading and Writing files:
The following image shows how to create and open a text file in notepad from
command
prompt

105
(or)
Hit on enter then it shows the following whether to open or not?
Click on “yes” to open else “no” to cancel
# Write a python program to open and read a file
a=open(“one.txt”,”r”)
print(a.read())

Downloaded by SK (mspanther1991@gmail.com)
lOMoARcPSD|36471140

106
a.close()
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-
32/filess/f1.py
welcome to
(or)
Note: All the program files and text files need to saved together in a particular
file then
only the program performs the operations in the given file mode
f.close() ---- This will close the instance of the file somefile.txt stored
# Write a python program to open and write “hello world” into a file?
f=open("1.txt","a")
f.write("hello world")
f.close()
Output:

107
(or)
Note: In the above program the 1.txt file is created automatically and adds
hello world
into txt file
If we keep on executing the same program for more than one time then it append
the data
that many times
# Write a python program to write the content “hi ” for the
existing file.
f=open("1.txt",'w')
f.write("hi ")
f.close()
Output:
In the above program the hello txt file consist of data like

108
But when we try to write some data on to the same file it overwrites and saves with
the
current data (check output)

Downloaded by SK (mspanther1991@gmail.com)
lOMoARcPSD|36471140

# Write a python program to open and write the content to file and read it.
fo=open("abc.txt","w+")
fo.write(" ")
print(fo.read())
fo.close()
Output:
(or)
Note: It creates the abc.txt file automatically and writes the data into it

109
Command line arguments:
The command line arguments must be given whenever we want to give the input
before the
start of the script, while on the other hand, raw_input() is used to get the input
while the
python program / script is running.
The command line arguments in python can be processed by using either „sys‟
module,
„argparse‟ module and „getopt‟ module.
„sys‟ module :
Python sys module stores the command line arguments into a list, we can access it
using sys.argv. This is very useful and simple way to read command line
arguments as
String.
sys.argv is the list of commandline 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 our program
>>> sys.modules.keys() -- this prints so many dict elements in the form of list.
# Python code to demonstrate the use of 'sys' module for command line arguments
import sys
# command line arguments are stored in the form
# of list in sys.argv
argumentList = sys.argv
print(argumentList)
# Print the name of file
print(sys.argv[0])
# Print the first argument after the name of file

Downloaded by SK (mspanther1991@gmail.com)
lOMoARcPSD|36471140

#print(sys.argv[1])
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/cmndlinarg.py
['C:/Users/MRCET/AppData/Local/Programs/Python/Python38-
32/cmndlinarg.py']
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/cmndlinarg.py

110
Note: Since my list consist of only one element at „0‟ index so it prints only that
list
element, if we try to access at index position „1‟ then it shows the error like,
IndexError: list index out of range
------------------
import sys
print(type(sys.argv))
print('The command line arguments are:')
for i in sys.argv:
print(i)
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/symod.py ==
<class 'list'>
The command line arguments are:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/symod.py
# write a python program to get python version.
import sys
print("System version is:")
print(sys.version)
print("Version Information is:")
print(sys.version_info)
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/s1.py =
System version is:
3.8.0 (tags/v3.8.0:fa919fd, Oct 14 2019, 19:21:23) [MSC v.1916 32 bit (Intel)]
Version Information is:
sys.version_info(major=3, minor=8, micro=0, releaselevel='final', serial=0)
„argparse‟ module :
Python getopt module is very similar in working as the C getopt() function for
parsing

Downloaded by SK (mspanther1991@gmail.com)
lOMoARcPSD|36471140

command-line parameters. Python getopt module is useful in parsing command


line
arguments where we want user to enter some options too.
>>> parser = argparse.ArgumentParser(description='Process some integers.')
#---------

111
import argparse
parser = argparse.ArgumentParser()
print(parser.parse_args())
„getopt‟ module :
Python argparse module is the preferred way to parse command line arguments. It
provides a
lot of option such as positional arguments, default value for arguments, help
message,
specifying data type of argument etc
It parses the command line options and parameter list. The signature of this
function is
mentioned below:
getopt.getopt(args, shortopts, longopts=[ ])
args are the arguments to be passed.
shortopts is the options this script accepts.
Optional parameter, longopts is the list of String parameters this function accepts
which should be supported. Note that the -- should not be prepended with option
names.
-h --------- print help and usage message
-m --------- accept custom option value
-d --------- run the script in debug mode
import getopt
import sys
argv = sys.argv[0:]
try:
opts, args = getopt.getopt(argv, 'hm:d', ['help', 'my_file='])
#print(opts)
print(args)
except getopt.GetoptError:
# Print a message or do something useful
print('Something went wrong!')
sys.exit(2)

Downloaded by SK (mspanther1991@gmail.com)
lOMoARcPSD|36471140

112
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/gtopt.py ==
['C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/gtopt.py']
Errors and Exceptions:
Python Errors and Built-in Exceptions: Python (interpreter) raises exceptions
when it
encounters errors. When writing a program, we, more often than not, will
encounter errors. Error caused by not following the proper structure (syntax) of the
language
is called syntax error or parsing error
ZeroDivisionError:
ZeroDivisionError in Python indicates that the second argument used in a division
(or
modulo) operation was zero.
OverflowError:
OverflowError in Python indicates that an arithmetic operation has exceeded the
limits of
the current Python runtime. This is typically due to excessively large float values,
as integer
values that are too big will opt to raise memory errors instead.
ImportError:
It is raised when you try to import a module which does not exist. This may happen
if you
made a typing mistake in the module name or the module doesn't exist in its
standard path.
In the example below, a module named "non_existing_module" is being imported
but it
doesn't exist, hence an import error exception is raised.
IndexError:
An IndexError exception is raised when you refer a sequence which is out of range.
In the
example below, the list abc contains only 3 entries, but the 4th index is being
accessed,
which will result an IndexError exception.
TypeError:
When two unrelated type of objects are combined, TypeErrorexception is raised.In
example

Downloaded by SK (mspanther1991@gmail.com)
lOMoARcPSD|36471140

below, an int and a string is added, which will result in TypeError exception.

113
IndentationError:
Unexpected indent. As mentioned in the "expected an indentedblock" section,
Python not
only insists on indentation, it insists on consistentindentation. You are free to
choose the
number of spaces of indentation to use, but you then need to stick with it.
Syntax errors:
These are the most basic type of error. They arise when the Python parser is unable
to
understand a line of code. Syntax errors are almost always fatal, i.e. there is almost
never a
way to successfully execute a piece of code containing syntax errors.
Run-time error:
A run-time error happens when Python understands what you are saying, but runs
into
trouble when following your instructions.
Key Error :
Python raises a KeyError whenever a dict() object is requested (using the
format a = adict[key]) and the key is not in the dictionary.
Value Error:
In Python, a value is the information that is stored within a certain object. To
encounter a
ValueError in Python means that is a problem with the content of the object you
tried to
assign the value to.
Python has many built-in exceptions which forces your program to output an
error when
something in it goes wrong. In Python, users can define such exceptions by
creating a new
class. This exception class has to be derived, either directly or indirectly,
from Exception class.
Different types of exceptions:
ArrayIndexOutOfBoundException.
ClassNotFoundException.
FileNotFoundException.
IOException.

Downloaded by SK (mspanther1991@gmail.com)
lOMoARcPSD|36471140

InterruptedException.
NoSuchFieldException.
NoSuchMethodException

114
Handling Exceptions:
The cause of an exception is often external to the program itself. For example, an
incorrect
input, a malfunctioning IO device etc. Because the program abruptly terminates on
encountering an exception, it may cause damage to system resources, such as files.
Hence,
the exceptions should be properly handled so that an abrupt termination of the
program is
prevented.
Python uses try and except keywords to handle exceptions. Both keywords are
followed by
indented blocks.
Syntax:
try :
#statements in try block
except :
#executed when error in try block
Typically we see, most of the times
Syntactical errors (wrong spelling, colon ( : ) missing ….),
At developer level and compile level it gives errors.
Logical errors (2+2=4, instead if we get output as 3 i.e., wrong output …..,),
As a developer we test the application, during that time logical error may obtained.
Run time error (In this case, if the user doesn‟t know to give input, 5/6 is ok but
if
the user say 6 and 0 i.e.,6/0 (shows error a number cannot be divided by zero))
This is not easy compared to the above two errors because it is not done by the
system, it is (mistake) done by the user.
The things we need to observe are:
1. You should be able to understand the mistakes; the error might be done by user,
DB
connection or server.
2. Whenever there is an error execution should not stop.
Ex: Banking Transaction
3. The aim is execution should not stop even though an error occurs.

Downloaded by SK (mspanther1991@gmail.com)
lOMoARcPSD|36471140

115
For ex:
a=5
b=2
print(a/b)
print("Bye")
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/ex1.py
2.5
Bye
The above is normal execution with no error, but if we say when b=0, it is a
critical and gives error, see below
a=5
b=0
print(a/b)
print("bye") #this has to be printed, but abnormal termination
Output:
Traceback (most recent call last):
File "C:/Users/MRCET/AppData/Local/Programs/Python/Python38-
32/pyyy/ex2.py", line
3, in <module>
print(a/b)
ZeroDivisionError: division by zero
To overcome this we handle exceptions using except keyword
a=5
b=0

116
try:
print(a/b)
except Exception:
print("number can not be divided by zero")
print("bye")
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/ex3.py
number can not be divided by zero
bye

Downloaded by SK (mspanther1991@gmail.com)
lOMoARcPSD|36471140

The except block executes only when try block has an error, check it below
a=5
b=2
try:
print(a/b)
except Exception:
print("number can not be divided by zero")
print("bye")
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/ex4.py
2.5
For example if you want to print the message like what is an error in a
program
then we use “e” which is the representation or object of an exception.
a=5
b=0
try:

117
print(a/b)
except Exception as e:
print("number can not be divided by zero",e)
print("bye")
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/ex5.py
number can not be divided by zero division by zero
bye
(Type of error)
Let us see some more examples:
I don‟t want to print bye but I want to close the file whenever it is opened.
a=5
b=2
try:
print("resource opened")
print(a/b)
print("resource closed")
except Exception as e:
print("number can not be divided by zero",e)
Output:

Downloaded by SK (mspanther1991@gmail.com)
lOMoARcPSD|36471140

C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/ex6.py
resource opened
2.5
resource closed

118
Note: the file is opened and closed well, but see by changing the value of b to
0,
a=5
b=0
try:
print("resource opened")
print(a/b)
print("resource closed")
except Exception as e:
print("number can not be divided by zero",e)
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/ex7.py
resource opened
number can not be divided by zero division by zero
Note: resource not closed
To overcome this, keep print(“resource closed”) in except block, see it
a=5
b=0
try:
print("resource opened")
print(a/b)
except Exception as e:
print("number can not be divided by zero",e)
print("resource closed")
Output:

119
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/ex8.py
resource opened
number can not be divided by zero division by zero
resource closed

Downloaded by SK (mspanther1991@gmail.com)
lOMoARcPSD|36471140

The result is fine that the file is opened and closed, but again change the
value of
b to back (i.e., value 2 or other than zero)
a=5
b=2
try:
print("resource opened")
print(a/b)
except Exception as e:
print("number can not be divided by zero",e)
print("resource closed")
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/ex9.py
resource opened
2.5
But again the same problem file/resource is not closed
To overcome this python has a feature called finally:
This block gets executed though we get an error or not
Note: Except block executes, only when try block has an error, but finally
block
executes, even though you get an exception.
a=5
b=0
try:

120
print("resource open")
print(a/b)
k=int(input("enter a number"))
print(k)
except ZeroDivisionError as e:
print("the value can not be divided by zero",e)
finally:
print("resource closed")
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/ex10.py
resource open
the value can not be divided by zero division by zero
resource closed

Downloaded by SK (mspanther1991@gmail.com)
lOMoARcPSD|36471140

change the value of b to 2 for above program, you see the output like
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/ex10.py
resource open
2.5
enter a number 6
6
resource closed
Instead give input as some character or string for above program, check the
output
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/ex10.py
resource open
2.5
enter a number p
resource closed
Traceback (most recent call last):
File "C:/Users/MRCET/AppData/Local/Programs/Python/Python38-
32/pyyy/ex10.py", line
7, in <module>
k=int(input("enter a number"))
ValueError: invalid literal for int() with base 10: ' p'

121
#--------------------
a=5
b=0
try:
print("resource open")
print(a/b)
k=int(input("enter a number"))
print(k)
except ZeroDivisionError as e:
print("the value can not be divided by zero",e)
except ValueError as e:
print("invalid input")
except Exception as e:
print("something went wrong...",e)
finally:
print("resource closed")
Output:

Downloaded by SK (mspanther1991@gmail.com)
lOMoARcPSD|36471140

C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/ex11.py
resource open
the value can not be divided by zero division by zero
resource closed
Change the value of b to 2 and give the input as some character or string
(other
than int)
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/ex12.py
resource open
2.5
enter a number p
invalid input
resource closed
Modules (Date, Time, os, calendar, math):
• Modules refer to a file containing Python statements and definitions.

122
• We use modules to break down large programs into small manageable and
organized
files. Furthermore, modules provide reusability of code.
• We can define our most used functions in a module and import it, instead of
copying
their definitions into different programs.
• Modular programming refers to the process of breaking a large, unwieldy
programming task into separate, smaller, more manageable subtasks or modules.
Advantages :
• Simplicity: Rather than focusing on the entire problem at hand, a module
typically
focuses on one relatively small portion of the problem. If you‟re working on a
single
module, you‟ll have a smaller problem domain to wrap your head around. This
makes
development easier and less error-prone.
• Maintainability: Modules are typically designed so that they enforce logical
boundaries between different problem domains. If modules are written in a way
that
minimizes interdependency, there is decreased likelihood that modifications to a
single module will have an impact on other parts of the program. This makes it
more

Downloaded by SK (mspanther1991@gmail.com)
lOMoARcPSD|36471140

viable for a team of many programmers to work collaboratively on a large


application.
• Reusability: Functionality defined in a single module can be easily reused
(through
an appropriately defined interface) by other parts of the application. This
eliminates
the need to recreate duplicate code.
• Scoping: Modules typically define a separate namespace, which helps avoid
collisions between identifiers in different areas of a program.
• Functions, modules and packages are all constructs in Python that promote code
modularization.
A file containing Python code, for e.g.: example.py, is called a module and its
module name
would be example.
>>> def add(a,b):
result=a+b
return result
"""This program adds two numbers and return the result""“

123
Here, we have defined a function add() inside a module named example. The
function takes
in two numbers and returns their sum.
How to import the module is:
• We can import the definitions inside a module to another module or the
Interactive
interpreter in Python.
• We use the import keyword to do this. To import our previously defined
module example we type the following in the Python prompt.
• Using the module name we can access the function using dot (.) operation. For
Eg:
>>> import example
>>> example.add(5,5)
10
• Python has a ton of standard modules available. Standard modules can be
imported
the same way as we import our user-defined modules.
Reloading a module:
def hi(a,b):

Downloaded by SK (mspanther1991@gmail.com)
lOMoARcPSD|36471140

print(a+b)
hi(4,4)
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/add.py
8
>>> import add
8

124
>>> import add
>>> import add
>>>
Python provides a neat way of doing this. We can use the reload() function inside
the imp module to reload a module. This is how its done.
• >>> import imp
• >>> import my_module
• This code got executed >>> import my_module >>> imp.reload(my_module)
This
code got executed <module 'my_module' from '.\\my_module.py'>how its done.
>>> import imp
>>> import add
>>> imp.reload(add)
8
<module 'add' from
'C:/Users/MRCET/AppData/Local/Programs/Python/Python38-
32/pyyy\\add.py'>
The dir() built-in function
>>> import example
>>> dir(example)
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__',
'__package__',
'__spec__', 'add']
>>> dir()
['__annotations__', '__builtins__', '__doc__', '__file__', '__loader__', '__name__',
'__package__', '__spec__', '__warningregistry__', 'add', 'example', 'hi', 'imp']
It shows all built-in and user-defined modules.
For ex:

125

Downloaded by SK (mspanther1991@gmail.com)
lOMoARcPSD|36471140

>>> example.__name__
'example'
Datetime module:
# Write a python program to display date, time
>>> import datetime
>>> a=datetime.datetime(2019,5,27,6,35,40)
>>> a
datetime.datetime(2019, 5, 27, 6, 35, 40)
# write a python program to display date
import datetime
a=datetime.date(2000,9,18)
print(a)
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/d1.py =
2000-09-18
# write a python program to display time
import datetime
a=datetime.time(5,3)
print(a)
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/d1.py =
05:03:00
#write a python program to print date, time for today and now.
import datetime

126
a=datetime.datetime.today()
b=datetime.datetime.now()
print(a)
print(b)
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/d1.py =
2019-11-29 12:49:52.235581
2019-11-29 12:49:52.235581
#write a python program to add some days to your present date and print the
date
added.
import datetime
a=datetime.date.today()

Downloaded by SK (mspanther1991@gmail.com)
lOMoARcPSD|36471140

b=datetime.timedelta(days=7)
print(a+b)
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/d1.py =
2019-12-06
#write a python program to print the no. of days to write to reach your
birthday
import datetime
a=datetime.date.today()
b=datetime.date(2020,5,27)
c=b-a
print(c)
Output:

127
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/d1.py =
180 days, 0:00:00
#write an python program to print date, time using date and time functions
import datetime
t=datetime.datetime.today()
print(t.date())
print(t.time())
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/d1.py =
2019-11-29
12:53:39.226763
Time module:
#write a python program to display time.
import time
print(time.time())
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/t1.py =
1575012547.1584706
#write a python program to get structure of time stamp.
import time
print(time.localtime(time.time()))
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/t1.py =

Downloaded by SK (mspanther1991@gmail.com)
lOMoARcPSD|36471140

128
time.struct_time(tm_year=2019, tm_mon=11, tm_mday=29, tm_hour=13,
tm_min=1,
tm_sec=15, tm_wday=4, tm_yday=333, tm_isdst=0)
#write a python program to make a time stamp.
import time
a=(1999,5,27,7,20,15,1,27,0)
print(time.mktime(a))
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/t1.py =
927769815.0
#write a python program using sleep().
import time
time.sleep(6) #prints after 6 seconds
print("Python Lab")
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/t1.py =
Python Lab (#prints after 6 seconds)
os module:
>>> import os
>>> os.name
'nt'
>>> os.getcwd()
'C:\\Users\\MRCET\\AppData\\Local\\Programs\\Python\\Python38-32\\pyyy'
>>> os.mkdir("temp1")

129
Note: temp1 dir is created
>>> os.getcwd()
'C:\\Users\\MRCET\\AppData\\Local\\Programs\\Python\\Python38-32\\pyyy'
>>> open("t1.py","a")
<_io.TextIOWrapper name='t1.py' mode='a' encoding='cp1252'>
>>> os.access("t1.py",os.F_OK)
True
>>> os.access("t1.py",os.W_OK)
True
>>> os.rename("t1.py","t3.py")
>>> os.access("t1.py",os.F_OK)
False

Downloaded by SK (mspanther1991@gmail.com)
lOMoARcPSD|36471140

>>> os.access("t3.py",os.F_OK)
True
>>> os.rmdir('temp1')
(or)
os.rmdir('C:/Users/MRCET/AppData/Local/Programs/Python/Python38-
32/pyyy/temp1')

130
Note: Temp1dir is removed
>>> os.remove("t3.py")
Note: We can check with the following cmd whether removed or not
>>> os.access("t3.py",os.F_OK)
False
>>> os.listdir()
['add.py', 'ali.py', 'alia.py', 'arr.py', 'arr2.py', 'arr3.py', 'arr4.py', 'arr5.py', 'arr6.py',
'br.py',
'br2.py', 'bubb.py', 'bubb2.py', 'bubb3.py', 'bubb4.py', 'bubbdesc.py', 'clo.py',
'cmndlinarg.py',
'comm.py', 'con1.py', 'cont.py', 'cont2.py', 'd1.py', 'dic.py', 'e1.py', 'example.py',
'f1.y.py',
'flowof.py', 'fr.py', 'fr2.py', 'fr3.py', 'fu.py', 'fu1.py', 'if1.py', 'if2.py', 'ifelif.py',
'ifelse.py',
'iff.py', 'insertdesc.py', 'inserti.py', 'k1.py', 'l1.py', 'l2.py', 'link1.py', 'linklisttt.py',
'lis.py',
'listlooop.py', 'm1.py', 'merg.py', 'nesforr.py', 'nestedif.py', 'opprec.py', 'paraarg.py',
'qucksort.py', 'qukdesc.py', 'quu.py', 'r.py', 'rec.py', 'ret.py', 'rn.py', 's1.py',
'scoglo.py',
'selecasce.py', 'selectdecs.py', 'stk.py', 'strmodl.py', 'strr.py', 'strr1.py', 'strr2.py',
'strr3.py',
'strr4.py', 'strrmodl.py', 'wh.py', 'wh1.py', 'wh2.py', 'wh3.py', 'wh4.py', 'wh5.py',
'__pycache__']
>>> os.listdir('C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32')
['argpar.py', 'br.py', 'bu.py', 'cmndlinarg.py', 'DLLs', 'Doc', 'f1.py', 'f1.txt', 'filess',
'functupretval.py', 'funturet.py', 'gtopt.py', 'include', 'Lib', 'libs', 'LICENSE.txt',
'lisparam.py',
'mysite', 'NEWS.txt', 'niru', 'python.exe', 'python3.dll', 'python38.dll', 'pythonw.exe',
'pyyy',
'Scripts', 'srp.py', 'sy.py', 'symod.py', 'tcl', 'the_weather', 'Tools', 'tupretval.py',
'vcruntime140.dll']

Downloaded by SK (mspanther1991@gmail.com)
lOMoARcPSD|36471140

Calendar module:

131
#write a python program to display a particular month of a year using
calendar
module.
import calendar
print(calendar.month(2020,1))
Output:
# write a python program to check whether the given year is leap or not.
import calendar
print(calendar.isleap(2021))
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/cl1.py
False
#write a python program to print all the months of given year.
import calendar
print(calendar.calendar(2020,1,1,1))
Output:

132
math module:
# write a python program which accepts the radius of a circle from user and
computes
the area.
import math
r=int(input("Enter radius:"))
area=math.pi*r*r
print("Area of circle is:",area)
Output:

133
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/m.py =
Enter radius:4
Area of circle is: 50.26548245743669
>>> import math
>>> print("The value of pi is", math.pi)
O/P: The value of pi is 3.141592653589793

Downloaded by SK (mspanther1991@gmail.com)
lOMoARcPSD|36471140

Import with renaming:


• We can import a module by renaming it as follows.
• For Eg:
>>> import math as m
>>> print("The value of pi is", m.pi)
O/P: The value of pi is 3.141592653589793
• We have renamed the math module as m. This can save us typing time in some
cases.
• Note that the name math is not recognized in our scope. Hence, math.pi is
invalid, m.pi is the correct implementation.
Python from...import statement:
• We can import specific names from a module without importing the module as a
whole. Here is an example.
>>> from math import pi
>>> print("The value of pi is", pi)
O/P: The value of pi is 3.141592653589793
• We imported only the attribute pi from the module.
• In such case we don't use the dot operator. We could have imported multiple
attributes
as follows.

134
>>> from math import pi, e
>>> pi
3.141592653589793
>>> e
2.718281828459045
Import all names:
• We can import all names(definitions) from a module using the following
construct.
>>>from math import *
>>>print("The value of pi is", pi)
• We imported all the definitions from the math module. This makes all names
except
those beginnig with an underscore, visible in our scope.
Explore packages:
• We don't usually store all of our files in our computer in the same location. We
use a
well-organized hierarchy of directories for easier access.

Downloaded by SK (mspanther1991@gmail.com)
lOMoARcPSD|36471140

• Similar files are kept in the same directory, for example, we may keep all the
songs in
the "music" directory. Analogous to this, Python has packages for directories
and modules for files.
• As our application program grows larger in size with a lot of modules, we place
similar modules in one package and different modules in different packages. This
makes a project (program) easy to manage and conceptually clear.
• Similar, as a directory can contain sub-directories and files, a Python package can
have sub-packages and modules.
• A directory must contain a file named __init__.py in order for Python to consider
it as
a package. This file can be left empty but we generally place the initialization code
for
that package in this file.
• Here is an example. Suppose we are developing a game, one possible
organization of
packages and modules could be as shown in the figure below.

135
• If a file named __init__.py is present in a package directory, it is invoked when
the
package or a module in the package is imported. This can be used for execution of
package initialization code, such as initialization of package-level data.
• For example __init__.py
• A module in the package can access the global by importing it in turn
• We can import modules from packages using the dot (.) operator.
• For example, if want to import the start module in the above example, it is done
as
follows.
• import Game.Level.start
• Now if this module contains a function named select_difficulty(), we must use
the
full name to reference it.
• Game.Level.start.select_difficulty(2)
136
• If this construct seems lengthy, we can import the module without the package
prefix
as follows.
• from Game.Level import start

Downloaded by SK (mspanther1991@gmail.com)
lOMoARcPSD|36471140

• We can now call the function simply as follows.


• start.select_difficulty(2)
• Yet another way of importing just the required function (or class or variable)
form a
module within a package would be as follows.
• from Game.Level.start import select_difficulty
• Now we can directly call this function.
• select_difficulty(2)
Examples:
#Write a python program to create a package (II YEAR),sub
package(CSE),modules(student) and create read and write function to module
def read():
print("Department")
def write():
print("Student")
Output:
>>> from IIYEAR.CSE import student
>>> student.read()
Department
>>> student.write()
Student
>>> from IIYEAR.CSE.student import read
>>> read

137
<function read at 0x03BD1070>
>>> read()
Department
>>> from IIYEAR.CSE.student import write
>>> write()
Student
# Write a program to create and import module?
def add(a=4,b=6):
c=a+b
return c
Output:
C:\Users\MRCET\AppData\Local\Programs\Python\Python38-
32\IIYEAR\modu1.py
>>> from IIYEAR import modu1

Downloaded by SK (mspanther1991@gmail.com)
lOMoARcPSD|36471140

>>> modu1.add()
10
# Write a program to create and rename the existing module.
def a():
print("hello world")
a()
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-
32/IIYEAR/exam.py
hello world
>>> import exam as ex
hello world

Downloaded by SK (mspanther1991@gmail.com)

You might also like