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

21cs15it Python

Uploaded by

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

21cs15it Python

Uploaded by

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

21CS15IT

PROBLEM SOLVING AND PYTHON


PROGRAMMING

VEL TECH HIGH TECH


Dr.Rangarajan Dr.Sakunthala Engineering College
An Autonomous Institution
Approved by AICTE - New Delhi
Affiliated to Anna University - Chennai
VEL TECH HIGH TECH
Dr. RANGARAJAN Dr. SAKUNTHALA ENGINEERING COLLEGE
An Autonomous Institution

Approved by AICTE-New Delhi, Affiliated to Anna University, Chennai


Accredited by NBA, New Delhi & Accredited by NAAC with “A” Grade & CGPA of 3.27

Course code 21CS15IT Semester I


Category ENGINEERING SCIENCE COURSE (ESC) L T P C
PROBLEM SOLVING AND PYTHON
Course Title PROGRAMMING 2 0 4 4
(COMMON FOR ALL BRANCHES)

COURSE OBJECTIVES:
 To be familiar with the basics of algorithmic problem solving.
 To construct python programs with conditionals, loops and functions.
 To use python data structures-Lists, Tuples and Dictionaries.
PREREQUISITE:
 Basic Mathematics Skills and Computer Knowledge
COURSE OUTCOMES:
Blooms
CO. No. Course Outcomes level
At the end of the course students will be able to
C105. 1 Develop algorithmic solutions to simple computational K3
problems
C105. 2 Construct simple Python programs for solving problems. K3
C105. 3 Build Python programs with conditionals and loops. K3
C105. 4 Demonstrate a Python program into functions. K2
Show compound data using Python lists, tuples, and
C105. 5 dictionaries. K2
C105. 6 Read and write data from/to files in Python Programs. K3

COURSE OUTCOMES MAPPING WITH PROGRAM OUTCOMES AND PROGRAM SPECIFIC OUTCOMES

CO No. PO-1 PO-2 PO-3 PO-4 PO-5 PO-6 PO-7 PO-8 PO-9 PO-10 PO-11 PO-12 PSO-1 PSO-2

C105. 1 3 2 1 - - - - - - - - - 2 2
C105. 2 3 2 1 - - - - - - - - - 2 2
C105. 3 3 2 1 - - - - - - - - - 2 2
C105. 4 3 2 1 - - - - - - - - - 2 2
C105. 5 3 2 1 - - - - - - - - - 2 2
C105. 6 3 2 1 - - - - - - - - - 2 2
C105 3 2 1 - - - - - - - - - 2 2
Note: 1: Slight, 2: Moderate, 3: Substantial
1
SYLLABUS No. of Credits: 4
UNIT- I ALGORITHMIC PROBLEM SOLVING AND BASICS OF PYTHON 8
Algorithms-building blocks of algorithms (statements, state, control flow, functions), simple
Strategies for developing algorithms (iteration, recursion)-pseudo code- flow chart-programming
language. Introduction to Python-Features of Python-Python Interpreter: Interactive and script
mode- Values and types, variables, Keywords, Identifiers, operators, precedence of operators,
expression, Comments.

UNIT-II CONTROL FLOW, FUNCTIONS 8

Conditional statements-Iterative statements, Functions: Built-in functions, user defined function-


Function Arguments-Fruitful functions and void functions- local and global variable - function
composition- recursion-Lambda Functions.

UNIT-III MODULES, PACKAGES, STRINGS 4

Modules-Packages-Strings-string operations, string functions and methods.

UNIT-IV LISTS, TUPLES, DICTIONARIES 5

Lists- list operations, list methods, list loop, mutability, aliasing, cloning lists-Tuples-Tuple
assignment, Operations on Tuples, Tuple as return value- Dictionaries- operations and methods-
Sets-Operations on sets.

UNIT-V FILES AND EXCEPTIONS 5


Files –Types of files, file operations, file methods, format operator-command line arguments-
Errors and Exceptions, handling exceptions.

List of Experiments: 30 Periods


1. Write a python program to demonstrate basic data types in python.
2. Write a python program using conditional statements.
3. Write a python program using Iterative statements.
4. Write a python program using built-in and user defined functions.
5. Write a python program using lambda functions and recursions.
6. Write a python program to demonstrate Strings and its Operations.
7. Write a python program to demonstrate lists, tuples and its operations.
8. Write a python program to demonstrate Sets and its operations.
9. Write a python program to demonstrate Dictionaries and its operations.
10. Write a python program to demonstrate Files and its Operations.
30 Periods

Total: 60 Periods

2
LEARNING RESOURCES:

TEXT BOOKS:
1. Reema Thareja, “Python Programming using Problem Solving Approach”, OXFORD
University Press, 2017.
2. Allen B. Downey, ``Think Python: How to Think Like a Computer Scientist‘‘, 2nd edition,
Updated for Python 3, Shroff/O‘Reilly Publishers, 2016.

REFERENCES:

1. Ashok Namdev Kamthane, Amit Ashok Kamthane, “Programming and Problem Solving with
Python”, Mc-Graw Hill Education, 2018.
2. Robert Sedgewick, Kevin Wayne, Robert Dondero, “Introduction to Programming in Python:
An Inter-disciplinary Approach, Pearson India Education Services Pvt. Ltd, 2016.
3. Kenneth A. Lambert, “Fundamentals of Python: First Programs”, CENGAGE Learning, 2012.

Required numbers
Sl. No. Description of Equipment (For batch of 30 students)

1 Standalone desktops with Python [Open Source] 30 Nos

3
21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING

UNIT- I
ALGORITHMIC PROBLEM SOLVING AND BASICS OF PYTHON 8

Algorithms- building blocks of algorithms (statements, state, control flow, functions),


simple Strategies for developing algorithms (iteration, recursion)-pseudo code- flow
chart-programming language. Introduction to Python-Features of Python-Python
Interpreter: Interactive and script mode- Values and types, variables, Keywords,
Identifiers, operators, precedence of operators, expression, Comments.

 ALGORITHM

It is defined as a sequence of instructions that describe a method for solving a


problem. In other words it is a step by step procedure for solving a problem

Input algorithm Output

Properties of Algorithms
 Should be written in simple English
 Each and every instruction should be precise and unambiguous.
 Instructions in an algorithm should not be repeated infinitely.
 Algorithm should conclude after a finite number of steps.
 Should have an endpoint
 Derived results should be obtained only after the algorithm terminates.
Qualities of a good algorithm
The following are the primary factors that are often used to judge the quality of the
algorithms.
Time – To execute a program, the computer system takes some amount of time. The lesser is
the time required, the better is the algorithm.
Memory – To execute a program, computer system takes some amount of memory space.
The lesser is the memory required, the better is the algorithm.
Accuracy – Multiple algorithms may provide suitable or correct solutions to a given
problem, some of these may provide more accurate results than others, and such algorithms
may be suitable.
Example:
Example
Write an algorithm to print “PSPP”
Step 1: Start
Step 2: Print “PSPP”
Step 3: Stop
Algorithmic problem solving is solving problem that require the formulation of an algorithm for the solution. Algorithmic
problem solving means solving the problem by means of algorithm.
Understanding the Problem
The problem given should be understood completely. Check if it is similar to some standard
problems & if a Known algorithm exists. Otherwise a new algorithm has to be developed It is
the process of finding the input of the problem that the algorithm solves.
VEL TECH HIGH TECH DR.RANGARAJAN DR.SAKUNTHALA ENGINEERING COLLEGE
1
21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING

Ascertaining the Capabilities of the Computational Device


Once a problem is understood, we need to know the capabilities of the computing device this can
be done by knowing the type of the architecture, speed & memory availability.
Choosing between Exact and Approximate Problem Solving
Once algorithm is developed, it is necessary to show that it computes answer for all the
possible legal inputs. The solution is stated in two forms, exact solution or approximate
solution. Examples of problems where an exact solution cannot be obtained are i) Finding a
square root of number. ii) Solutions of nonlinear equations.
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
BUILDING BLOCKS OF ALGORITHMS (statements, state,
control flow, functions)
The building blocks of algorithm refer to the blocks such as statements, state, control flow
structures, functions, etc that are used to develop algorithms

Building blocks of algorithms:


The following are the various building blocks of algorithms:
Statements
State
Control flow
Functions
1. 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

2. State:
Transition from one process to another process under specified condition with in a
time is called state. State is the information that the program manipulates to accomplish
VEL TECH HIGH TECH DR.RANGARAJAN DR.SAKUNTHALA ENGINEERING COLLEGE
2
21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING

some task. It is data or information that gets changed or manipulated throughout the runtime
of a program. The state of an algorithm is defined as its condition regarding stored data.
Example: state refers to the set of variables and the values to which they refer.

3. Control flow:
The process of executing the individual statements in a given order is called control flow.
Control flow is the order that instructions are executed in a program .A control statement is a
statement that determines the control flow of a set of instructions
The control can be executed in three ways
1. sequence
2. selection
3. Iteration
Sequence:
All the instructions are executed one after another is called sequence execution.
Pseudo code Flowchart
BEGIN
statement
Statement Action1
END
Action2

Example:
Step 1: Start
Step 2: Get x,y
Step 3: Calculate sum=x+y
Step 4: Display sum
Step 5: Stop

Selection:
It is provided by a control statement that selectively executes instructions. The selection
structure allows the programs to make a choice between two alternate paths, whether it is true
or false. These statements are known as conditional or decision making or selection
statements or branching statements.
Iteration:
Iteration is a process of executing the set of instructions repeatedly till the condition in
iteration statement becomes false. The iteration statement includes the initialization,
comparison, execution of the statements inside the iteration statement and finally the updating
of the control variable. After the control variable is updated it is compared again, and the
process repeats itself, till the condition in iteration statement turns out to be false.

VEL TECH HIGH TECH DR.RANGARAJAN DR.SAKUNTHALA ENGINEERING COLLEGE


3
21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING

4. 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:
Function: piece of prewritten code that performs an operation
print function: displays output on the screen
Argument: data given to a function
Example: data that is printed to screen
Types of functions/categories of functions:
Pre-defined functions-built in functions provided by programming languages Example: print() in
python
User-defined functions-created by user. Example fact()
Pseudo code:
BEGIN BEGINPROCEDURE
CALLPROCEDURE statement1
END statement2
END PROCEDURE
 SIMPLE STRATEGIES FOR DEVELOPING ALGORITHMS:
The following strategies are used for developing algorithms:
Iteration:
Iteration is a process of executing the set of instructions repeatedly till the condition in
VEL TECH HIGH TECH DR.RANGARAJAN DR.SAKUNTHALA ENGINEERING COLLEGE
4
21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING

iteration statement becomes false. The iteration statement includes the initialization,
comparison, execution of the statements inside the iteration statement and finally the
updating of the control variable. After the control variable is updated it is compared again,
and the process repeats itself, till the condition in iteration statement turns out to be false.
1. for loop
2. While loop
Advantages:
 The iteration statement does not use a stack to store the variables. Hence, the execution
of the iteration statement is faster as compared to recursive function.
 Even the iteration function does not have the overhead of repeated function calling which
also make its execution faster than recursive function.
Disadvantages:
 The iteration is terminated when the control condition becomes false. The absence of
control condition in iteration statement may result in an infinite loop, or it may cause a
compilation error.
Example:
Problem: To find the factorial of a number (using While loop)
Description: factorial of a number n!=n*(n-1)! Where n is the number for which factorial
is to be calculated
Solution: The algorithm, pseudo code and flowchart are as follows:
Algorithm
step 1. Start
step 2. Read the number n step 3. Initialize i=1,
fact=1
step 4. Repeat step 4 through 6 until i<=n
step 5. fact =fact*i
step 6. i=i+1 step 7. Print fact step
8. Stop

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.
 Recursion is a programming technique that comes from recurrence relation, where
the problem is divided further in sub problems smaller in size but same in nature.
 This division stops when the problem cannot be divided further.
 This point is called base case from where control moves back towards the original
problem by solving sub problems and assembling results in order to get the final
result.
Advantages: The main advantage recursion provides to programmers is that it takes less code
to write comparative to iterative version. The code written with help of recursion is more
VEL TECH HIGH TECH DR.RANGARAJAN DR.SAKUNTHALA ENGINEERING COLLEGE
5
21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING

concise, cleaner and easier to understand.

There are some data structures you will see which are quite easy to code with help of recursion.
Tree traversals, quick, and merge sort are a few examples.
Disadvantages: Recursion provides no storage saving, nor time.

 PSEUDO CODE
Pseudo code derived from ‘pseudo’ which means imitation and ‘code’ means instruction
is a generic way of describing an algorithm without using any specific programming language
related notations. Pseudo code is an artificial and informal language that helps programmers to
develop algorithms. Pseudo code can be defined as the narrative description of the flow and
logic of the intended program, written in plain language that expresses each step of the
algorithm. The pseudo code is also called as Program design language (PDL)
Characteristics/properties of Pseudo code:

 It is a “text based” detail (algorithmic) design tool.


 Pseudo code generally consists of short English phrases to express a specifictask
 Consists of natural language-like statements that precisely describe the steps of an
algorithm or program
 Statements describe actions
 Focuses on the logic of the algorithm or program
 Avoids language-specific elements

Guidelines for developing Pseudo code:


The general guidelines for developing pseudo codes are :
• Statements should be written in English and should be programming language independent.
• Steps of the pseudo codes must be understandable.
• It should be concise.
• Each instruction should be written in a separate list and each statement in pseudo code
should express just one action for the computer.
• The keywords like READ, PRINT etc should be written in capital letter.
Pseudo code Language Constructs
The Commonly used keywords Start:
START,BEGIN
STOP:END
Input: READ, OBTAIN, GET, USERINPUT
Output: PRINT, DISPLAY, SHOW, RETURN, OUTPUT
Process/compute: COMPUTE, CALCULATE,
DETERMINE Initialize: SET, INIT
Add one: INCREMENT, BUMP
If: IF condition THEN
statement 1
ELSE
VEL TECH HIGH TECH DR.RANGARAJAN DR.SAKUNTHALA ENGINEERING COLLEGE
6
21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING

statement 2
END‐IF
While: WHILE condition
statements
END‐WHILE
For: FOR condition
statements

ND‐WHILE
For: FOR condition
statements
END‐FOR
for subprogram BEGIN SUBPROGRAM, END

 FLOW
CHART
SUBPROGRAM,BEGIN PROCEDURE,END PROCEDURE
Flow chart is defined as graphical representation of the logic for problem solving. The
purpose of flowchart is making the logic of the program clear in a visual
representation.

Rules for drawing a flowchart


1. The flowchart should be clear, neat and easy to follow.
2. The flowchart must have a logical start and finish.
3. Only one flow line should come out from a process symbol.

VEL TECH HIGH TECH DR.RANGARAJAN DR.SAKUNTHALA ENGINEERING COLLEGE


7
21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING

4. Only one flow line should enter a decision symbol. However, two or three
flow lines may leave the decision symbol.

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

6. Within standard symbols, write briefly and precisely.


7. Intersection of flow lines should be avoided.

Advantages of flowchart:
1. Communication: - Flowcharts are better way of communicating the logic of a
system to all concerned.
2. Effective analysis: - With the help of flowchart, problem can be analyzed in
more effective way.
3. Proper documentation: -Program flowcharts serve as a good
program documentation, which is needed for various purposes.
4. Efficient Coding: - The flowcharts act as a guide or blueprint during the
systems analysis and program development phase.
5. Proper Debugging: - The flowchart helps in debugging process.
6. Efficient Program Maintenance: - The maintenance of operating program
becomes easy with the help of flowchart. It helps the programmer to put efforts
more efficiently on that part.
Disadvantages of flow chart:
2. Complex logic: - Sometimes, the program logic is quite complicated. In that
case, flowchart becomes complex and clumsy.
3. Alterations and Modifications: - If alterations are required the flowchart may
require re-drawing completely.
4. Reproduction: - As the flowchart symbols cannot be typed, reproduction of
flowchart becomes a problem.
5. Cost: For large application the time and cost of flowchart drawing becomes
costly.

 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.
VEL TECH HIGH TECH DR.RANGARAJAN DR.SAKUNTHALA ENGINEERING COLLEGE
8
21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING

Types of programming language


1. Machine language
2. Assembly language
3. High level language
Machine language:
The computer can understand only machine language which uses 0’s and 1’s. In
machine language the different instructions are formed by taking different combinations of
0’s and 1’s.

 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.
Ex: ADD a, b
Assembler:
Assembler is the program which translates assembly language instruction in to a
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.
Examples: C and C++ compilers.

 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.
VEL TECH HIGH TECH DR.RANGARAJAN DR.SAKUNTHALA ENGINEERING COLLEGE
9
21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING

 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.
 PythonisaBeginner'sLanguage:Pythonisagreatlanguageforthebeginner-
level programmers and supports the development of a wide range of
applications.
1.1. Python Features:
 Easy-to-learn: Python is clearly defined and easily readable. The structure
of the program is very simple. It uses few keywords.
 Easy-to-maintain: Python's source code is fairly easy-to-maintain.
 Portable: Python can run on a wide variety of hardware platforms and has the same
interface on all platforms.
 Interpreted: Python is processed at runtime by the interpreter. So, there is no need to
compile a program before executing it. You can simply run the program.
 Extensible: Programmers can embed python within their C,C++,Java script
,ActiveX, etc.
 Free and Open Source: Anyone can freely distribute it, read the source code, and edit
it.
 High Level Language: When writing programs, programmers concentrate on solutions
of the current problem, no need to worry about the low level details.
 Scalable: Python provides a better structure and support for large programs than shell
scripting.
1.2. Applications:
 Bit Torrent file sharing
 Google search engine, You tube
 Intel, Cisco, HP,IBM
 i–Robot
 NASA
 Face book, Drop box

 PYTHON INTERPRETER:
Interpreter: To execute a program in a high-level language by translating it one line ata 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

VEL TECH HIGH TECH DR.RANGARAJAN DR.SAKUNTHALA ENGINEERING COLLEGE


10
21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING

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

MODES OF PYTHON INTERPRETER:


Python Interpreter is a program that reads and executes Python code. It uses 2 modes of
Execution.
1. Inter active mode
2. Script mode
1.Interactive mode:
 Interactive Mode, as the name suggests, allows us to interact with OS.
 When we type Python statement, interpreter displays the result(s)
immediately.
Advantages:
 Python, in interactive mode, is good enough to learn, experiment or explore.
 Working in interactive mode is convenient for beginners and for testing small pieces of
code.
Drawback:
 We cannot save the statements and have to retype all the statements once again to re-run
them.
In interactive mode, you type Python programs and the interpreter displays the result:
>>> 1 + 1
2
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.Script mode:
Script mode is where you write your code in a . py file and then run it with the python
command. This is the most common way that people use Python because it lets you write and
save your code so that you can use it again later.

2.1
 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:
VEL TECH HIGH TECH DR.RANGARAJAN DR.SAKUNTHALA ENGINEERING COLLEGE
11
21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING

 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 type
 .2.1Strings:
 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 –ven(where n is length of the string) displays the first element.
Example: A[0] or A[-5] will display “H”
 Subscript 1 or –ve (n-1) displays the second element.
Example: A[1] or A[-4] will display “E”

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.
2.2.4 Tuple:
 A tuple is same as list, except that the set of elements is enclosed in parentheses
instead of square brackets.
 A tuple is an immutable list. i.e. once a tuple has been created, you can't add elements
to a tuple or remove elements from the tuple.
 Benefit of Tuple:
 Tuples are faster than lists.
 If the user wants to protect the data from accidental changes, tuple can be used.
 Tuple can be used as keys in dictionaries, while lists can't.
Mapping
-This data type is unordered and mutable.
-Dictionaries fall under Mappings.
2.3.1 Dictionaries:
 Lists are ordered sets of objects, whereas dictionaries are unordered sets.
VEL TECH HIGH TECH DR.RANGARAJAN DR.SAKUNTHALA ENGINEERING COLLEGE
12
21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING

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

 VALUES AND DATATYPES

Value:
Value can be any letter ,number or string.
Eg, Values are 2, 42.0, and 'Hello, World!'. (These values belong to different data types.)
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:

 VARIABLES,KEYWORDS EXPRESSIONS, STATEMENTS, COMMENTS, DOC


STRING ,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.

3.3 IDENTIFIERS:
Identifier is the name given to entities like class, functions, variables etc. in Python.
 Identifiers can be a combination of letters in lowercase (a to z) or uppercase (A to
Z) or digits (0 to 9) or an underscore (_).

VEL TECH HIGH TECH DR.RANGARAJAN DR.SAKUNTHALA ENGINEERING COLLEGE


13
21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING

 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
Statements:
-Instructions that a Python interpreter can executes are called statements.
-A statement is a unit of code like creating a variable or displaying a value.
>>> n = 17
>>>print(n)
Here, The first line is an assignment statement that gives a value to n. The
second line is a print statement that displays the value of n.
Expressions:
-An expression is a combination of values, variables, and operators.
- A value all by itself is considered an expression, and also a variable.
- So the following are all legal expressions:

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


python, input () function is available for input.

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 anhour
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:
Doc string 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 doc string.
Triple quotes are used while writing doc strings.
Syntax:
function name__ doc.__

3.10 TUPLE ASSIGNMENT

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


VEL TECH HIGH TECH DR.RANGARAJAN DR.SAKUNTHALA ENGINEERING COLLEGE
14
21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING

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)
Value error: need more than 3 values to unpack
-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
>>>maili d='[email protected]'
>>>name, domain=mail id. 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
VEL TECH HIGH TECH DR.RANGARAJAN DR.SAKUNTHALA ENGINEERING COLLEGE
15
21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING

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

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

VEL TECH HIGH TECH DR.RANGARAJAN DR.SAKUNTHALA ENGINEERING COLLEGE


16
21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING

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

becomes true. not 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
operand, then condition becomes true. not true.

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

>= If the value of left operand is greater than or equal to the value (a >= b) is
of right operand, then condition becomes true. not 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.

Example

VEL TECH HIGH TECH DR.RANGARAJAN DR.SAKUNTHALA ENGINEERING COLLEGE


17
21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING

a=10 Output:
b=5 print("a>b=>",a>b) 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

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 the c += a is
result to left operand equivalent
to c = c + a

-= Subtract It subtracts right operand from the left operand and assign c -= a is
AND the result to left operand equivalent
to c = c -a

*= 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 assign c /= a is
AND 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 result c %= a is
AND to left operand equivalent
to c = c % a

VEL TECH HIGH TECH DR.RANGARAJAN DR.SAKUNTHALA ENGINEERING COLLEGE


18
21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING

**= 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 value to c //= a is
Division 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 is2
c += a Line 6 - Value of c is 2097152
print("Line 2 - Value of c is ", c) Line 7 - Value of c is99864
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)

4.4 Logical Operators:


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

VEL TECH HIGH TECH DR.RANGARAJAN DR.SAKUNTHALA ENGINEERING COLLEGE


19
21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING

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 = 00111100 Line 1 - Value of c is 12
b =13 # 13 = 00001101 Line 2 - Value of c is 61
c=0 Line 3 - Value of c is 49
c = a& b; # 12 = 00001100 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 = 00111101 Line 6 - Value of c is 15
print "Line 2 - Value of c is ", c
c = a^b; # 49 = 00110001
print "Line 3 - Value of c is ",c
c =~a; # -61 = 11000011
print "Line 4 - Value of c is ", c
c = a<<2; # 240 = 11110000
print "Line 5 - Value of c is ", c
c = a>>2; # 15 = 00001111
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,
VEL TECH HIGH TECH DR.RANGARAJAN DR.SAKUNTHALA ENGINEERING COLLEGE
20
21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING

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 partof the
memory.

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

OPERATOR PRECEDENCE

When an expression contains more than one operator, the order of evaluation
depends on the order of operations.

VEL TECH HIGH TECH DR.RANGARAJAN DR.SAKUNTHALA ENGINEERING COLLEGE


21
21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING

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) is8.
 Youcanalsouseparenthesestomakeanexpressioneasiertoread,asin(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, and2
*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, not5.
 Operators with the same precedence are evaluated from left to right (except
exponentiation).
Example:

VEL TECH HIGH TECH DR.RANGARAJAN DR.SAKUNTHALA ENGINEERING COLLEGE


22
21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING

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=10 A=9+6 m=1
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

VEL TECH HIGH TECH DR.RANGARAJAN DR.SAKUNTHALA ENGINEERING COLLEGE


23
21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING

INTEGRATED LAB PROGRAMS

[1] Write a program to demonstrate data types

PROGRAM

a=532
b=42.5
c=True
d=10+5j
e="Hello"
f=[1,2,3,4,5]
g=(1,2,3,4,5)
h={1,2,3,4,5}
i={"Eng":45,"Mat":52,"Sci":53}
print("a:",a ,type(a))
print("b:",b ,type(b))
print("c:",c ,type(c))
print("d:",d ,type(d))
print("e:",e ,type(e))
print("f:",f ,type(f))
print("g:",g ,type(g))
print("h:",h ,type(h))
print("i:",i ,type(i))

OUTPUT

VEL TECH HIGH TECH DR.RANGARAJAN DR.SAKUNTHALA ENGINEERING COLLEGE


24
21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING

UNIT II

CONTROL FLOW, FUNCTIONS

Conditional statements-Iterative statements, Functions: Built-in functions, user


defined function Function Arguments-Fruitful functions and void functions- local and
global variable - function composition- recursion-Lambda Functions.

1) Conditional Statements
we have to control the flow of execution of our program and we want to execute some
set of statements only if the given condition is satisfied, and a different set of
statements when it’s not satisfied.Conditional statements are also known as decision-
making statements. We need to use these conditional statements to execute the specific
block of code if the given condition is true or false.

• 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:
if(condition 1):
statement 1

Flowchart:

EXAMPLE:

Program to provide bonus mark if the output


category is 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 S
m=m+5 mark is 90
print(“mark
is”,m)
VEL TECH HIGH TECH DR.RANGARAJAN DR.SAKUNTHALA ENGINEERING COLLEGE

1
21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING

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:
if(condition 1):
statement 1
else:
statement 2
Flowchart:

Examples:
1. odd or even number
2. positive or negative number

Odd or even number Output

n=eval(input("enter a number")) enter a number 4


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 year")) enter a year2000


if(y%4==0): leap year
VEL TECH HIGH TECH DR.RANGARAJAN DR.SAKUNTHALA ENGINEERING COLLEGE

2
21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING

print("leap year")
else:
print("not leap year")
3. leap year or not

Chained conditionals (if-elif-else) :

The elif is short for else if. This is used to check more than one condition. If the condition1 is False, it
checks the condition2 of the elif block. If all the conditions are False, then the else part is executed.
Among the several if...elif...else part, only one part is executed according to the condition. The if
block can have only one else block. But it can have multiple elif blocks. The way to express a
computation like that is a chained conditional.

syntax:

if(condition 1):
statement 1
elif(condition 2):
statement 2
elif(condition 3):
statement 3
else:
default statement
Flowchart:

Example:
1. student mark system
2. traffic light system

VEL TECH HIGH TECH DR.RANGARAJAN DR.SAKUNTHALA ENGINEERING COLLEGE

3
21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING

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

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

Syntax

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

VEL TECH HIGH TECH DR.RANGARAJAN DR.SAKUNTHALA ENGINEERING COLLEGE

4
21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING

Example:
1. greatest of three numbers
2. positive negative or zero
greatest of three numbers output

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


b=eval(input(“enter the value of b”)) enter the value of a 9
c=eval(input(“enter the value of c”)) enter the value of a 1
if(a>b): enter the value of a 8
if(a>c): the greatest no is 9
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)
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")

2.Iteration Or Control Statements:

VEL TECH HIGH TECH DR.RANGARAJAN DR.SAKUNTHALA ENGINEERING COLLEGE

5
21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING

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

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 start with indentation and the first
unintended line marks the end.
Syntax:
initial value
while (condition):
body of while loop
increment
flowchart:

Examples:
program to find sum of n numbers:
program to find factorial of a number
program to find sum of digits of a number:
Program to Reverse the given number:
Program to find number is Armstrong number or not
Program to check the number is palindrome or not
program to find sum of n numbers output
n=eval(input("enter n")) enter n
VEL TECH HIGH TECH DR.RANGARAJAN DR.SAKUNTHALA ENGINEERING COLLEGE

6
21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING

i=1 10
sum=0 55
while(i<=n):
sum=sum+i
i=i+1
print(sum)
program to find factorial of a number 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)
program to find 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
sum=sum+a
n=n//10
print(sum)
Program to 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)
Program to find number is Armstrong number or not output

n=eval(input("enter a number")) enter a number153


org=n The given number is Armstrong
sum=0 number
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")
Program to check the number is palindrome or not output

n=eval(input("enter a number")) enter a number


org=n 121
sum=0 The given no is palindrome
while(n>0):
a=n%10
VEL TECH HIGH TECH DR.RANGARAJAN DR.SAKUNTHALA ENGINEERING COLLEGE

7
21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING

sum=sum*10+a
n=n//10
if(sum==org):
print("The given no is palindrome")
else:
print("The given no is not palindrome")
For loop:

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:

for i in range(start, stop, steps):


body of for loop

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.
for i in sequence:
print (i)
Sequence can be a list, strings or tuples

s.no sequences example output

VEL TECH HIGH TECH DR.RANGARAJAN DR.SAKUNTHALA ENGINEERING COLLEGE

8
21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING

R
1. For loop in string for i in "Ramu": print(i)
A
M
U

2
2. For loop in list for i in [2,3,5,6,9]: print(i)
3
5
6
9

for i in (2,3,1): print(i) 2


3. For loop in tuple
3
1

Examples:

Program to print Fibonacci series.


check the no is prime or not

Program to print Fibonacci series.


a=0
b=1
n=eval(input("Enter the number of terms:"))
print("Fibonacci Series:")
print(a,b)
for i in range(1,n,1):
c=a+b
print(c)
a=b
b=c
output:
Enter the number of terms: 6

Fibonacci Series:

01

VEL TECH HIGH TECH DR.RANGARAJAN DR.SAKUNTHALA ENGINEERING COLLEGE

9
21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING

check the no is prime or not


n=eval(input("enter a number"))

for i in range(2,n):

if(n%i==0):

print("The num is not a prime")

break

else:

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

output:

enter a no:7

The num is a prime number.

Loop Control structure

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

While (test condition)


// codes
If (condition for break):
Break
// codes

Flowchart

VEL TECH HIGH TECH DR.RANGARAJAN DR.SAKUNTHALA ENGINEERING COLLEGE

10
21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING

Example:

for i in "welcome":
if(i=="c"):
break

print(i)

output:

CONTINUE

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

Syntax:

Continue

While (test condition)


// codes
If (condition for continue):
continue
// codes

Flowchart

VEL TECH HIGH TECH DR.RANGARAJAN DR.SAKUNTHALA ENGINEERING COLLEGE

11
21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING

Example:

for i in "welcome":if(i=="c"):
continueprint(i)
Output

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.

Syntax:

Pass

Break

EXAMPLE

for i in “welcome”:
if(i==“c”):
pass

print(i)
VEL TECH HIGH TECH DR.RANGARAJAN DR.SAKUNTHALA ENGINEERING COLLEGE

12
21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING

OUTPUT:

w
E
L
C
O
M
E
Difference between break and continue
It terminates the current loop It terminates the current iteration
and executes the remaining and transfer the control to the
statement outside the loop. next iteration in 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 we
e lo
l 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

For i in range(1,6):

Print (i)

Else:

Print(“the number greater than 6”)

Output

1
VEL TECH HIGH TECH DR.RANGARAJAN DR.SAKUNTHALA ENGINEERING COLLEGE

13
21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING

The number greater than 6

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.

Example:
i=1
while(i<=5):
print(i)
i=i+1
else:

print("the number greater than 5")


output:
1
2
3
4

5
the number greater than 5

VEL TECH HIGH TECH DR.RANGARAJAN DR.SAKUNTHALA ENGINEERING COLLEGE

14
21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING

FUNCTION:

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

 user defined function


 Built in function
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 functions Description

>>>max(3,4) 4 # returns largest element

>>>min(3,4) 3 # returns smallest element

>>>len("hello") 5 #returns length of an object

>>>range(2,8,1) [2, #returns range of given values


3, 4, 5, 6, 7]
>>>round(7.8) 8.0 #returns rounded integer of the given number

VEL TECH HIGH TECH DR.RANGARAJAN DR.SAKUNTHALA ENGINEERING COLLEGE

15
21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING

>>>chr(5) #returns a character (a string) from an integer


\x05'
>>>float(5) 5.0 #returns float number from string or integer

>>>int(5.0) 5 # returns integer from string or float

>>>pow(3,5) 243 #returns power of given number

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

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

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

def fun_name(Parameter1,Parameter2…Parameter n):


statement1 statement2…
statement n return[expression]

VEL TECH HIGH TECH DR.RANGARAJAN DR.SAKUNTHALA ENGINEERING COLLEGE

16
21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING

EXAMPLE:
def my_add(a,b):
c=a+b
return c
Function Calling: (Main Function)

 Once we have defined a function, we can call it from another function, program or
even the Pythonprompt.
 To call a function we simply type the function name with appropriate arguments.
 Example:
x=5 y=4
my_add(x,y)
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.
Function Prototypes:

 Function without arguments and without return type


 Function with arguments and without return type
 Function without arguments and with return type
 Function with arguments and with return type

 Function without arguments and without return type


 In this type no argument is passed through the function call and no output is return to
main function
 The sub function will read the input values perform the operation and print the result
in the same block
 Function with arguments and without return type
 Arguments are passed through the function call but output is not return to the main
function
 Function without arguments and with return type
 In this type no argument is passed through the function call but output is return to the
main function.
 Function with arguments and with return type
 In this type arguments are passed through the function call and output is return to the
main function

VEL TECH HIGH TECH DR.RANGARAJAN DR.SAKUNTHALA ENGINEERING COLLEGE

17
21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING

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) add() b=int(input("enter b"))
add(a,b)
OUTPUT: OUTPUT:
enter a5 enter a5
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("enterb")) return c
c=a+b a=int(input("enter a"))
return c b=int(input("enter b"))
c=add(a,b)
c=add()
print(c)
print(c)
OUTPUT: OUTPUT:
enter a5 enter a5
enter b 10 enter b 10
15 15
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: defmy_add(a,b):

Arguments :

VEL TECH HIGH TECH DR.RANGARAJAN DR.SAKUNTHALA ENGINEERING COLLEGE

18
21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING

 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 ofarguments as mentioned in parameter list.
Example:my_add(x,y)

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

ARGUMENT TYPES:

 Required Arguments
 Keyword Arguments
 Default Arguments
 Variable length Arguments
Required Arguments :

 The number of arguments in the function call should match exactly with the function
definition.
defmy_details( name, age ):
print("Name: ", name)
print("Age ", age)
return my_details("george",56)
OUTPUT:
Name: georgeAge56

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.

defmy_details( name, age ):print("Name: ", name)


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

Output:
Name: georgeAge56
VEL TECH HIGH TECH DR.RANGARAJAN DR.SAKUNTHALA ENGINEERING COLLEGE

19
21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING

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

Output:
Name: georgeAge40

Variable length Arguments


 If we want to specify more arguments than specified while defining the function,
variable lengtharguments are used. It is denoted by * symbol before parameter.

def my_details(*name ):
print(*name)
my_details("rajan","rahul","micheal", ärjun")

Output:
rajanrahulmichealärjun

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()
VEL TECH HIGH TECH DR.RANGARAJAN DR.SAKUNTHALA ENGINEERING COLLEGE

20
21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING

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
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– return expression
return 8– return value

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:
a=50

def add(): -------------- GLOBAL VARIABLE


b=20
c=a+b
print©
---------------LOCAL VARIABLE
def sub(): b=30
c=a-b print©
print(a)
OUTPUT:
70
20
50

Local Scope
 A variable with local scope can be used only within the function .
EXAMPLE:
def add():
VEL TECH HIGH TECH DR.RANGARAJAN DR.SAKUNTHALA ENGINEERING COLLEGE

21
21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING

b=20
c=a+b
print©
def sub():
b=30
c=a-b
print©
print(a)
print(b)
OUTPUT:
70
20
error
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:
find sum and average using function output composition
def sum(a,b):
sum=a+b return sum
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)
print("the avg is",avg)
OUTPUT:
enter a:4
enter b:8
the avg is 6.0
Recursion

 A function calling itself till it reaches the base value - stop point of function call.
Example: factorial of a given number using recursion.
EXAMPLE:
FACTORIAL PROGRAM
def fact(n):
if(n==1):
return 1
else:
return n*fact(n-1)
n=eval(input("enter no. to find fact:"))
fact=fact(n)
print("Fact is",fact)
OUTPUT:
enter no. to find fact:5
VEL TECH HIGH TECH DR.RANGARAJAN DR.SAKUNTHALA ENGINEERING COLLEGE

22
21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING

Fact is 120.

EXPLANATION:

LAMBDA FUNCTIONS

A function is said to be anonymous function when it is defined without a name and def

keyword A lambda function evaluates an expression for a given argument. You give the

function a value
(argument) and then provide the operation (expression). The keyword lambda must come
first. A fullcolon (:) separates the argument and the expression.

#Normal python
function def a_name(x):
return x+x

Example 1: #Lambda
function lambda x: x+x

Example 2:
a=lambda b: b*2+b print(a(3))

Advantages:
Good for simple logical operations that are easy to understand. This makes the code more
readable too.
Good when you want a function that you will use just one time.

Disadvantages:
They can only perform one expression. It’s not possible to have multiple independent
VEL TECH HIGH TECH DR.RANGARAJAN DR.SAKUNTHALA ENGINEERING COLLEGE

23
21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING

operations inone lambda function.

Bad because you can’t write a doc-string to explain all the inputs, operations, and
outputs as you would in a normal def function.

Scalar values
This is when you execute a lambda function on a single value. (lambda x: x*2)(12)

###Results 24

Filter(). This is a Python inbuilt library that returns only those values that fit certain criteria.
The syntax is filter(function, iterable).

list_1 = [1,2,3,4,5,6,7,8,9]
list(filter(lambda x: x%2==0, list_1))

###Results[2, 4, 6, 8]

Map( ). This is another inbuilt python library with the syntax map(function, iterable). This
returns a modified list where every value in the original list has been changed based on a
function.

list_1 = [1,2,3,4,5,6,7,8,9]
cubed = map(lambda x: pow(x,3),list_1)
list(cubed) ###Results
[1, 8, 27, 64, 125, 216, 343, 512, 729]

INTEGRATED LAB PROGRAM:

write a program to check whether the given number is even or odd

Program:
a=int(input ("Enter the number:"))
if a%2==0:
print("The given number is even")
else:
print("The given number is odd")

Output:

VEL TECH HIGH TECH DR.RANGARAJAN DR.SAKUNTHALA ENGINEERING COLLEGE

24
21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING

write the program for student Mark system.


Program:
m=int(input("Enter the total marks of 6 subjects Max 100 in each subject :"))
per=(m*100)/600
print ("you have scored {}% of marks".format(per))
if per<35:
print ("Failure")
elif per>=35 and per<50:
print ("passed")
elif per>=50 and per<60:
print ("Second Division")
elif per>=60 and per<70:
print ("First Division")
else:
print ("First Class with Distinction")
output:

write the program to find the greatest among three numbers.

Programs:
a=int(input("Enter the value of a:"))
b=int(input("Enter the value of b:"))
c=int(input("Enter the value of c:"))
if(a>b):
if(a>c):
print("The greatest number is",a)
else:
print("The greatest number is",c)
else:
if(b>c):
print("The greatest number is",b)
else:
print("The greatest number is",c)
Output:

Write a Program to Check whether the given number is Armstrong or not


Program:
n=int(input("enter a number"))
org=n
VEL TECH HIGH TECH DR.RANGARAJAN DR.SAKUNTHALA ENGINEERING COLLEGE

25
21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING

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 ")
else:
print("The given number is not Armstrong")
Output:

Write the python program to find the Fibonacci series

Program:
a=0
b=1
n=int(input("Enter the number of terms"))
print("fibonacci series")
print(a,b)
for i in range(1,n,1):
c=a+b
print(c)
a=b
b=c
Output:

write a python program using Function to generate the Factorial of given number.
Program:
def fact(n):
if(n==1):
return 1
else:
return n*fact(n-1)
n=int(input("Enter the number to find Factorial"))
Fact=fact(n)
print("Factorial value is ", Fact)

Output:
VEL TECH HIGH TECH DR.RANGARAJAN DR.SAKUNTHALA ENGINEERING COLLEGE

26
21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING

write a program to compute the GCD of two numbers using recursion

Programs:
defgcd(a,b):
if(b==0):
return a
else:
return b
a=int(input("Enter first number:"))
b=int(input("Enter second number: "))
GCD=gcd(a,b)
print("The GCD of a and b is ",GCD )

Output:

Write the program to find the square using lambda function.


Program:
def square(x):
return x*x
def dec(x):
return x-1
def compose_fun(p,q):
return lambda x:p(q(x))
dec_and_square=compose_fun(square,dec)
print("The dec_and_square value is ",dec_and_square(10))

Output:

VEL TECH HIGH TECH DR.RANGARAJAN DR.SAKUNTHALA ENGINEERING COLLEGE

27
21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING

UNIT-III
MODULES,PACKAGES,STRINGS

Topics:
Modules- Packages- Strings- String Operations, String
Functions And Methods.
MODULES
 A module allows to logically organize Python code.
 Grouping related code into a module makes the code easier to understand
and use.
 A module is a Python object with arbitrarily named attributes that can
bind and reference.
 Simply, a module is a file consisting of Python code.
 A module can define functions, classes and variables.
 A module can also include runnable code.

EXAMPLE:
 The Python code for a module named aname normally resides in
a file named aname.py.
 Example of a simple module, support.py
defprint_func( parameter ):
print"Hello : ", parameter
return

The import Statement


 Python source file as a module by executing an import statement
in some other Python source file. The import has the following
syntax −
import module1[, module2[,... moduleN]]
 When the interpreter encounters an import statement, it imports the
module if the module is present in the search path.
 A search path is a list of directories that the interpreter searches before
importing a module.

VEL TECH HIGH TECH DR.RANGARAJAN DR.SAKUNTHALA ENGINEERING COLLEGE

1
21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING

Example,
To import the module sample.py, need to put the following command at the top
of the script

#!/usr/bin/python

# Import module support


import sample

# Now you can call defined function that module as follows


sample.print_func("welcome")
Above code executed, it produces the following result −
Output:
Hello : welcome
 A module is loaded only once, regardless of the number of times it is
imported.
 This prevents the module execution from happening over and over again
if multiple imports occur.
The from...import Statement
 Python's from statement lets you import specific attributes from a module
into the current namespace. The from...import has the following syntax −
from modname import name1[, name2[, ... nameN]]

For example, to import the function factorial from the module fact, use the
following statement –
from fact import factorial

This statement does not import the entire module fact into the current
namespace; it just introduces the item factorial from the module fact into the
global symbol table of the importing module.

from...import * Statement
It is also possible to import all names from a module into the current namespace
by using the following import statement –

from modname import *

VEL TECH HIGH TECH DR.RANGARAJAN DR.SAKUNTHALA ENGINEERING COLLEGE

2
21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING

This provides an easy way to import all the items from a module into the current
namespace; however, this statement should be used sparingly.
Locating Modules

To import a module, the Python interpreter searches for the module in the
following sequences −
 The current directory.
 If the module isn't found, Python then searches each directory in the shell
variable PYTHONPATH.
 If all else fails, Python checks the default path. On UNIX, this default
path is normally /usr/local/lib/python/.
 The module search path is stored in the system module sys as
the sys.path variable.
 The sys.path variable contains the current directory, PYTHONPATH, and
the installation-dependent default.
The PYTHONPATH Variable
 The PYTHONPATH is an environment variable, consisting of a list of
directories. The syntax of PYTHONPATH is the same as that of the shell
variable PATH.
PYTHONPATH from a Windows system –
set PYTHONPATH = c:\python20\lib;
Namespaces and Scoping:
 Variables are names (identifiers) that map to objects. A namespace is a
dictionary of variable names (keys) and their corresponding objects
(values).
 Access variables in a local namespace and in the global namespace. If a
local and a global variable have the same name, the local variable
shadows the global variable.
 Each function has its own local namespace. Class methods follow the
same scoping rule as ordinary functions.
 Python makes educated guesses on whether variables are local or global.
It assumes that any variable assigned a value in a function is local.
 Therefore, in order to assign a value to a global variable within a
function, you must first use the global statement.
 The statement global VarName tells Python that VarName is a global
variable. Python stops searching the local namespace for the variable.
VEL TECH HIGH TECH DR.RANGARAJAN DR.SAKUNTHALA ENGINEERING COLLEGE

3
21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING

For example, a variable number in the global namespace.


 Within the function addnumber, assign number a value, therefore Python
assumes number as a local variable.
 However, we accessed the value of the local variable number before
setting it, so an UnboundLocalError is the result. Uncommenting the
global statement fixes the problem.
#!/usr/bin/python

number=2000
defAddnumber():
# Uncomment the following line to fix the code:
# globalnumber
Number =number+1

Print number
Addnumber()
Print number

 The dir( ) Function


 The dir() built-in function returns a sorted list of strings containing the
names defined by a module.
 The list contains the names of all the modules, variables and functions
that are defined in a module. Following is a simple example −
#!/usr/bin/python

# Import built-in module math


import math
content=dir(math)
print content
 When the above code is executed, it produces the following result −
['__doc__', '__file__', '__name__', 'acos', 'asin', 'atan',
'atan2', 'ceil', 'cos', 'cosh', 'degrees', 'e', 'exp', 'fabs', 'floor', 'fmod',
'frexp', 'hypot', 'ldexp', 'log',
'log10', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh',
'sqrt', 'tan', 'tanh']
 Here, the special string variable __name__ is the module's name,
and __file__ is the filename from which the module was loaded.

VEL TECH HIGH TECH DR.RANGARAJAN DR.SAKUNTHALA ENGINEERING COLLEGE

4
21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING

globals() and locals() Functions


 The globals() and locals() functions can be used to return the names in
the global and local namespaces depending on the location from where
they are called.
 If locals() is called from within a function, it will return all the names that
can be accessed locally from that function.
 If globals() is called from within a function, it will return all the names
that can be accessed globally from that function.
 The return type of both these functions is dictionary. Therefore, names
can be extracted using the keys() function.
 The reload() Function
 When the module is imported into a script, the code in the top-level
portion of a module is executed only once.
 Therefore, if you want to reexecute the top-level code in a module, you
can use the reload() function. The reload() function imports a previously
imported module again. The syntax of the reload() function is this −
 reload(module_name)
 Here, module_name is the name of the module you want to reload and not
the string containing the module name. For example, to
reload hello module, do the following −
 reload(hello)
PACKAGES IN PYTHON
A package is a hierarchical file directory structure that defines a single
Python application environment that consists of modules and sub packages and
sub-subpackages, and so on.
Consider a file dots.py available in Phone directory. This file has
following line of source code −
#!/usr/bin/python

defdots():
print"I'm dots Phone"
Similar way, another two files having different functions with the same name
as above −
 Phone/Isdn.py file having function Isdn()
VEL TECH HIGH TECH DR.RANGARAJAN DR.SAKUNTHALA ENGINEERING COLLEGE

5
21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING

 Phone/G3.py file having function G3()


Now, create one more file __init__.py in Phone directory −
 Phone/__init__.py
To make all of functions available when imported Phone, need to put explicit
import statements in __init__.py as follows −
from Pots import dots
from Isdn import Isdn
from G3 import G3
After add these lines to __init__.py, have all of these classes available when
import the Phone package.
#!/usr/bin/python

# Now import your Phone Package.


importPhone

Phone.dots()
Phone.Isdn()
Phone.G3()
OUTPUT:
I'm Pots Phone
I'm 3G Phone
I'm ISDN Phone

In the above example, a single functions in each file, keep multiple


functions in files. Define different Python classes in those files and packages
out of those classes.

VEL TECH HIGH TECH DR.RANGARAJAN DR.SAKUNTHALA ENGINEERING COLLEGE

6
21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING

String in Python
 A string is a sequence of characters.
 A character is simply a symbol. For example, the English language has 26
characters.
 Computers do not deal with characters, they deal with numbers (binary).
Even though characters on user screen, internally it is stored and
manipulated as a combination of 0s and 1s.
 This conversion of character to a number is called encoding, and the
reverse prSocess is decoding. ASCII and Unicode are some of the popular
encodings used.
 In Python, a string is a sequence of Unicode characters. Unicode was
introduced to include every character in all languages and bring
uniformity in encoding.
How to create a string in Python?
 Strings can be created by enclosing characters inside a single quote or
double-quotes.
 Even triple quotes can be used in Python but generally used to represent
multiline strings and docstrings.

# defining strings in Python


# all of the following are equivalent
my_string = 'Hello'
print (my_string)

my_string = "Hello"
print(my_string)

my_string = '''Hello'''
print(my_string)
# triple quotes string can extend multiple lines
my_string = """Hello, welcome to
the world of Python"""
VEL TECH HIGH TECH DR.RANGARAJAN DR.SAKUNTHALA ENGINEERING COLLEGE

7
21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING

print(my_string)
output
Hello
Hello
Hello
Hello, welcome to
the world of Python

How to access characters in a string?

 Access individual characters using indexing and a range of characters


using slicing.
 Index starts from 0.
 Trying to access a character out of index range will raise an IndexError.
 The index must be an integer.
 Use floats or other types, this will result into TypeError.
 Python allows negative indexing for its sequences.

The index of -1 refers to the last item, -2 to the second last item and so on.
Access a range of items in a string by using the slicing operator :(colon).
String Function
#Accessing string characters in Python
str = 'programiz'
print('str = ', str)

#first character
print('str[0] = ', str[0])

#last character
print('str[-1] = ', str[-1])

#slicing 2nd to 5th character


print('str[1:5] = ', str[1:5])

#slicing 6th to 2nd last character


print('str[5:-2] = ', str[5:-2]

VEL TECH HIGH TECH DR.RANGARAJAN DR.SAKUNTHALA ENGINEERING COLLEGE

8
21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING
output:
str = programiz
str[0] = p
str[-1] = z
str[1:5] = rogr
str[5:-2] = am

 To access an index out of the range or use numbers other than an integer,
will get errors.
# index must be in range
my_string[15] ...
IndexError: string index out of range
# index must be an integer
my_string[1.5]
...
TypeError: string indices must be integers

 Slicing can be best visualized by considering the index to be between the


elements as shown below.

 To access a range, the index that will slice the portion from the string.

String Slicing in Python

VEL TECH HIGH TECH DR.RANGARAJAN DR.SAKUNTHALA ENGINEERING COLLEGE

9
21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING

How to change or delete a string?

 Strings are immutable.


 This means that elements of a string cannot be changed once they have
been assigned.
 Simply reassign different strings to the same name.
my_string = 'programiz'
my_string[5] = 'a'
...
TypeError: 'str' object does not support item assignment
my_string = 'Python'
my_string
'Python'

 cannot delete or remove characters from a string. But deleting the string
entirely is possible using the del keyword.
del my_string[1]
...
TypeError: 'str' object doesn't support item deletion
del my_string
my_string
...
NameError: name 'my_string' is not defined
Python String Operations

There are many operations that can be performed with strings which makes it
one of the most used data types in Python.

Concatenation of Two or More Strings

 Joining of two or more strings is called concatenation.

 The ‘+ ‘operator does this in Python. Simply writing two string literals
together also concatenates them.
 The * operator can be used to repeat the string for a given number of
times.
VEL TECH HIGH TECH DR.RANGARAJAN DR.SAKUNTHALA ENGINEERING COLLEGE

10
21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING

# Python String Operations


str1 = 'Hello'
str2 ='World!'

# using +
print('str1 + str2 = ', str1 + str2)

# using *
print('str1 * 3 =', str1 * 3)

output:
str1 + str2 = HelloWorld!
str1 * 3 = HelloHelloHello

 Writing two string literals together also concatenates them


like ‘+’ operator.
 To concatenate strings in different lines, use parentheses.

Iterating Through a string

Iterate through a string using a for loop. here is an example to count the number
of 'l's in a string.
STRING LAB EXERCISE

# Iterating through a string

count = 0

for letter in'Hello World':

if(letter == 'l'):

count += 1

print(count,'letters found')

output:

3 letters found

VEL TECH HIGH TECH DR.RANGARAJAN DR.SAKUNTHALA ENGINEERING COLLEGE

11
21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING

String Membership Test

test if a substring exists within a string or not, using the keyword in.

'a' in' program'


True
'at' not in 'battle'
False

Built-in functions to Work with Python

 Various built-in functions that work with sequence work with strings as
well.
 Some of the commonly used ones are enumerate() and len().
 The enumerate() function returns an enumerate object.
 It contains the index and value of all the items in the string as pairs.
 This can be useful for iteration.
 Similarly, len() returns the length (number of characters) of the string.
str = 'cold'
# enumerate()
list_enumerate = list(enumerate(str))
print('list(enumerate(str) = ', list_enumerate)
#character count
print('len(str) = ', len(str))
output:
list(enumerate(str) = [(0, 'c'), (1, 'o'), (2, 'l'), (3, 'd')]
len(str) = 4

VEL TECH HIGH TECH DR.RANGARAJAN DR.SAKUNTHALA ENGINEERING COLLEGE

12
21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING

Python String Formatting

Escape Sequence

 To print a text like He said, "What's there?",


 neither use single quotes nor double quotes.
 This will result in a SyntaxError as the text itself contains both single and
double quotes.
print("He said, "What's there?"")

SyntaxError: invalid syntax

print('He said, "What's there?"')

SyntaxError: invalid syntax

 One way to get around this problem is to use triple quotes.


 Alternatively, we can use escape sequences.
 An escape sequence starts with a backslash and is interpreted differently.
 If we use a single quote to represent a string, all the single quotes inside
the string must be escaped.
 Similar is the case with double quotes.
 Here is how it can be done to represent the above text.
# using triple quotes
print('''He said, "What's there?"''')
# escaping single quotes
print('He said, "What\'s there?"')
# escaping double quotes
print("He said, \"What's there?\"")
output:
He said, "What's there?"
He said, "What's there?"
He said, "What's there?"

VEL TECH HIGH TECH DR.RANGARAJAN DR.SAKUNTHALA ENGINEERING COLLEGE

13
21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING

List Of All The Escape Sequences

Escape Sequence Description

\newline Backslash and newline ignored

\\ Backslash

\' Single quote

\" Double quote

\a ASCII Bell

\b ASCII Backspace

\f ASCII Formfeed

\n ASCII Linefeed

\r ASCII Carriage Return

\t ASCII Horizontal Tab

\v ASCII Vertical Tab

\ooo Character with octal value ooo

\xHH Character with hexadecimal value HH

VEL TECH HIGH TECH DR.RANGARAJAN DR.SAKUNTHALA ENGINEERING COLLEGE

14
21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING

some examples are

print("C:\\Python32\\Lib")

C:\Python32\Lib

print("This is printed\nin two lines")

This is printed in two lines

print("This is \x48\x45\x58 representation")

This is HEX representation

Raw String to ignore escape sequence

Sometimes to ignore the escape sequences inside a string. To do this


place r or R in front of the string. This will imply that it is a raw string and any
escape sequence inside it will be ignored.
print("This is \x61 \ngood example")

This is a good example

print(r"This is \x61 \ngood example")

This is \x61 \ngood example

The format() Method for Formatting Strings


 The format() method that is available with the string object is very
versatile and powerful in formatting strings.
 Format strings contain curly braces {} as placeholders or replacement
fields which get replaced.
 We can use positional arguments or keyword arguments to specify the
order.

# Python string format() method


# default(implicit) order
default_order = "{}, {} and {}".format('raj','cash','paid')
print('\n--- Default Order ---')
print(default_order)

VEL TECH HIGH TECH DR.RANGARAJAN DR.SAKUNTHALA ENGINEERING COLLEGE

15
21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING

# order using positional argument

positional_order = "{1}, {0} and {2}".format('raj','cash','paid')

print('\n--- Positional Order ---')


print(positional_order)

# order using keyword argument


keyword_order = "{s}, {b} and {j}".format(j='raj',b='cash',s='paid')

print('\n--- Keyword Order ---')

print(keyword_order)

output:
--- Default Order ---
Raj,cash and paid
--- Positional Order ---

Raj,cash and paid

--- Keyword Order ---

Raj,cash and paid

 The format() method can have optional format specifications.


 They are separated from the field name using colon.
 For example, left-justify <, right-justify > or center ^ a string in the given
space.Format integers as binary, hexadecimal, etc. and floats can be
rounded or displayed in the exponent format. There are tons of formatting
use.
# formatting integers

"Binary representation of {0} is {0:b}".format(12)

'Binary representation of 12 is 1100'

# formatting floats
VEL TECH HIGH TECH DR.RANGARAJAN DR.SAKUNTHALA ENGINEERING COLLEGE

16
21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING

"Exponent representation: {0:e}".format(1566.345)

'Exponent representation: 1.566345e+03'

# round off

"One third is: {0:.3f}".format(1/3)

'One third is: 0.333'

# string alignment

"|{:<10}|{:^10}|{:>10}|".format('butter','bread','ham')

'|butter | bread | ham|'

Common Python String Methods


 There are numerous methods available with the string object.
 The format() method that we mentioned above is one of them.
 Some of the commonly used methods lower(), upper(), join(), split(),
find(), replace() etc.
 a complete list of all the built-in methods to work with strings in Python.
Integrated course Lab Exercise:6
Input_string =input(“Enter the string:”).lower()
Vowels=”aeiou”
Flag=Flase
for char in vowels:
if char in input_string:
print(“vowel:”,char,input_string,count(char))
flag=True
if not flag:
print(“there are no vowels in {}”.format(input_string))
output:
Enter a string pythonprogramming
Vowel:a 1
Vowel:I 1
Vowel:o 2

VEL TECH HIGH TECH DR.RANGARAJAN DR.SAKUNTHALA ENGINEERING COLLEGE

17
21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING

BUILD IN STRING FUNCTION

Sono. String Syntax statements Return


functions

1. islower() str.islower() given string true


has all otherwise
lowercase false
letter
2. isupper() str.isupper() given string true
has all otherwise
lowercase false
letter

3. swapcase() str.swapcase() reverse the


case of all
string upper to
lower
viseversa
4. find() str.find(‘’substring’’) find if a return index
substring if found or
occurs in a else-1
string for given
starting index
beg and end
index as end
5. index() str.index(‘’substring’’) tries find if a return index
substring of the
occurs in a substring or
string for given else rises
starting index exception
beg and end
index as end
6. split() str.split breaks a string return a list
([sep,[maxsplit]) which is
separated by
separator

VEL TECH HIGH TECH DR.RANGARAJAN DR.SAKUNTHALA ENGINEERING COLLEGE

18
21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING

7. lstrip() str.lstrip() removes all the return the


leading string minus
whitespaces in trailing
string whitespaces

8. rstrip() str.rstrip() removes return string


trailing minus
whitespaces in trailing
the string whitespaces

9. isspace() str.isspace() is there is any return true


whitespace else it return
false

10. splitlines() str.splitlines split a given return the


(num=str.count(‘\n’)) string by new string as a
lines(\n) list with the
newlines
removed.

11. join() separator.join(str) string sequence if num which


joined by is an integer
string seperator value and if
indicates the
newlines
need to be
included in
the lines.

VEL TECH HIGH TECH DR.RANGARAJAN DR.SAKUNTHALA ENGINEERING COLLEGE

19
21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING

MISCELLENOUS STRING FUNCTION


s.no string function syntax statement return

1. join() separator.join sequence return join


(str) joined by a string.
string
separator.

2. len() len(str) length of the returns the


string length of
string

3. replace() str.replace(old,new update the old return new


(count)) occurrences string
to new

4. max() max(str) maximum return


characters in maximum
a string character

5. min() min(str) Minimum Return


characters in minimum
a string character

6. title() str.title() converts a Return string


string in titled
case.
uppercase
follows by
lowercase.
7. istitle() str.istitle() checks the return true,
string in title else false
case
8. capitalize() Str.capitalize() Capitalize the Return string
first letter of
string

VEL TECH HIGH TECH DR.RANGARAJAN DR.SAKUNTHALA ENGINEERING COLLEGE

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

List is a 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.

Eg: a=[10, 20, 30, 40]; b=[10, 20, “abc”, 4.5]
Operations on list:
1. Indexing - accessing the list elements
2. Slicing - accessing the list elements
3. Concatenation -main Operations
4. Repetition - main Operations
5. Updating -updating the list
6. Membership -other operations
7. Comparison -other operations

Operations examples description


create a list >>> a=[2,3,4,5,6,7,8,9,10] in this way we can create a
>>> print(a) list at compile time
[2, 3, 4, 5, 6, 7, 8, 9, 10]

>>> print(a[0]) Accessing the item in the


Indexing 2 position 0
>>> print(a[8]) Accessing the item in the
10 position 8
>>> print(a[-1]) Accessing a last element
10 using negative indexing.

>>> print(a[0:3])
Slicing [2, 3, 4]
>>> print(a[0:]) Printing a part of the list.
[2, 3, 4, 5, 6, 7, 8, 9, 10]

>>>b=[20,30] Adding and printing the


Concatenation >>> print(a+b) items of two lists.
[2, 3, 4, 5, 6, 7, 8, 9, 10, 20, 30]
>>> print(b*3) Create a multiple copies of
Repetition [20, 30, 20, 30, 20, 30] the same list.

>>> print(a[2])
4 Updating the list using
Updating >>> a[2]=100 Index value .
>>> print(a)
[2, 3, 100, 5, 6, 7, 8, 9, 10]

>>> a=[2,3,4,5,6,7,8,9,10]
>>> 5 in a
Membership True Returns True if element is
>>> 100 in a present in list. Otherwise
False returns false.
>>> 2 not in a
False

>>> a=[2,3,4,5,6,7,8,9,10] Used for comparing two lists.


>>>b=[2,3,4] Returns True if all elements
Comparison
>>> a==b in both lists are same.
False Otherwise returns false
>>> a!=b
True

List slices:
List slicing is an operation that extracts a subset of elements from an list and packages
them as another list.
Syntax:
Listname[start:stop]
Listname[start:stop:steps]


default start value is 0

default stop value is n-1

[:] this will print the entire list

[2:2] this will create a empty slice
slices Example Description
>>> a=[9,8,7,6,5,4]
a[0:3] >>> a[0:3] Printing a part of a list from
[9, 8, 7] 0 to 2.
a[:4] >>> a[:4] Default start value is 0. So
[9, 8, 7, 6] prints from 0 to 3
a[1:] >>> a[1:] Default stop value will be
[8, 7, 6, 5, 4] n-1. so prints from 1 to 5

a[:] >>> a[:] Prints the entire list.


[9, 8, 7, 6, 5, 4]

a[2:2] >>> a[2:2] print an empty slice


[]

a[0:6:2] >>> a[0:6:2] Slicing list values with step


[9, 7, 5] size 2.

a[::-1] >>> a[::-1] Returns reverse of given list


[4, 5, 6, 7, 8, 9] Values

List methods:

Methods used in lists are used to manipulate the data quickly.

These methods work only on lists.

They do not work on the other sequence types that are not mutable, that is, the values
they contain cannot be changed, added, or deleted.

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

Methods syntax Example Description


1 Append(): list.append(element) >>> a=[1,2,3,4,5]
>>> a.append(6) Add an element to
>>> print(a) the end of the list
[1, 2, 3, 4, 5, 6]

2 Insert(): list.insert(index,element) >>> a.insert(0,0) Insert an item at the


>>> print(a) defined index
[0, 1, 2, 3, 4, 5, 6]

3 Extend(): list.extend(list) >>> b=[7,8,9] Add all elements of a


>>> a.extend(b) list to the another
>>> print(a) List
[0, 1, 2, 3, 4, 5, 6, 7, 8,9]

4 Index(): list.index(element) >>> a.index(8) Returns the index of


8 the first matched
Item

5 Sort(): list.sort() >>> a.sort() Sort items in a list in


>>> print(a) ascending order
[0, 1, 2, 3, 4, 5, 6, 7, 8]

6 Reverse(): list.reverse() >>> a.reverse() Reverse the order of


>>> print(a) items in the list
[8, 7, 6, 5, 4, 3, 2, 1, 0]

7 Pop(): list.pop() >>> a.pop() Removes and


0 returns the
last element

8 Pop(): list.pop(index) >>> a.pop(0) Remove the


particular element
8 present on the index
and return it.

9 Remove(): list.remove(element) >>> a.remove(1) Removes an item


>>> print(a) from the list
[7, 6, 5, 4, 3, 2]

10 Count(): list.count(element) >>> a.count(6) Returns the number of


1 occurrences of an
element in a list.

11 Copy(): list.copy() >>> b=a.copy() Returns a copy


>>> print(b) of the list.
[7, 6, 5, 4, 3, 2]

>>> a.clear()
12 Clear(): list.clear() >>> print(a) Removes all items
[] from the list.

13 del(): del(list) >>> del(a) delete the entire list.


>>> print(a)
Error: name 'a' is not
Defined

List built-in functions:


Python’s built-in functions such as min(), max(),len() and sorted() can be used with list
to obtain needed value and execute various tasks.
a=[1,2,3,4,5]
1. Len()
This function returns the number of items on a list(length of the list).
>>>len(a)
5
2. Max()
This function returns the maximum value in a list.
>>>max(a)
5
3. Min()
This function returns the maximum value in a list.
>>>min(a)
1
4. Sum()
This function returns the sum of all items on a list.
>>sum(a)
15
5. Sorted()
This function returns a sorted list in ascending order.
>>>c=[5,3,4,1,2]
>>>sorted(c)
[1,2,3,4,5]

List loops:
1. For loop
2. While loop

List using For Loop:



The for loop in Python is used to iterate over a sequence (list, tuple, string) or other
iterable objects.

Iterating over a sequence is called traversal.

Loop continues until we reach the last item in the sequence.

The body of for loop is separated from the rest of the code using indentation.
Syntax:
for val in sequence:
print val

Accessing element Output


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

Accessing element using range: Output


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

List using While loop



The while loop in Python is used to iterate over a block of code as long as the test
expression (condition) is true.

When the condition is tested and the result is false, the loop body will be skipped and
the first statement after the while loop will be executed.
Syntax:
while (condition):
body of while

Sum of elements in list Output:


a=[1,2,3,4,5] 15
i=0
sum=0
while i<len(a):
sum=sum+a[i]
i=i+1
print(sum)

Infinite Loop
A loop becomes infinite loop if the condition given never becomes false. It keeps on
running. Such loops are called infinite loop.
Example Output:
a=1 Enter the number 10
while (a==1): you entered:10
n=int(input("enter the number")) Enter the number 12
print("you entered:" , n) you entered:12
Enter the number 16
you entered:16

Integrated Lab Program


Program to find the Maximum of a List of Numbers

Program:
size=int(input("Enter the number of elements:"))
lst=[]
print("Enter the elements:")
for i in range(0,size):
lst.append(int(input()))
print("The elements of the list are",lst)
max=lst[0]
for i in range(0,size):
iflst[i]>max:
max=lst[i]
print("The Maximum element is",max)

Output:

Mutability:

Lists are mutable. (can be changed)

Mutability is the ability for certain types of data to be changed without entirely
recreating it.

An item can be changed in a list by accessing it directly as part of the assignment
statement.

Using the indexing operator (square brackets[ ]) on the left side of an assignment, one
of the list items can be updated.

Example description

>>> a=[1,2,3,4,5] changing single element


>>> a[0]=100
>>> print(a)
[100, 2, 3, 4, 5]

>>> a=[1,2,3,4,5] changing multiple element


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

>>> a=[1,2,3,4,5] The elements can be inserted into a list by


>>> a[0:0]=[20,30,45] squeezing them into an empty slice at the
>>> print(a) desired location.
[20,30,45,1, 2, 3, 4, 5]
Aliasing(copying):

Creating a copy of a list is called aliasing. When you create a copy both list will be

having same memory location. changes in one list will affect another list.

Alaising refers to having different names for same list values.

Example Output:
a= [1, 2, 3 ,4 ,5]
b=a
print (b) [1, 2, 3, 4, 5]
print (a is b) True
a[0]=100
print(a) [100,2,3,4,5]
print(b) [100,2,3,4,5]


In this a single list object is created and modified using the subscript operator.

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

This type of change is what is known as a side effect. This happens because after the
assignment b=a, the variables a and b refer to the exact same list object.

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

To prevent aliasing, a new object can be created and the contents of the original can be
copied which is called cloning.

Cloning:

To avoid the disadvantages of copying we are using cloning. creating a copy of a same
list of elements with two different memory locations is called cloning.

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

Cloning is a process of making a copy of the list without modifying the original list.

Example:

>>>a=[1,2,3,4,5]
>>>b=a[:] or a.copy()
>>>print(b)
[1,2,3,4,5]
>>>a is b
False
Example Output:
a= [1, 2, 3 ,4 ,5]
b=a.copy()
print (b) [1, 2, 3, 4, 5]
print (a is b) False
a[0]=100
print(a) [100,2,3,4,5]
print(b) [1,2,3,4,5]

List as parameters:

In python, arguments are passed by reference.

If any changes are done in the parameter which refers within the function, then the
changes also reflects back in the calling function.

When a list to a function is passed, the function gets a reference to the list.

Passing a list as an argument actually passes a reference to the list, not a copy of the
list.

Since lists are mutable, changes made to the elements referenced by the parameter
change the same list that the argument is referencing.

Example 1`: Output


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

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

Example 3 Output
def insert(a): [30, 1, 2, 3, 4, 5]
a.insert(0,30)
a=[1,2,3,4,5]
insert(a)
print(a)
Tuple:

A tuple is a set of elements separated by commas and enclosed in parentheses.

A tuple is an immutable list. i.e. once a tuple has been created, we can't add elements to
a tuple or remove elements from the tuple.

But tuple can be converted into list and list can be converted in to tuple.

A tuple can also be created without using parentheses.
Methods Example description
list( ) >>> a=(1,2,3,4,5) it converts the given sequence
>>> a=list(a) into list.
>>> print(a)
[1, 2, 3, 4, 5]
it convert the given sequence
tuple( ) >>> a=[1,2,3,4,5] into tuple.
>>> a=tuple(a)
>>> print(a)
(1, 2, 3, 4, 5)
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.
Operations on Tuples:
1. Indexing -accessing tuple elements
2. Slicing -accessing tuple elements
3. Concatenation -main operations
4. Repetition -main operations
5. Membership -other operations
6. Comparison -other operations
Operations examples description
Creating the tuple with
Creating a tuple >>>a=(20,40,60,”apple”,”ball”) elements of different data
types.

>>>print(a[0]) Accessing the item in the


Indexing 20 position 0
>>> a[2] Accessing the item in the
60 position 2

Printing a part of the list.


Slicing >>>print(a[1:3]) Displaying items from 1st
(40,60) till 2nd.
Concatenation >>> b=(2,4) Adding tuple elements at
>>>print(a+b) the end of another tuple
>>>(20,40,60,”apple”,”ball”,2,4) elements

Repetition >>>print(b*2) repeating the tuple in n no


>>>(2,4,2,4) of times

>>> a=(2,3,4,5,6,7,8,9,10)
>>> 5 in a
Membership True Returns True if element is
>>> 100 in a present in tuple. Otherwise
False returns false.
>>> 2 not in a
False

>>> a=(2,3,4,5,6,7,8,9,10)
>>>b=(2,3,4) Returns True if all elements
Comparison
>>> a==b in both elements are same.
False Otherwise returns false
>>> a!=b
True

Tuple methods:

Tuple is immutable so changes cannot be done on the elements of a tuple once it is


assigned.

Methods & functions example description


Index() - tuple.index(tuple)
>>> a=(1,2,3,4,5) Returns the index of the
>>> a.index(5) first matched item.
4
Count() - tuple.count(tuple)
>>>a=(1,2,3,4,5) Returns the number of
>>> a.count(3) occurrences of an
1 element in a list
del() - del(tuple) >>> del(a) Delete the entire tuple.
Len()- len(tuple) >>> len(a) return the length of the
5 Tuple

Min()- min(tuple) >>> min(a) return the minimum


1 element in a tuple
Max()- max(tuple) >>> max(a) return the maximum
5 element in a tuple

Sum()- Sum(tuple) >>>sum(a) Returns the sum of the


15 elements in a tuple.

Tuple Assignment:

Tuple assignment allows, variables on the left of an assignment operator and values of
tuple on the right of the assignment operator.

Multiple assignment works by creating a tuple of expressions from the right hand side,
and a tuple of targets from the left, and then matching each expression to a target.
 Because multiple assignments use tuples to work, it is often termed tuple assignment.

Uses of Tuple assignment:


It is often useful to swap the values of two variables.
Example:
Swapping using temporary variable: Swapping using tuple assignment:
a=20 a=20
b=50 b=50
temp = a (a,b)=(b,a)
a=b print("value after swapping is",a,b)
b = temp
print("value after swapping is",a,b)

Multiple assignments:

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


>>>(a,b,c)=(1,2,3)
>>>print(a)
1
>>>print(b)
2
>>>print(c)
3

Tuple as return value:



A Tuple is a comma separated sequence of items.

A function can return one value. if you want to return more than one value from a
function. we can use tuple as return value.
Example1: Output:
def div(a,b): enter a value:4
r=a%b enter b value:3
q=a//b reminder: 1
return(r,q) quotient: 1
a=int(input("enter a value:"))
b=int(input("enter b value:"))
r,q=div(a,b)
print("reminder:",r)

Example2: Output:
def min_max(a): smallest: 1
small=min(a) biggest: 6
big=max(a)
return(small,big)
a=[1,2,3,4,6]
small,big=min_max(a)
print("smallest:",small)
print("biggest:",big)

Tuple as argument:

The parameter name that begins with * gathers argument into a tuple.

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

Integrated Lab Program


Python program to find the repeated items of a tuple.
Program:

tuple_1 =( 2, 4, 5, 6, 2, 3, 4, 4, 7)

print(tuple_1)

count = tuple_1.count(4)

print(count)
Output:

Dictionaries:

Dictionary is a collection of elements. An element in dictionary has a key: value pair.

All elements in dictionary are placed inside the curly braces i.e. { }

Elements in Dictionaries are accessed via keys and not by their position.

The values of a dictionary can be any data type.

Keys must be immutable data type (numbers, strings, tuple)
Operations on dictionary:
1. Accessing an element
2. Update
3. Add element
4. Membership
Operations Example Description

Creating a >>> a={1:"one",2:"two"} Creating the dictionary with


dictionary >>> print(a) elements of different data types.
{1: 'one', 2: 'two'}

accessing an >>> a[1] Accessing the elements by using


element 'one' keys.
>>> a[0]
KeyError: 0

Update >>> a[1]="ONE" Assigning a new value to key. It


>>> print(a) replaces the old value by new value.
{1: 'ONE', 2: 'two'}

add element >>> a[3]="three" Add new element in to the


>>> print(a) dictionary with key.
{1: 'ONE', 2: 'two', 3: 'three'}

membership a={1: 'ONE', 2: 'two', 3: 'three'} Returns True if the key is present in
>>> 1 in a dictionary. Otherwise returns false.
True
>>> 3 not in a
False

Methods in dictionary:
Copy()
Items()
Keys()
Values()
Pop()
Setdefault()
Update()
Fromkeys()
clear()
get()
popitem()
Syntax Example Description

dict.copy( ) a={1: 'ONE', 2: 'two', 3: 'three'} It returns copy of the


>>> b=a.copy() dictionary. here copy of
>>> print(b) dictionary ’a’ get stored
{1: 'ONE', 2: 'two', 3: 'three'} in to dictionary ‘b’
dict.items() >>> a.items() Return a new view of
dict_items([(1, 'ONE'), (2, 'two'), (3, the dictionary's items. It
'three')]) displays a list of
dictionary’s (key, value)
tuple pairs.
dict.keys() >>> a.keys() It displays list of keys in
dict_keys([1, 2, 3]) a dictionary
dict.values() >>> a.values() It displays list of values
dict_values(['ONE', 'two', 'three']) in dictionary
>>a.pop(3) Remove the element with
'three' key and return its
dict.pop(key) >>> print(a) value from the
{1: 'ONE', 2: 'two'} dictionary.

setdefault(key,value) >>> a.setdefault(3,"three") If key is in the


'three' dictionary, return its
>>> print(a) value. If key is not
{1: 'ONE', 2: 'two', 3: 'three'} present, insert key with
>>> a.setdefault(2) a value into dictionary and
'two' return value.
dict.update(dict) >>> b={4:"four"}
It will add the dictionary
>>> a.update(b)
with the existing
>>> print(a)
{1: 'ONE', 2: 'two', 3: 'three', 4: 'four'} Dictionary
dict.fromkeys(key,valu
e) >>> key={"apple","ball"} It creates a dictionary
>>> value="for kids" from key and values.
>>> d=dict.fromkeys(key,value)
>>> print(d)
{'apple': 'for kids', 'ball': 'for kids'}
dict.clear() a={1: 'ONE', 2: 'two', 3: 'three'} Remove all elements
>>>a.clear() from the dictionary.
>>>print(a)
>>>{ }
dict.get(key,value) >>>a={‘a’:1,’b’:2} Returns the value for the
>>>a.get(‘a’) given key if present in the
1 dictionary. If not it will
>>>a.get(‘c’) return none.
None
dict.popitem() >>>a={1: 'ONE', 2: 'two', } This method is used to
>>>a.popitem() remove a recently inserted
(2,’two’) key-value pair from a
>>>print(a) dictionary.
a={1:’ONE’}

del(dict) a={1: 'ONE', 2: 'two', 3: 'three'} It delete the entire


>>> del(a) dictionary.
Function: len(dict) a ={1: 'ONE', 2: 'two', 3: 'three'} It returns the length of
>>>len(a) the list.

Difference between List , Tuples and dictionary:

List Tuples Dictionary


A list is mutable A tuple is immutable A dictionary is mutable
Lists are dynamic Tuples are fixed size in nature values can be of any
data type and can
repeat, keys must be of
immutable type
List are enclosed in Tuples are enclosed in parenthesis ( ) Tuples are enclosed in
brackets[ ] and their and cannot be updated curly braces { } and
elements and size consist of key:value
can be changed
Homogenous Heterogeneous Homogenous
Example: Example: Example:
List = [10, 12, 15] Words = ("spam", "egss") Dict = {"ram": 26, "abi":
Or 24}
Words = "spam", "eggs"
Access: Access: Access:
print(list[0]) print(words[0]) print(dict["ram"])

Can contain duplicate Can contain duplicate elements. Cant contain duplicate
Elements Faster compared to lists keys, but can contain
duplicate values
Slicing can be done Slicing can be done Slicing can't be done
Usage: Usage: Usage:
List is used if a Tuple can be used when data Dictionary is used
collection of data that cannot be changed. when a logical
doesnt need random A tuple is used in combination association between
access. with a dictionary i.e.a tuple might key:value pair.
List is used when represent a key. When in need of fast
data can be modified lookup for data, based
frequently on a custom key.
Dictionary is used
when data is being
constantly modified.
Integrated lab Program

Python Program to merge two python dictionaries.


Program:
d1={'a':100,'b':200}
d2={'x':300,'y':200}
d=d1.copy()
d.update(d2)
print(d)
Output:

Integrated lab Program

Python program to print a dictionary where the keys are numbers between 1 and 10 and the
valuesare square of keys.
Program:
d=dict()
for x in range(1,11):
d[x]=x**2
print(d)
Output:

Sets in Python:
A set is an unordered collection of items. Every set element is unique (no duplicates) and must be
immutable (cannot be changed).
However, a set itself is mutable. We can add or remove items from it.
Sets can also be used to perform mathematical set operations like union, intersection, symmetric
difference, etc.
Creating Python Sets:

A set is created by placing all the items (elements) inside curly braces {}, separated by comma, or
by using the built-in set() function.
It can have any number of items and they may be of different types (integer, float, tuple, string etc.).
But a set cannot have mutable elements like lists, sets or dictionaries as its elements.

Program 1:
# Different types of sets in Python
# set of integers
my_set = {1, 2, 3}
print(my_set)
# set of mixed datatypes
my_set = {1.0, "Hello", (1, 2, 3)}
print(my_set)

Output:

{1, 2, 3}
{1.0, (1, 2, 3), 'Hello'}

Program 2:

# set cannot have duplicates


# Output: {1, 2, 3, 4}
my_set = {1, 2, 3, 4, 3, 2}
print(my_set)

# we can make set from a list


# Output: {1, 2, 3}
my_set = set([1, 2, 3, 2])
print(my_set)

# set cannot have mutable items


# here [3, 4] is a mutable list
# this will cause an error.
my_set = {1, 2, [3, 4]}

Output:

{1, 2, 3, 4}
{1, 2, 3}
Traceback (most recent call last):
File "<string>", line 15, in <module>
my_set = {1, 2, [3, 4]}
TypeError: unhashable type: 'list'

Creating an empty set is a bit tricky.


Empty curly braces {} will make an empty dictionary in Python. To make a set without any
elements, we use the set() function without any argument.
Program 3:
# Distinguish set and dictionary while creating empty set

# initialize a with {}
a = {}

# check data type of a


print(type(a))

# initialize a with set()


a = set()

# check data type of a


print(type(a))

Output:

<class 'dict'>
<class 'set'>

Modifying a set in Python:


Sets are mutable. However, since they are unordered, indexing has no meaning.
We cannot access or change an element of a set using indexing or slicing. Set data type does not
support it.
We can add a single element using the add() method, and multiple elements using
the update() method. The update() method can take tuples, lists, strings or other sets as its argument.
In all cases, duplicates are avoided.

Program 4:

# initialize my_set
my_set = {1, 3}
print(my_set)

#my_set[0]
# if you uncomment the above line
# you will get an error
# TypeError: 'set' object does not support indexing

# add an element
# Output: {1, 2, 3}
my_set.add(2)
print(my_set)

# add multiple elements


# Output: {1, 2, 3, 4}
my_set.update([2, 3, 4])
print(my_set)

# add list and set


# Output: {1, 2, 3, 4, 5, 6, 8}
my_set.update([4, 5], {1, 6, 8})
print(my_set)

Output:

{1, 3}
{1, 2, 3}
{1, 2, 3, 4}
{1, 2, 3, 4, 5, 6, 8}

Removing elements from a set:


A particular item can be removed from a set using the methods discard() and remove().
The only difference between the two is that the discard() function leaves a set unchanged if the
element is not present in the set. On the other hand, the remove() function will raise an error in such
a condition (if element is not present in the set).
The following example will illustrate this.
Program 5:

# Difference between discard() and remove()

# initialize my_set
my_set = {1, 3, 4, 5, 6}
print(my_set)
# discard an element
# Output: {1, 3, 5, 6}
my_set.discard(4)
print(my_set)
# remove an element
# Output: {1, 3, 5}
my_set.remove(6)
print(my_set)
# discard an element
# not present in my_set
# Output: {1, 3, 5}
my_set.discard(2)
print(my_set)
# remove an element
# not present in my_set
# you will get an error.
# Output: KeyError
my_set.remove(2)
Output:

{1, 3, 4, 5, 6}
{1, 3, 5, 6}
{1, 3, 5}
{1, 3, 5}
Traceback (most recent call last):
File "<string>", line 28, in <module>
KeyError: 2

Similarly, we can remove and return an item using the pop() method.
Since set is an unordered data type, there is no way of determining which item will be popped. It is
completely arbitrary.
Program 6:

We can also remove all the items from a set using the clear() method.
# initialize my_set
# Output: set of unique elements
my_set = set("HelloWorld")
print(my_set)
# pop an element
# Output: random element
print(my_set.pop())
# pop another element
my_set.pop()
print(my_set)
# clear my_set
# Output: set()
my_set.clear()
print(my_set)
Output:

{'H', 'l', 'r', 'W', 'o', 'd', 'e'}


H
{'r', 'W', 'o', 'd', 'e'}
set()

Python Set Operations:

Sets can be used to carry out mathematical set operations like union, intersection, difference and
symmetric difference. We can do this with operators or methods.
Let us consider the following two sets for the following operations.
>>> A = {1, 2, 3, 4, 5}
>>> B = {4, 5, 6, 7, 8}

Set Union:

Set Union in Python


Union of A and B is a set of all elements from both sets.
Union is performed using | operator. Same can be accomplished using the union() method.

Program 7:

# Set union method


# initialize A and B
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
# use | operator
# Output: {1, 2, 3, 4, 5, 6, 7, 8}
print(A | B)

Output:

{1, 2, 3, 4, 5, 6, 7, 8}

Set Intersection:

Set Intersection in Python


Intersection of A and B is a set of elements that are common in both the sets.
Intersection is performed using & operator. Same can be accomplished using
the intersection() method.

Program 8 :
# Intersection of sets
# initialize A and B
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
# use & operator
# Output: {4, 5}
print(A & B)

Output:

{4, 5}

Set Difference:

Set Difference in Python


Difference of the set B from set A(A - B) is a set of elements that are only in A but not in B.
Similarly, B - A is a set of elements in B but not in A.
Difference is performed using - operator. Same can be accomplished using the difference() method.

Program 9:
# Difference of two sets
# initialize A and B
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}

# use - operator on A
# Output: {1, 2, 3}
print(A - B)
Run Code
Output:

{1, 2, 3}

Set Symmetric Difference:

Set Symmetric Difference in Python


Symmetric Difference of A and B is a set of elements in A and B but not in both (excluding the
intersection).
Symmetric difference is performed using ^ operator. Same can be accomplished using the
method symmetric_difference().

Program 10:
# Symmetric difference of two sets
# initialize A and B
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}

# use ^ operator
# Output: {1, 2, 3, 6, 7, 8}
print(A ^ B)
Run Code
Output:

{1, 2, 3, 6, 7, 8}

Other Python Set Methods:

There are many set methods, some of which we have already used above. Here is a list of all the
methods that are available with the set objects:

Method Description

add() Adds an element to the set


clear() Removes all elements from the set
copy() Returns a copy of the set
difference() Returns the difference of two or more
sets as a new set
difference_update() Removes all elements of another set
from this set
discard() Removes an element from the set if it
is a member. (Do nothing if the
element is not in set)
intersection() Returns the intersection of two sets as
a new set
intersection_update() Updates the set with the intersection of
itself and another
isdisjoint() Returns True if two sets have a null
intersection
Returns True if another set contains
issubset() this set
issuperset() Returns True if this set contains
another set
pop() Removes and returns an arbitrary set
element. Raises KeyError if the set is
empty
remove() Removes an element from the set. If
the element is not a member, raises a
KeyError
symmetric_difference() Returns the symmetric difference of
two sets as a new set
symmetric_difference_update() Updates a set with the symmetric
difference of itself and another
union() Returns the union of sets in a new set
update() Updates the set with the union of itself
and others

Other Set Operations:

Set Membership Test

We can test if an item exists in a set or not, using the in keyword.


# in keyword in a set
# initialize my_set
my_set = set("apple")

# check if 'a' is present


# Output: True
print('a' in my_set)

# check if 'p' is present


# Output: False
print('p' not in my_set)

Output:

True
False

Built-in Functions with Set:

Built-in functions like all(), any(), enumerate(), len(), max(), min(), sorted(), sum() etc. are
commonly used with sets to perform different tasks.
Function Description
all() Returns True if all elements of the set
are true (or if the set is empty).
any() Returns True if any element of the set
is true. If the set is empty, returns
False.
Returns an enumerate object. It
enumerate() contains the index and value for all the
items of the set as a pair.
len() Returns the length (the number of
items) in the set.
max() Returns the largest item in the set.
min() Returns the smallest item in the set.
Returns a new sorted list from
sorted() elements in the set(does not sort the set
itself).
Returns the sum of all elements in the
sum()
set.
Python Frozenset:

Frozenset is a new class that has the characteristics of a set, but its elements cannot be changed once
assigned. While tuples are immutable lists, frozensets are immutable sets.
Sets being mutable are unhashable, so they can't be used as dictionary keys. On the other hand,
frozensets are hashable and can be used as keys to a dictionary.
Frozensets can be created using the frozenset() function.
This data type supports methods
like copy(), difference(), intersection(), isdisjoint(), issubset(), issuperset(), symmetric_difference()
and union(). Being immutable, it does not have methods that add or remove elements.
# Frozensets
# initialize A and B
A = frozenset([1, 2, 3, 4])
B = frozenset([3, 4, 5, 6])
Integrated Lab Program
Python program to perform set operation(Union, Intersection, Difference, Symmetric
Difference)
Program:
A={0,2,4,6.8}
B={1,2,3,4,5}
print("Union:",A|B)
print("Intersection:",A&B)
print("Difference:",A-B)
print("Symmetric difference:",A^B)
output:
21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING

UNIT V
FILES, MODULES, PACKAGES

1. FILE AND ITS OPERATION


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

File Type
1. Text file
2. Binary file

Text file Binary file


Text file is a sequence of characters that can A binary files store the data in the binary
be sequentially processed by a computer in format(i.e .0’s and 1’s)
forward direction
It contains any type of data
Each line is terminated with a special (pdf,images,word doc,spreadsheet,zip
character called the E0L or end of line files,etc)
character
Mode in File
Module Description
r Read only
w mode Write
a only Appending
r+ only
Read and write only
Differentiate write and append mode:
Write mode Append mode

 It is used to write a string in a file  It is used to append (add) a string


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

File Operation:
 Open a file
 Reading a file

VEL TECH HIGH TECH DR.RANGARAJAN DR.SAKUNTHALA ENGINEERING COLLEGE 1


21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING

 Writing a file
 Closing a file

VEL TECH HIGH TECH DR.RANGARAJAN DR.SAKUNTHALA ENGINEERING COLLEGE 1


21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING

1. Open ( ) function:

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


 The open function opens a file.
 It returns a something called a file object.
 File objects can turn methods and attributes that can be used to collect

Syntax:
file_object=open(“file_name” , ”mode”)

Example:
fp=open(“a.txt”,”r”)

Create a text file


fp=open (“text.txt”,”w”)

2. Read ( ) function
Read functions contains different methods

 read() – return one big string


 readline() – return one line at a time
 readlines() – return a list of lines

Syntax:
file_name.read ()

Example:
fp=open(“a.txt”,”w”)
print(fp.read())
print(fp.read(6))
print (fp.readline())
print (fp.readline(3))
print (fp.readlines())

a.txt

A file stores related data,


information, settings or commands
in secondary storage device like
magnetic disk, magnetic tape,
hello guysoptical disk, flash memory.

VEL TECH HIGH TECH DR.RANGARAJAN DR.SAKUNTHALA ENGINEERING COLLEGE 1


21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING

Output

VEL TECH HIGH TECH DR.RANGARAJAN DR.SAKUNTHALA ENGINEERING COLLEGE 1


21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING

Reading file using looping:


 Reading a line one by one in given file
fp=open(“a.txt”,”r”)
for line in fp:
print(line)

3. Write ( ) function
This method is used to add information or content to existing file.

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

Output: a.txt

A file stores related data,


information, settings or commands
in secondary storage device like
magnetic disk, magnetic tape,
optical disk, flash memory.
this file is a.txt to
add more lines

4. Close ( ) function
It is used to close the file.

Syntax:
File name.close()

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

VEL TECH HIGH TECH DR.RANGARAJAN DR.SAKUNTHALA ENGINEERING COLLEGE 1


21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING

fp.close()

VEL TECH HIGH TECH DR.RANGARAJAN DR.SAKUNTHALA ENGINEERING COLLEGE 1


21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING

Splitting line in a text line:


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

2. Write a program for one file content copy into another file:
source=open(“a.txt”,”r”)
destination=open(“b.txt”,”w”) for
line in source:
destination.write(line) source.
close() destination.close()

Output:
Input a.txt Output b.txt
A file stores related data, information, A file stores related data, information,
settings or commands in secondary storage settings or commands in secondary storage
device like magnetic disk, magnetic tape, device like magnetic disk, magnetic tape,
optical disk, flash memory optical disk, flash memory

3. Write a program to count number of lines, words and characters in a text file:
fp = open(“a.txt”,”r”)
line =0
word = 0
character = 0for line
in fp:
words = line . split ( )line =
line + 1
word = word + len(words) character =
character +len(line)
print(“Number of line”, line) print(“Number of
words”, word) print(“Number of character”,
character)
Output:
Number of line=5 Number of
words=15 Number of
character=47

VEL TECH HIGH TECH DR.RANGARAJAN DR.SAKUNTHALA ENGINEERING COLLEGE 1

107
21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING

Format Operator
The argument of write has to be a string, so if we want to put other values in afile,
we have to convert them to strings. The easiest way to do that is with str:
>>> f5=open('stringsample.txt','w')
>>>f5.write(5)
TypeError: expected a string or other character buffer object
>>>f5.write(str(5))
An alternative is to use the format operator, %. When applied to integers, %
is the modulus operator. But when the first operand is a string, % is the format operator.
The first operand is the format string, which contains one or more format sequences, whichspecify how
the second operand is formatted. The result is a string.
For example, the format sequence '%d' means that decimal value is converted to string.
Conversion Meaning
d Signed integer decimal.
i Signed integer decimal.
o Unsigned octal.
u Unsigned decimal.
x Unsigned hexadecimal (lowercase).
X Unsigned hexadecimal (uppercase).
e Floating point exponential format (lowercase).
E Floating point exponential format (uppercase).
f Floating point decimal format.
F Floating point decimal format.
g Same as "e" if exponent is greater than -4 or less than precision, "f" otherwise.
G Same as "E" if exponent is greater than -4 or less than precision, "F" otherwise.
c Single character (accepts integer or single character string).
r String (converts any python object using repr()).
s String (converts any python object using str()).
% No argument is converted, results in a "%" character in the result.
The result is the string '8', which is not to be confused with the integer value8.Some other format strings are.

A format sequence can appear anywhere in the string, so you can embed avalue
in a sentence:
>>> 'India need %d runs'%3
'India need 3 runs'
If there is more than one format sequence in the string, the second argument
has to be a tuple. Each format sequence is matched with an element of the tuple, in order.
>>> 'India need %d runs in %d balls'%(3,5)
'India need 3 runs in 5 balls'
The following example uses '%d' to format an integer, '%g' to format a
floating-point number, and '%s' to format a string:
>>> '%d %s price is %g rupees'%(5,'apple',180.50)'5
apple price is 180.500000 rupees'
The number of elements in the tuple has to match the number of format

VEL TECH HIGH TECH DR.RANGARAJAN DR.SAKUNTHALA ENGINEERING COLLEGE 1

108
21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING

sequences in the string. Also, the types of the elements have to match the format sequences:
>>> '%d %d %d' % (1, 2)
TypeError: not enough arguments for format string
>>> '%d' % 'apple'
TypeError: %d format: a number is required, not str
In the first example, there aren‘t enough elements; in the second, the element
is the wrong type.

Filenames and Paths


Files are organized into directories (also called ―folders‖). Every running
program has a ―current directory‖, which is the default directory for most operations. For
example, when you open a file for reading, Python looks for it in the current directory.
The os module provides functions for working with files and directories (―os‖ stands
for ―operating system‖). os.getcwd returns the name of the current directory:
>>> import os
>>>os.getcwd()
'C:\\Python27'
cwd stands for ―current working directory‖. A string like 'C:\\Python27' that
identifies a file or directory is called a path.
A simple filename, like 'stringsample.txt' is also considered a path, but it is a
relative path because it relates to the current directory.
If the current directory 'C:\\Python27', the filename 'stringsample.txt' wouldrefer to
'C:\\Python27\\stringsample.txt'.
A path that begins with drive letter does not depend on the current directory; itis
called an absolute path. To find the absolute path to a file, you can use os.path.abspath:
>>>os.path.abspath('stringsample.txt')'C:\\Python27\\stringsample.txt'

os.path provides other functions for working with filenames and paths. For
example, os.path.exists checks whether a file or directory exists:
>>>os.path.exists('memo.txt')
True
If it exists, os.path.isdir checks whether it‘s a directory:
>>>os.path.isdir('memo.txt')
False
>>>os.path.isdir ('C:\\Python27')
True
Similarly, os.path.isfile checks whether it‘s a file.
os.listdir returns a list of the files (and other directories) in the given directory:
>>>cwd=os.getcwd()
>>>os.listdir(cwd)
['DLLs', 'Doc', 'include', 'infinitLoop.py', 'Lib', 'libs', 'LICENSE.txt', 'NEWS.txt', 'parameter.py',
'python.exe', 'pythonw.exe', 'README.txt', 'sample.txt', 'sample2.txt', 'Scripts', 'stringsample.txt',
'swapwith third.py', 'tcl', 'Tools', 'w9xpopen.exe', 'wc.py', 'wc.pyc']
To demonstrate these functions, the following example ―walks‖ through a

VEL TECH HIGH TECH DR.RANGARAJAN DR.SAKUNTHALA ENGINEERING COLLEGE 1

109
21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING

directory, prints the names of all the files, and calls itself recursively on all the directories.
>>>def walk(dirname):
for name in os.listdir(dirname):
path = os.path.join(dirname, name)
ifos.path.isfile(path):
print(path)
else:
walk(path)
>>>cwd=os.getcwd()
>>>walk(cwd)

Output:
C:\Python27\DLLs\tcl85.dll
C:\Python27\include\abstract.h
C:\Python27\include\asdl.h
C:\Python27\include\ast.h
os.path.join takes a directory and a file name and joins them into a complete
path.
>>>os.path.join(cwd,'stringsample.txt')'C:\\Python27\\stringsample.txt'

COMMAND LINE ARGUMENTS

It is possible to pass some values from the command line to your python programs
when they are executed. These values are called command line arguments and many times they are
important for your program especially when you want to control your program from outside instead of
hard coding those values inside the code.
The command line arguments are handled using sys module. We can access
command-line arguments via the sys.argv. This serves two purposes −

 sys.argv is the list of command-line arguments.

 len(sys.argv) is the number of command-line arguments.

Here sys.argv[0] is the program nameie. script name.

Example 1
Consider the following script command_line.py

import sys
print 'There are %d arguments'%len(sys.argv)
print 'Argument are', str(sys.argv)
print 'File Name is: ', sys.argv[0]

VEL TECH HIGH TECH DR.RANGARAJAN DR.SAKUNTHALA ENGINEERING COLLEGE 1

110
21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING

Now run above script as follows – in Command prompt:


C:\Python27>python.exe command_line.py vinuranjith
This produce following result –
There are 3 arguments
Argument are ['command_line.py', 'vinu', 'ranjith']File
Name is: command_line.py
NOTE: As mentioned above, first argument is always script name and it is also being counted in
number of arguments. Here ‗vinu‘ and ‗ranjith‘ are extra inputs passed to program through
command line argument method while running python program command_line.py.

VEL TECH HIGH TECH DR.RANGARAJAN DR.SAKUNTHALA ENGINEERING COLLEGE 1

111
21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING

Example 2
This is a Python Program to copy the contents of one file into another. Source
and destination file names are given through command line argument while running the
program.

In order to do this we have to follow the following steps

1) Open file name with command line argument one as read mode (input file).
2) Open file name with command line argument two as write mode (output file).
3) Read each line from the input file and write it into the output file until the
input filedata getsover.
4) Exit.

Program
import sys source=open(sys.argv[1],'r')
destination=open(sys.argv[2],'w')
while(True):
new_line=source.readline()
ifnew_line=='':
break
destination.write(new_line)
source.close()
destination.close()

Now run above script as follows – in Command prompt:


C:\Python27>python.exe copy_file.py input_file.txt output_file.txt

VEL TECH HIGH TECH DR.RANGARAJAN DR.SAKUNTHALA ENGINEERING COLLEGE 1


21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING

INTEGRATED LAB PROGRAM


EXP NO: 10
DATE:
Write a python Program to count the number of lines in a File.

Program:

file_name = input("Enter file name:")


count_lines = 0
with open(file_name, 'r') as fo:
for line in fo:
count_lines += 1
print("Number of lines in the input file:",file_name, "is:",count_lines)

OUTPUT:
Enter file name:abc.txt
Number of lines in the input file: abc.txt is: 5

4. ERRORS,EXCEPTION HANDLING
Errors
 Error is a mistake in python also referred as bugs .they are almost always the fault of
the programmer.
 The process of finding and eliminating errors is called debugging
Types of errors
o Syntax error or compile time error
o Run time error
o Logical error
Syntax errors
 Syntax errors are the errors which are displayed when the programmer do mistakes
when writing a program, when a program has syntax errors it will not get executed
 Leaving out a keyword
 Leaving out a symbol, such as colon, comma, brackets
 Misspelling a keyword
 Incorrect indentation
Runtime errors
 If a program is syntactically correct-that is ,free of syntax errors-it will be run by
the python interpreter
 However, the program may exit unexpectedly during execution if it encounters a

VEL TECH HIGH TECH DR.RANGARAJAN DR.SAKUNTHALA ENGINEERING COLLEGE 1


21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING

runtime error.
 When a program has runtime error it will get executed but it will not produce output
 Division by zero
 Performing an operation on incompatible types
 Using an identifier which has not been defined
 Trying to access a file which doesn’t exit
Logical errors
 Logical errors are the most difficult to fix
 They occur when the program runs without crashing but produces incorrect result
 Using the wrong variable name
 Indenting a blocks to the wrong level
 Using integer division instead of floating point division
 Getting operator precedence wrong

Exception handling

Exceptions
 An exception is an error that happens during execution of a program. When that Error
occurs
Errors in python
 IO Error-If the file cannot be opened.
 Import Error -If python cannot find the module
 Value Error -Raised when a built-in operation or function receives an argument that
has the right type but an inappropriate value
 Keyboard Interrupt -Raised when the user hits the interrupt
 EOF Error -Raised when one of the built-in functions (input() or raw_input()) hits an
end-of-file condition (EOF) without reading any data

EXCEPTION NAME DESCRIPTION


Exception Base class for all exceptions
StopIteration Raised when the next() method of an iterator does not point to any object.
SystemExit Raised by the sys.exit() function.
StandardError Base class for all built-in exceptions except StopIteration and SystemExit.
ArithmeticError Base class for all errors that occur for numeric calculation.
OverflowError Raised when a calculation exceeds maximum limit for a numeric type.
FloatingPointError Raised when a floating point calculation fails.
ZeroDivisionError Raised when division or modulo by zero takes place for all numeric types.
AssertionError Raised in case of failure of the Assert statement.
AttributeError Raised in case of failure of attribute reference or assignment.
EXCEPTION NAME DESCRIPTION
Exception Base class for all exceptions
StopIteration Raised when the next() method of an iterator does not point to any object.
SystemExit Raised by the sys.exit() function.
StandardError Base class for all built-in exceptions except StopIteration and SystemExit.
ArithmeticError Base class for all errors that occur for numeric calculation.

VEL TECH HIGH TECH DR.RANGARAJAN DR.SAKUNTHALA ENGINEERING COLLEGE 1


21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING

OverflowError Raised when a calculation exceeds maximum limit for a numeric type.
FloatingPointError Raised when a floating point calculation fails.
ZeroDivisionError Raised when division or modulo by zero takes place for all numeric types.
AssertionError Raised in case of failure of the Assert statement.
AttributeError Raised in case of failure of attribute reference or assignment.
Exception Handling Mechanism
1. try –except
2. try –multiple except
3. try –except-else
4. raise exception
5. try –except-finally

1. Try –Except Statements


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

The try statement works as follows:-


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

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

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

2. Try – Multiple except Statements


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

VEL TECH HIGH TECH DR.RANGARAJAN DR.SAKUNTHALA ENGINEERING COLLEGE 1


21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING

statements

VEL TECH HIGH TECH DR.RANGARAJAN DR.SAKUNTHALA ENGINEERING COLLEGE 1


21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING

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

Output:1 Output 2: Output 3:


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

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

o Python will try to process all the statements inside try block. If value error occur,
the flow of control will immediately pass to the except block and remaining
statements in try block will be skipped.
Syntax:
try:
statements
except:
statements
else:
statements
Example
X=int(input(“Enter the value of X”))
Y=int(input(“Enter the value of Y”))
try:
result = X / ( X – Y )
except ZeroDivisionError:
print(“Division by Zero”)
else:
print(“result=”.result)
Output:1 Output : 2
Enter the value of X = 10 Enter the value of X = 10
Enter the value of Y = 5 Enter the value of Y = 10
Result = 2 Division by Zero

VEL TECH HIGH TECH DR.RANGARAJAN DR.SAKUNTHALA ENGINEERING COLLEGE 1


21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING

4. Raise statement
 The raise statement allows the programmer to force a specified exception to occur.
Example:
>>> raise NameError('HiThere')
Output:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: HiThere
 If you need to determine whether an exception was raised but don’t intend to handle
it, a simpler form of the raise statement allows you to re-raise the exception:
Example
try:
... raise NameError('HiThere')
... except NameError:
... print('An exception flew by!')
... raise
Output:
An exception flew by! Traceback
(most recent call last):
File "<stdin>", line 2, in <module>
NameError: HiThere
5. Try –Except-Finally
 A finally clause is always executed before leaving the try statement, whether an
exception has occurred or not.
 The finally clause is also executed “on the way out” when any other clause of the
try statement is left via a break, continue or return statement.
Syntax
try:
statements
except:
statements
finally:
statements
Example
X=int(input(“Enter the value of X”))
Y=int(input(“Enter the value of Y”))
try:
result = X / ( X – Y )
except Zero DivisionError:
print(“Division by Zero”)
else:
print(“result=”.result)
finally:
print (“executing finally clause”)
Output:1 Output : 2
Enter the value of X = 10 Enter the value of X = 10
Enter the value of Y = 5 Enter the value of Y = 10

VEL TECH HIGH TECH DR.RANGARAJAN DR.SAKUNTHALA ENGINEERING COLLEGE 1


21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING

Result = 2 Division by Zero


executing finally clause executing finally clause

VEL TECH HIGH TECH DR.RANGARAJAN DR.SAKUNTHALA ENGINEERING COLLEGE 1


21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING

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

1. Import statement:
 An import statement is used to import python module in some python source file.
Syntax: import module1 [, module2 […module]]
Example:
>>>import math
>>>print (math.pi)
3.14159265

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

3. Import file name


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

VEL TECH HIGH TECH DR.RANGARAJAN DR.SAKUNTHALA ENGINEERING COLLEGE 1


21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING

support.display (‘fleming’) #calling display() of support module with a string value

VEL TECH HIGH TECH DR.RANGARAJAN DR.SAKUNTHALA ENGINEERING COLLEGE 1


21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING

Output:
The result is 7
The result is 8.2
The result is ab
The result is yonaalex
Welcome, fleming
4. from……import statement:

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


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

5. OS Module
 The OS module in python provide function for interacting with operating
system
 To access the OS module have to import the OS module in our program
import os
method example description
name Osname ‘nt’ This function gives the name
of the operating system
getcwd() Os,getcwd() Return the current working
,C;\\Python34’ directory(CWD)of the file
used to execute the code
mkdir(folder) Os.mkdir(“python”) Create a directory(folder)
with the given name
rename(oldname,newname) Os.rename(“python”,”pspp”) Rename the directory or
folder

VEL TECH HIGH TECH DR.RANGARAJAN DR.SAKUNTHALA ENGINEERING COLLEGE 1


21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING

remove(“folder”) Os.remove(“pspp”) Remove (delete)the directory


or folder

VEL TECH HIGH TECH DR.RANGARAJAN DR.SAKUNTHALA ENGINEERING COLLEGE 1


21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING

getuid() Os.getuid() Return the current process’s


user id
environ Os.nviron Get the users environment

6. Sys Module
 Sys module provides information about constant, function and methods
 It provides access to some variables used or maintained by the interpreter

import sys
methods example description
sys.argv sys.argv Provides the list of
command line arguments
passed to a python script
sys.argv(0) Provides to access the file
name
sys.argv(1) Provides to access the first
input

sys.path sys.path It provide the search path


for module
sys.path.append() sys.path.append() Provide the access to
specific path to our program
sys.platform sys.platform Provide information about
‘win32’ the operating system
platform
sys.exit sys.exit Exit from python
<built.in function exit>

Steps to Create the Own Module


 Here we are going to create a calc module ; our module contains four functions
i.e add(),sub(),mul(),div()

Program for calculator module output


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

VEL TECH HIGH TECH DR.RANGARAJAN DR.SAKUNTHALA ENGINEERING COLLEGE 1


21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING

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

Steps to Create a Package


Step1: create the package directory
 Create the directory (folder)and give it your packages name
 Here the package name is calculator
Name Data modified Type
1. pycache 05-12-2017 File folder
2.calculater 08-12-2017 File folder
3. DLLs 10-12-2017 File folder

Step2: write module for calculator directory add save the module in calculator directory
 Here four module have create for calculator directory

Local Disk (C)>Python34>Calculator

Name Data modified Type Size


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

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


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

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


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

VEL TECH HIGH TECH DR.RANGARAJAN DR.SAKUNTHALA ENGINEERING COLLEGE 1


21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING

Add the following code in the init .py file

from * add import add


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

Local Disk (C):/Python34>Calculator


Name Data modified Type Size
1. init 08-12-2017 File folder 1KB
2. add 08-12-2017 File folder 1KB
3. div 08-12-2017 File folder 1KB
4. mul 08-12-2017 File folder 1KB
5. sub 08-12-2017 File folder 1KB

Step4: To test your package


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

Output :
>>> 15
5
50
2
Two marks:

1. Why do we go for file?


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

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


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

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

VEL TECH HIGH TECH DR.RANGARAJAN DR.SAKUNTHALA ENGINEERING COLLEGE 1


21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING

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

4. Differentiate error and exception.


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

5. Give the methods of exception handling.


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

VEL TECH HIGH TECH DR.RANGARAJAN DR.SAKUNTHALA ENGINEERING COLLEGE 1


21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING

6. State the syntax for try…except block


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

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

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

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

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


Import os
print(os.getcwd))

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

VEL TECH HIGH TECH DR.RANGARAJAN DR.SAKUNTHALA ENGINEERING COLLEGE 1


21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING

11. Give the use of format operator


The argument of write has to be a string, so if we want to put other values in a file, we
have to convert them to strings. The easiest way to do that is with str:
>>> x = 52
>>> fout.write(str(x))
An alternative is to use the format operator, %. When applied to integers, % is the
modulus operator. But when the first operand is a string, % is the format operator. The
first operand is the format string, which contains one or more format sequences,
which specify how the second operand is formatted. The result is a string. For
example, the format sequence '%d' means that the second operand should be
formatted as an integer (d stands for “decimal”):
>>> camels = 42
>>>'%d' % camels '42'
The result is the string '42', which is not to be confused with the integer value 42.
12. Write the snippet to find the absolute path of a file.
import os
os.path.abspath('w
rite.py')
Output:
'C:\\Users\\Mano\\Desktop\\write.py'

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


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

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


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

15. What is command line argument?


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

VEL TECH HIGH TECH DR.RANGARAJAN DR.SAKUNTHALA ENGINEERING COLLEGE 1


21CS15IT-PROBLEM SOLVING AND PYTHON PROGRAMMING

VEL TECH HIGH TECH DR.RANGARAJAN DR.SAKUNTHALA ENGINEERING COLLEGE 1

You might also like