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

Python Unit 1 To 5

Uploaded by

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

Python Unit 1 To 5

Uploaded by

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

Subject Subject Name Cate L T P S Cr Marks

Code gory ed CIA Ext Total


its er
na
l
PYTHON CCI 5 - - I 4 25 75 100
PROGRAMMING
Learning Objectives
LO1 To make students understand the concepts of Python programming.
LO2 To apply the OOPs concept in PYTHON programming.
LO3 To impart knowledge on demand and supply concepts
LO4 To make the students learn best practices in PYTHON programming

LO5 To know the costs and profit maximization


UNIT Contents No. of
Hours
I Basics of Python Programming: History of Python-Features of Python-Literal-
Constants-Variables - Identifiers–Keywords-Built-in Data Types-Output
Statements – Input Statements-Comments – Indentation- Operators-Expressions- 15
Type conversions. Python Arrays: Defining and Processing Arrays – Array
methods.

II Control Statements: Selection/Conditional Branching statements: if, if-else,


nested if and if-elif-else statements. Iterative Statements: while loop, for loop, else
suite in loop and nested loops. Jump Statements: break, continue and pass 15
statements.

III Functions: Function Definition – Function Call – Variable Scope and its
Lifetime-Return Statement. Function Arguments: Required Arguments,
Keyword Arguments, Default Arguments and Variable Length Arguments-
15
Recursion. Python Strings: String operations- Immutable Strings - Built-in
String Methods and Functions - String Comparison.
Modules: import statement- The Python module – dir() function – Modules and
Namespace – Defining our own modules.
IV Lists: Creating a list -Access values in List-Updating values in Lists- Nested lists
-Basic list operations-List Methods. Tuples: Creating, Accessing, Updating and
Deleting Elements in a tuple – Nested tuples– Difference between lists and 15
tuples. Dictionaries: Creating, Accessing,
Updating and Deleting Elements in a Dictionary – Dictionary Functions
and Methods - Difference between Lists and Dictionaries.
V Python File Handling: Types of files in Python - Opening and Closing files-
Reading and Writing files: write() and writelines() methods- append() method –
read() and readlines() methods – with keyword – Splitting words 15
– File methods - File Positions- Renaming and deleting files.

TOTAL HOURS 75

Course Outcomes Programme


Outcomes
CO On completion of this course, students will
Learn the basics of python, Do simple programs on python, PO1, PO2, PO3,
CO1
Learn how to use an array. PO4, PO5, PO6

Develop program using selection statement, Work with Looping PO1, PO2, PO3,
CO2
and jump statements, Do programs on Loops and jump statements. PO4, PO5, PO6

Concept of function, function arguments, Implementing the


CO3 PO1, PO2, PO3,
concept strings in various application, Significance of Modules, PO4, PO5, PO6
Work with functions, Strings and modules.
CO4 Work with List, tuples and dictionary, Write program using list, PO1, PO2, PO3,
tuples and dictionary. PO4, PO5, PO6
CO5 Usage of File handlings in python, Concept of reading and PO1, PO2, PO3,
writing files, Do programs using files. PO4, PO5, PO6

Textbooks
1 Reema Thareja, “Python Programming using problem solving approach”, First Edition,
2017, Oxford University Press.

2 Dr. R. Nageswara Rao, “Core Python Programming”, First Edition, 2017, Dream tech
Publishers.

Reference Books
1. VamsiKurama, “Python Programming: A Modern Approach”, Pearson Education.
2. Mark Lutz, ”Learning Python”, Orielly.
3. Adam Stewarts, “Python Programming”, Online.
4. Fabio Nelli, “Python Data Analytics”, APress.
5. Kenneth A. Lambert, “Fundamentals of Python – First Programs”, CENGAGE
Publication.

Web Resources
1. https://www.programiz.com/python-programming
Python programming

Unit - I
Python

Python is an interpreted, object-oriented, high-level programming language with dynamic semantics developed by
Guido van Rossum. It was originally released in 1991.
Python is used for server-side web development, software development, mathematics, and system scripting, and is
popular for Rapid Application Development and as a scripting or glue language to tie existing components because
of its high-level, built-in data structures, dynamic typing, and dynamic binding. Program maintenance costs are
reduced with Python due to the easily learned syntax and emphasis on readability. Additionally, Python's support of
modules and packages facilitates modular programs and reuse of code. Python is an open source community
language, so numerous independent programmers are continually building libraries and functionality for it.

Features and History of Python:


Features of Python
Simple: Reading a program written in Python feels almost like reading english. The main strength of Python
which allows programmer to concentrate on the solution to the problem rather than language itself.
Easy to Learn: Python program is clearly defined and easily readable. The structure of the program is simple.
It uses few keywords and clearly defined syntax.
Versatile: Python supports development of wide range of applications such as simple text processing, WWW
browsers and games etc..
Free and Open Source: It is a Open Source Software. So, anyone can freely distribute it, read the source
code, edit it, and even use the code to write new (free) programs.
High-level Language: While writing programs in Python we do not worry about the low-level details like
managing memory used by the program.
Interactive: Programs in Python work in interactive mode which allows interactive testing and debugging of
pieces of code. Programmer can easily interact with the interpreter directly at the python prompt to write
their programs.
Portable: It is a portable language and hence the programs behave the same on wide variety of hardware
platforms with different operating systems.
Object Oriented: Python supports object-oriented as well as procedure-oriented style of programming .While
object-oriented technique encapsulates data and functionality with in objects, Procedure oriented at other
hand, builds programs around procedure or functions.
Interpreted: Python is processed at runtime by interpreter. So, there is no need to compile a program before
executing it. You can simply run the program. Basically python converts source program into intermediate
form called byte code.

Dynamic and strongly typed language: Python is strongly typed as the interpreter keeps
track of all variables types. It's also very dynamic as it rarely uses what it knows to limit variable usage.
Embeddable: Programmers can embed Python within their C, C++, COM, ActiveX, CORBA and Java
Programs to give „scripting „capability for users.
Extensive Libraries: Python has huge set of libraries that is easily portable across different platforms with
different operating systems.
Easy maintenance: Code Written in Python is easy to maintain.
Secure: This Programming language is secure for tampering. Modules can be distributed to prevent altering of
source code. Additionally, Security checks can be easily added to implement additional security features.

History of Python.
Python was first developed by Guido van Rossum in the late 80‟s and early 90‟s at the National Research
Institute for Mathematics and Computer Science in the Netherlands.
It has been derived from many languages such as ABC, Modula-3, C, C++, Algol-68, SmallTalk, UNIX shell
and other scripting languages.
Since early 90‟s Python has been improved tremendously. Its version 1.0 was released in 1991, which
introduced several new functional programming tools.

While version 2.0included list comprehension was released in 2000 by the Be Open Python Labs team.
Python 2.7 which is still used today will be supported till 2020.
Currently Python 3.6.4 is already available. The newer versions have better features like flexible string
representation e.t.c,
Although Python is copyrighted, its source code is available under GNU General Public License (GPL) like
that Perl.
Python is currently maintained by a core development team at the institute which is directed by Guido Van
Rossum.
These days, from data to web development, Python has emerged as very powerful and popular language. It
would be surprising to know that python is actually older than Java, R and JavaScript.

Applications of Python:

Embedded scripting language: Python is used as an embedded scripting language for various testing/ building/
deployment/ monitoring frameworks, scientific apps, and quick scripts.
3D Software: 3D software like Maya uses Python for automating small user tasks, or for doing more complex
integration such as talking to databases and asset management systems.
Web development: Python is an easily extensible language that provides good integration with database and other
web standards.
GUI-based desktop applications: Simple syntax, modular architecture, rich text processing tools and the ability to
work on multiple operating systems makes Python a preferred choice for developing desktop-based applications.
Image processing and graphic design applications: Python is used to make 2D imaging software such as
Inkscape, GIMP, Paint Shop Pro and Scribus. It is also used to make 3D animation packages, like Blender, 3ds
Max, Cinema 4D, Houdini, Light wave and Maya.
Scientific and Computational applications: Features like high speed, productivity and availability of tools, such
as Scientific Python and Numeric Python, have made Python a preferred language to perform computation and
processing of scientific data. 3D modeling software, such as FreeCAD, and finite element method software, like
Abaqus, are coded in Python.
Games: Python has various modules, libraries, and platforms that support development of games. Games like
Civilization-IV, Disney's Toontown Online, Vega Strike, etc. are coded using Python.
Enterprise and Business applications: Simple and reliable syntax, modules and libraries, extensibility, scalability
together make Python a suitable coding language for customizing larger applications. For example, Reddit which
was originally written in Common Lips, was rewritten in Python in 2005. A large part of Youtube code is also
written in Python.
Operating Systems: Python forms an integral part of Linux distributions.
Keyword in Python:

Keywords are the reserved words in Python. We cannot use a keyword as variable name, function name or any
other identifier.
Here's a list of all keywords in Python Programming.
There are 33 keywords in Python 3.3. This number can vary slightly in course of time.
All the keywords except True, False and None are in lowercase and they must be written as it is. The list of all the
keywords are given below.

Keywords in Python Programming Language


False class finally is return
None continu for lambda try
e
True def from nonloca while
l
and del global not with

as elif if or yield
assert else import pass
break except in raise

Literal Constants
Numeric Literals
Boolean Literals
String Literals

Literal Constants
In programming constants are referred to variables that cannot be changed.
Generally Literal constants are classified in to three types.

Numeric Literals
The value of a literal constant can be used directly in programs. For example, 7, 3.9, 'A', and "Hello" are literal
constants.
Numbers refers to a numeric value. You can use four types of numbers in Python program- integers, long integers,
floating point and complex numbers.
Numbers like 5 or other whole numbers are referred to as integers. Bigger whole numbers are called long integers.
For example, 535633629843L is a long integer.
Numbers like are 3.23 and 91.5E-2 are termed as floating point numbers.
Numbers of a + bj form (like -3 + 7j) are complex numbers.
Boolean Literals
A Literals Boolean type can have one of the two values- True or False.

String Literals
A string is a group of characters.
Using Single Quotes ('): For example, a string can be written as 'HELLO'.
Using Double Quotes ("): Strings in double quotes are exactly same as those in single quotes. Therefore, 'HELLO'
is same as "HELLO".
Using Triple Quotes (''' '''): You can specify multi-line strings using triple quotes. You can use as many single
quotes and double quotes as you want in a string within triple quotes.

Escape Sequences
Some characters (like ", \) cannot be directly included in a string. Such characters must be escaped by placing a
backslash before them.

Raw Strings
If you want to specify a string that should not handle any escape sequences and want to display exactly as specified
then you need to specify that string as a raw string. A raw string is specified by prefixing r or R to the string.

Example:

Data types
The variables can hold values of different type called Data Type.
Data type is a set of values and the allowable operations on those values.
Python has a great set of useful data types. Python's data types are built in the core of the language. They are easy to
use and straightforward.
Example a person age is stored in a number ,his name is made only with characters, and his address is made with
mixture of numbers and characters.
Python ha various standard data types to define the operations possible on them and storage method for each of
them.
Python supports the following five standard data types

1.Numbers
2.Strings
3.Lists
4.Tuple
5.Dictionary
6. Sets

Assigning or Initializing Values to Variables


In Python, programmers need not explicitly declare variables to reserve memory space. The declaration is done
automatically when a value is assigned to the variable using the equal sign (=). The operand on the left side of equal
sign is the name of the variable and the operand on its right side is the value to be stored in that variable.

Example: Program to display data of different types using variables and literal constants.

In Python , you can reassign variables as many times as you want to change the value stored in them. You may even
store value of one data type in a statement and other data type in subsequent statement. This is possible because
Python variables do not have specific types, i.e., we can assign integer to the variable, later we assign string to the
same variable.
Example:Program to reassign value to a variable
val = „Hello‟
print(val)
val = 100
print(val)
val=10.32

print(val)
Output
Hello
100
10.32

Multiple Assignments
Python allows programmers to assign single value to more than one variable simultaneously.
For example

>>>sum = flag = a = b = 0
In the above statement, all four integer variables are assigned a value 0.You can also assign different values to
multiple variables simultaneously as shown below
For example

>>>sum, a, b, mesg = 0, 3, 5, “Result”


Here, variable sum,a and b are integers(numbers) and mesg is assigned “Result”.
Note: Removing a variable means that the reference from the name to the value has been deleted.However, deleted
variables can be used again in the code if and only if you reassign them some value.

Boolean Type

A variable of Boolean type can have one of the two values- True or False.
Similar to other variables, the Boolean variables are also created while we assign a value to them or when we use a
relational operator on them.

TUPLE

A tuple is similar to the list as it also consists of a number of values separated by commas and enclosed within
parentheses.
The main difference between lists and tuples is that you can change the values in a list but not in a tuple. This
means that while tuple is a read only data type, the list is not.
Lists
Lists are the most versatile data type of Python language.
A list consist of items separated by commas and enclosed within square brackets The values stored in a list are
accessed using indexes.
The index of the first element being 0 and n-1 as that of the last element, where n is the total number of elements in
the list. Like strings, you can also use the slice, concatenation and repetition operations on lists.
Example program to demonstrate operations on lists

list = ['a', 'bc', 78, 1.23]


list1 = ['d', 78]
print(list)
print(list[0])

print(list[1:3])
print(list[2:])
print(list * 2)
print(list + list1)
Output:
['a', 'bc', 78, 1.23]
a
['bc', 78]
[78, 1.23]
['a', 'bc', 78, 1.23, 'a', 'bc', 78, 1.23]
['a', 'bc', 78, 1.23, 'd', 78]
Dictionary
Python‟s dictionaries stores data in key-value pairs.
The key values are usually strings and value can be of any data type. The key value pairs are enclosed with curly
braces ({ }).
Each key value pair separated from the other using a colon (:). To access any value in the dictionary, you just need
to specify its key in square braces ([]).Basically dictionaries are used for fast retrieval of data.

SET
Set is an unordered collection of unique items.set is defined by values seperated by commas inside braces{ }.
For example
Sid={11,12,13,16}
Print(sid)

Variables and Identifiers


Variables
python variable is container that store values.
 Python is not statically typed user do not need to declare variables before using them or declare their type.
 Python variable is a name given to a memory location. It is the basic unit of a storage location.

Identifiers
Identifiers are names given to identify something. This something can be a variable, function, class, module or
other object. For naming any identifier, there are some basic rules like:
The first character of an identifier must be an underscore ('_') or a letter (upper or lowercase).
The rest of the identifier name can be underscores ('_'), letters (upper or lowercase), or digits (0-9).
Identifier names are case-sensitive. For example, myvar and myVar are not the same.
Punctuation characters such as @, $, and % are not allowed within identifiers.
Examples of valid identifier names are sum, __my_var, num1, r, var_20, First, etc.
Examples of invalid identifier names are 1num, my-var, %check, Basic Sal, H#R&A, etc.,

5. Operators
Operators are special symbols in Python that carry out arithmetic or logical computation. The value that the
operator operates on is called the operand.
For example:

>>> 2+3
5
Here, + is the operator that performs addition. 2 and 3 are the operands and 5 is the output of the operation.

Python supports the following operators


1. Arithmetic operators
2. Comparison (Relational) operators
3. Unary Operators
4. Bitwise operators
5. Shift Operators
6. Logical Operators
7. Membership and Identity Operators
8. Assignment operators

Arithmetic Operators
Arithmetic operators are used to perform mathematical operations like addition, subtraction, multiplication etc.
This operator will work on two operands.
Example: If a=100 and b=200 then look at the table below, to see the result of arithmetic operations.
Comparision (Relational) Operators
A Relational or Comparison operator checks the relationship between two operands. If the relation is true, it
returns 1; if the relation is false, it returns value 0

For Example assuming a=100 and b=2000,we can use the comparison operators on them as specified in the
following table.

Unary Operator

Unary operators act on single operands. Python supports unary minus operator.
Unary minus operator is strikingly different from the arithmetic operator that operates on two operands and
subtracts the second operand from the first operand.
When an operand is preceded by a minus sign, the unary operator negates its value.
For example, if a number is positive, it becomes negative when preceded with a unary minus operator. Similarly, if
the number is negative, it becomes positive after applying the unary minus operator. Consider the given example.

b = 10 a = -(b)
The result of this expression, is a = -10, because variable b has a positive value. After applying unary minus
operator (-) on the operand b, the value becomes -10, which indicates it as a negative value.

Bitwise Operators
As the name suggests, bitwise operators perform operations at the bit level.
These operators include bitwise AND, bitwise OR, bitwise XOR, and shift operators.
Bitwise operators expect their operands to be of integers and treat them as a sequence of bits.
The truth tables of these bitwise operators are given below.

Example: If a=60 and b=13 then look at the table below, to see the result of Bitwise operations.

Operator Description Example


& Operator copies a bit to the (a & b) =12 (means 0000
Binary AND result if it exists in both 1100)
operands
| It copies a bit if it exists in (a | b) = 61 (means 0011
Binary OR either operand. 1101)
^ It copies the bit if it is set in (a ^ b) = 49 (means 0011
Binary XOR one operand but not both. 0001)
~ It is unary and has the effect (~a ) = -61 (means 1100
Binary Ones Complement of 'flipping' bits. 0011 in 2's complement
form due to a signed

<< The left operands value is a << 2 = 240 (means 1111


Binary Left Shift moved left by the number 0000)
of bits specified by the right
operand.
>> The left operands value is a >> 2 = 15 (means 0000
Binary Right Shift moved right by the number 1111)
of bits specified by the right
operand.
Shift Operators
Python supports two bitwise shift operators. They are shift left (<<) and shift right (>>).
These operations are used to shift bits to the left or to the right. The syntax for a shift operation can be given as
follows:

Logical Operators
Logical operators are used to simultaneously evaluate two conditions or expressions with relational operators.
Logical AND (and) If expressions on both the sides (left and right side) of the logical operator are true, then the
whole expression is true.

For example, If we have an expression (a>b) and (b>c), then the whole expression is true only if both expressions
are true. That is, if b is greater than a and c.

Logical OR (or) operator is used to simultaneously evaluate two conditions or expressions with relational operators.
If one or both the expressions of the logical operator is true, then the whole expression is true.
For example, If we have an expression (a>b) or (b>c), then the whole expression is true if either b is greater than a
or b is greater than c.
Logical NOT (not) operator takes a single expression and negates the value of the expression. Logical NOT
produces a zero if the expression evaluates to a non-zero value and produces a 1 if the expression produces a zero.
In other words, it just reverses the value of the expression.

For example, a = 10; b = not a; Now, the value of b = 0.


Membership and Identity Operators
Membership Operator
Python supports two types of membership operators–in and not in. These operators, test for membership in a
sequence such as strings, lists, or tuples.
in Operator: The operator returns true if a variable is found in the specified sequence and false otherwise.
not in Operator: The operator returns true if a variable is not found in the specified sequence and false otherwise.
Example:
x=’Hello world’
y={1:’a’,2:’b’}
Print(‘H’ in x)
Print(‘hello’ not in x)

Identity Operators
is Operator: Returns true if operands or values on both sides of the operator point to the same object and false
otherwise.

For example a=10


b=10

Print(a is b)
Output

True
if a is b returns 1, if id(a) is same as id(b).
is not Operator: Returns true if operands or values on both sides of the operator does not point to the same object
and false otherwise.
For example,
A=10
B=20
Print(a is not b)
Output
true
if a is not b returns 1, if id(a) is not same as id(b).
5.8 Assignment Operators
Assignment operators are used in Python to assign values to variables.

a = 5 is a simple assignment operator that assigns the value 5 on the right to the variable a on the left.
There are various compound operators in Python like a += 5 that adds to the variable and later assigns the same. It
is equivalent to a = a + 5.
Assignment operators in Python
Operator Example Equivatent
to
= x=5 x=5
+= x += 5 x=x+5
-= x -= 5 x=x-5
*= x *= 5 x=x*5
/= x /= 5 x=x/5
%= x %= 5 x=x%5
//= x //= 5 x = x // 5
**= x **= 5 x = x ** 5
&= x &= 5 x=x&5
|= x |= 5 x=x|5
^= x ^= 5 x=x^5
>>= x >>= 5 x = x >> 5

Input Operation
To take input from the users, Python makes use of the input( ) function. The input( ) function prompts the user to
provide some information on which the program can work and give the result.
However, we must always remember that the input function takes user‟s input as a string.

Comments
Comments are the non-executable statements in a program. They are just added to describe the statements in the
program code.
Comments make the program easily readable and understandable by the programmer as well as other users who are
seeing the code. The interpreter simply ignores the comments.
In Python, a hash sign (#) that is not inside a string literal begins a comment. All characters following the # and up
to the end of the line are part of the comment
Indentation
Whitespace at the beginning of the line is called indentation. These whitespaces or the indentation are very
important in Python.
Where as indentation in code is only for readability in other programming languages.it is critical in python employs
indentation to denote a block of code.
Rules
 Python default indentation spaces are four spaces
 Indentation is not permitted on the first line of python code.
 Python requires indentation to define statement blocks.
 A block of code must have a consistent number of spaces.
 To indent in Python, whitespaces are preferred over tabs. Also, use either whitespace or tabs to indent; mixing
tabs and whitespaces in indentation can result in incorrect indentation errors.

Example

j=1
while(j<= 5):
print(j)
j=j+1

Expressions

An expression is any combination of symbols (like variables, constants and operators) that represents a value.

In Python, an expression must have at least one operand (variable or constant) and can have one or more operators.
On evaluating an expression, we get a value. Operand is the value on which operator is applied.
Generally Expressions are divided into the following types
1. Constant Expressions: One that involves only constants.
Example: 8 + 9 – 2
2. Integral Expressions: One that produces an integer result after evaluating the expression.

Example:a = 10
3. Floating Point Expressions: One that produces floating point results.

Example: a * b / 2.0
4. Relational Expressions: One that returns either true or false value.
Example: c = a>b
5. Logical Expressions: One that combines two or more relational expressions and returns a value as True or False.

Example: a>b and y! = 0


6. Bitwise Expressions: One that manipulates data at bit level.

Example: x = y&z
7. Assignment Expressions: One that assigns a value to a variable.

Example: c = a + b or c = 10
Example Program:
Give the output for the following statements)
a = 20
b = 10
c = 15
d=5
print ("a:%d b:%d c:%d d:%d" % (a,b,c,d ))
e = (a + b) * c / d
d) is ", e)
e = a + (b * c) / d
print ("Value of a + (b * c) / d is ", e)
Output:
a:20 b:10 c:15 d:5
Value of (a + b) * c / d is 90.0
Value of ((a + b) * c) / d is 90.0
Value of (a + b) * (c / d) is 90.0
Value of a + (b * c) / d is 50.0

Operator Precedence
The operator precedence in Python are listed in the following table.
It is in descending order, upper group has higher precedence than the lower ones.
Operator precedence rule in Python
Operators Meaning
() Parentheses
** Exponent
+x, -x, ~x Unary plus, Unary minus, Bitwise NOT
*, /, //, % Multiplication, Division, Floor division,
Modulus
+, - Addition, Subtraction
<<, >> Bitwise shift operators
& Bitwise AND
^ Bitwise XOR
| Bitwise OR
==, !=, >, >=, <, <=, is, is not, in, not in Comparison, Identity, Membership
operators

not Logical NOT


and Logical AND
or Logical OR
Associativity rule
All the operators,except(**)follow the left to right associativity.
It means the valuation will proceed from left to right while evaluating the expression.
ARRAY

An Array Is A Collection Of Related Data Items Of The Same Data Type.


An array is used to store more than one value at a time.

Creating an array in python

An array is created by importing an array module to the Python program.


Syntax:
from array import *
arrayName = array(typecode, [ Initializers ])
Example
from array import *
a= array(‘i’,[10,20,30,40,50])

Typecodes are alphabetic representations that are used to define the type of value the array is going to store. Some
common typecodes are:

Typecode value

B Represents signed integer of size 1 byte

B Represents unsigned integer of size 1 byte

C Represents character of size 1 byte

I Represents signed integer of size 2 byte

F Represents floating point numbers of size4 bytes

D Represents floating point numbers of size 8 bytes

L Represents unsigned integer of size 2 byte

Accessing the array Elements

To access an array elemt, you need to specify the index number. Indexing starts at index 0
Hence, the index number is always one less than the length of the array.

Example

From array import *


a=array(‘i’,[10,20,30,40])
Print(a[0])
Print(a[1])

Array methods

Insert()
insert()function is used to insert an element to the array at a specific index or position.
It will take pos, and value as its parameters
where pos variables tell the position and value is the value need to insert into array.

Syntax
Arrayname.insert(index,value)

Example
a = array('i',[1,2,3,4])
a. insert(2,9)
print("Array after inserting 9 is", a)

append(value)
append() function is used to add value or append a value to the existing array in the end. It will take the value
which we want to add as an argument.
Syntax

Arrayname.append(value)

Ex

a. append(6)

print(a)

remove(value)
remove() function is used to remove the given element from the array. It will take value to remove as an argument
and removes the element from the array and it won’t display the element.

Syntax

Remove(value)
example

remove(9)

print(a)

extend(arr)
extend() function is used to add an array of values at the end of the existing array created. It will take an array of
values or an array as its input argument.

Syntax

Arrayname.extend([array values])

a. extend([7,5,8])

print(a)

pop()
The above function, pop() is used to remove an element from the array. It can take the argument as a position of the
element we want to remove or by default it removes the element at the last index.

Ex:

a.pop()

It removes last element in the array and displays element.

a.pop(4)

It removes the element at 4th index position in the array and displays element

reverse()
To Reverses the order of an array list

Ex:

a.reverse()

print("Array after reverse is:",a)

count(value)
The above function, count() will tell the total number of occurrences of the given value in the array. It will take a
value as an argument to it to know the total number of occurrences.

a. extend([2,1,3,2,1])

a.count(2)

Type conversion

Python defines type conversion functions to directly convert one data type to another
There are two types of Type Conversion in Python:
1. Implicit Type Conversion
2. Explicit Type Conversion

Implicit Type Conversion

In Implicit type conversion of data types in Python, the Python interpreter automatically converts one data type to
another .this is known as type coercion.
For example
Converting int to float
Python promotes the conversion of the lower data type(int) to the higher data type(float) to avoid data loss.
a=123
b=45.6
c=a+b
print(“value=”,c)
output
168.6

Explicit type conversion

User convert the data type of an object to required data type.

This type of conversion is also called typecasting because the user casts(changes) the datatype of the objects.

There is a risk of data loss since we are forcing an expression to be changed in some specific data loss

Example

S=’12’

a=23

S=int(s)

C=s+a

Print(“sum=”,c)

Function Description

float(x) It converts x to a floating-point number.

Int(x) It converts x to a interger number


str(x) It converts y to a string.

Tuple(x) It converts y to a tuple.

list(x) It converts y to a list.

set(x) It converts y to a set.

dict(x) It creates a dictionary and y should be a sequence of (key, value) tuples.

ord(x) It converts a character into an integer.

hex(x) It converts an integer to a hexadecimal string.

oct(x) It converts an integer to an octal string


UNIT - II

Conditional statement

A program’s control flow is the order in which the program’s code executes.

The control flow of a Python program is regulated by conditional statements, loops, and function calls.

Python has three types of control structures:

 Sequential
 Selection
 Repetition

Sequential

Sequential statements are a set of statements whose execution process happens in a sequence. The problem
with sequential statements is that if the logic has broken in any one of the lines, then the complete source
code execution will break.
Example
a=10
b=20
c=a-b
Print(c)

Selection/Decision control statements

The selection statement allows a program to test several conditions and execute instructions based on which
condition is true.Some decision control statements are:

 if
 if-else
 nested if
 if-elif-else

if Statement:

An if statement is a selection control statement which is based on the valueof a given Boolean Expression.

Syntax:

if test_expression:

statement 1

.....

statement n

statement x

 if structure may include 1 or n statements enclosed within if block.


 First, test expression is evaluated. If the test expression is true, thestatement of if block (statement 1 to n) are
executed, otherwise thesestatements will be skipped and the execution will jump to statement x.

Flowchart:

Example

X=10

If(x>0):

x=x+1

Print(x)

if-else –

The if-else statement evaluates the condition and will execute the statement block1 if if the test condition
is True, but if the condition is False, then the statement block2 of else block is executed.

Syntax:

if (test expression):

statement_block 1

else:

statement_block 2

statement x
Flowchart:

Example

n=5

If(n%2==0):

Print(“Even number”)

else:

Print(“Odd number”)

In the following code example, the else body will execute as 5 modulo 2 is not equal to 0.

Nested if Statements :

A statement that contains other statements is called a compound statement.

To perform more complex checks, if statements can be nested, that is, canbe placed one inside the other.

In such a case, the inner if statement is the statement part of the outer one.

Nested if statements are used to check if more than one conditions aresatisfied.

if statements can be nested resulting in multi-way selection.

Syntax

If(test expression1):

Statement

If(test experssion 2):

Statement

if-elif-else Statement :

 The if-elif-else construct works in the same way as a usual if-else statement.

 If-elif-else construct is also known as nested-if construct.

 A series of if and elif statements have a final else block, which is executed if none of the if or elif
expressions is True.
Syntax:

if (test expression 1):

statement block1

elif (test expression 2):

statement block2

. . . . . . . . . . . . . . ..

elif( test expression N):

statement block N

else:

statement block X

Flowchart:

Example

a=10

b=15

c=20

If (a>b) and (a>c) :

Print(“a is the Biggest Value”)

Elif (b>a)and (b>c)

Print(“b is the Biggest Value”)

Else

Print(“c is the Biggest Value”)


Looping Statements/Iterative Structure:

Iterative statements are decision control statements that are used to repeat the execution of a list of statements.

Python supports 2 types of iterative statements-

 while loop

 for loop.

while Loop :

The While loop provides a mechanism to repeat one or more statements while a particular condition is TRUE.

Statement while (condition):

Statement block
Statement y

 In while loop, the condition is tested before any of the statements in the statement block is executed.

 If the condition is TRUE, only then the statements will be executed otherwise if the condition is False, the
control will jump to statement y, that is the immediate statement outside the while loop block.

Flowchart:

Example

n=int(input(“Enter the number”))

S=0

While(n>0):

r=n%10

s=s*10+r
n=n//10

Print(“reverse the given number “,s)

for Loop:

For loop provides a mechanism to repeat a task until a particular condition is True. It is usually known as a
determinate or definite loop because the programmer knows exactly how many times the loop will repeat.

The for...in statement is a looping statement used in Python to iterate over a sequence of objects.

Syntax

Syntax:

for loop_control_var in sequence:

statement block

FLOWCHART

for Loop and range() Function :

o The range( ) function is a built-in function in Python that is used to iterate over a sequence of numbers.

Syntax

range(beg,end,[step])
 The range( ) produces a sequence of numbers starting with beg (inclusive) and ending with one less than the
number end.

 The step argument is option (that is why it is placed in brackets). By default, every number in the range is
incremented by 1 but we can specify a different increment using step. It can be both negative and positive, but
not zero.

EXAMPLE

for i in range(1,5):

Print(i,end= “ “)

Output

1 2 3 4

Example

for I in range(1,10,2)

Print(I,end=” “)

Output

1 3 5 7 9

 If range( ) function is given a single argument, it produces an object with values from 0 to argument-1. For
example: range(10) is equal to writing range(0, 10).

 If range( ) is called with two arguments, it produces values from the first to the second. For example, range(0,
10) gives 0-9.

 If range( ) has three arguments then the third argument specifies the interval of the sequence produced. In this
case, the third argument must be an integer.

For example, range(1, 20, 3) gives 1, 4, 7, 10, 13, 16, 19.

Nested Loops :

Python allows its users to have nested loops, that is, loops that can be placed inside other loops.

Although this feature will work with any loop like while loop as well as for loop.

A for loop can be used to control the number of times a particular set of statements will be executed.

Another outer loop could be used to control the number of times that a whole loop is repeated.

Loops should be properly indented to identify which statements are contained within each for statement.

Example:

Program to print the following pattern


1

1 2

1 2 3

1 2 3 4

1 2 3 4 5

For i in range (1,6)

Print( )

For j in range(1,i+1)

Print(j,end=” “)

TheBreak Statement:
 The break statement is used to terminate a loop and skip the next code
after the loop
 When compiler encounter a break statement, the control passes to the statement that
follows the loop in which the break statement appears.

syntax

Break

Example:Programtodemonstratethebreakstatement
When i is equal to 5 the break statement terminates the loop.

The Continue Statement:

It is used to skip the current iteration of the loop and the control flow of the
program goes to the next iteration.

Syntax
Continue

Example
For I in range(1,10) :
If(I==5):
Continue
Print(I)
Print(“done”)

Output
12346789
Done

The PassS tatement:


 Pass statement isused when a statement is required syntactically but no
command or code has to be executed.
 It specified a null operation or simply NoOperation(NOP)
statement.Nothing happens when the pass statement is executed.
 The difference between a comment and pass statement is that while the
interpreter ignore a comment entirely,pass is not ignored.
 Comment is not executed but pass statement is executed but nothing
happens.
 Pass is a null statement.
Example:

1. Program to demonstrate pass statement

Else suite in loops

 In Python you can have the else statement associated with a loop
statements.

 If the else statement isused with a for loop,the else statement is executed when the
loop has completed iterating.
UNIT- III

FUNCTIONS:

A function is a block of code that performs a specific task.

NEED FOR FUNCTION

Each function to be written and tested separately.

Understanding, coding and testing multiple separate functions are far easier than doing the same for one huge
function.

When a big program is broken into comparatively smaller functions, then different programmers working on that
project can divide the workload by writing different functions.

All the libraries in Python contain pre-defined and pre-tested functions which the programmers are free to use
directly in their programs, without worrying about their code details.

This speed up program development.

Like Python libraries, programmers can also make their own functions and use them from different points in the
main program or any other program that needs its functionalities.

So code reuse is one of the most prominent reasons to use functions.

TYPES OF FUNCTIONS

There are two basic types of functions


1. built-in functions eg: dir(), len(), abs() etc.,

2. user defined functions.

FUNCTION DEFINITION

We can create a user defined function using def keyword.

When a function is defined,space is allocated for that function in the memory.

A function definition contains two parts

Function header
Function body

syntax

Def function_name(variable1,variable2,….) :

Documentation string

Function body

Return[ expression]

Function blocks starts with the keyword def

. The keyword is followed by the function name and parentheses (( )).

 After the parentheses a colon (:) is placed

. Parameters or arguments that the function accept are placed within parentheses.

. A function may have a return[expression] statement. That is, the return statement is optional. You can assign the
function name to a variable.

Example

Def func ():

For i in range(4):

Print(“hello world”)

func()

Function Call

Defining a function means specifying its name, parameters that are expected, and the set of instructions. The
function call statement invokes the function.

When a function is invoked the program control jumps to the called function to execute the statements that are a
part of that function. Once the called function is executed, the program control passes back to the calling function.

Syntax of calling a function


Function_name()

Syntax of called function

Function _name (variable1,variable2,….)

When a function is called,the interpreter checks that the number and type of arguments are used in the function call

Function Parameters

A function can take parameters which are nothing but some values that are passed to it so that the function can
manipulate them to produce the desired result.

Function name and the number and type of arguments in the function call must be same as that given in the function
definition.

If the data type of the argument passed does not matches with that expected in function then an error is generated.

Example

Def total(a,b) :

Result=a+b

Print(“sum= “,result)

a=int(input(“enter the a value”))

b=int(input(“enter the b value”))

total(a,b)

Variable scope and lifetime:

The scope of variable is a region of the program where a variable is visible or accessible. Lifetime of a variable is
the duration for which a variable exists in the memory. The existence and accessibility depend on the declaration of
a variable in the program.

For example, the lifetime of a variable declared inside a function is as long as the function is alive. When the
execution of function body is finished, then the variable defined inside a function will destroy.
The location where we can find a variable and also access it if required is called the scope of a variable.

There are three basic types of scope of variables in Python. They are:
 Global scope
 Local scope
 Nonlocal Keyword

Python Local variable

Local variables are those that are initialized within a function and are unique to that function. It cannot be
accessed outside of the function. Let’s look at how to make a local variable.
def f():

# local variable
s = "I love Geeksforgeeks"
print(s)

# Driver code
f()

Python Global variables

Global variables are the ones that are defined and declared outside any function and are not specified to any
function. They can be used by any part of the program.
Example:
def f():
print(s)

# Global scope
s = "I love Geeksforgeeks"
f()

Python Nonlocal keyword

In Python, the nonlocal keyword is used in the case of nested functions. This keyword works similarly to the
global, but rather than global, this keyword declares a variable to point to the variable of an outside enclosing
function, in case of nested functions.
print("Value of a using nonlocal is : ", end="")

def outer():
a=5

def inner():
nonlocal a
a = 10
inner()
print(a)

outer()

# demonstrating without non local


# inner loop not changing the value of outer a
# prints 5
print("Value of a without using nonlocal is : ", end="")

RETURN STATEMENT

A return statement is used to end the execution of the function call and “returns” the result to the caller.
SYNTAX

Return [Expression ]

The expression is written in brackets because it is optional.


If the expression is present, it is evaluated and the resultant value is returned to the calling function.
if no expression is specified then the function will return none.

Example
Def cube(x):
Return(x*x*x)
Num=10
Print(“cube of”, Num, “=”,result)

Moreondefiningfunctions:

Inthissectionwewilldiscusssomemorewaysofdefiningafunction.

1. Requiredarguments
2. Keywordarguments
3. Defaultarguments
4. Variable-lengtharguments
RequiredArguments

In the required arguments,the arguments are passed to a function in correct positional


order.Also,the number of arguments in the function call should exactly match with the
number of arguments specified in the function definition

Example:

KeywordArguments

When we call a function with some values,the values are assigned to the arguments
based on their position. Python also allow functions to be called using keyword
arguments in which the order(orposition) of the argument can be changed.The values are
not assigned to arguments according to their position but based on their
name(orkeyword).

Keywordargumentsarebeneficialintwocases.

• First,ifyouskiparguments.
• Second,ifinthefunctioncallyouchangetheorderofparameters.Example:
DefaultArguments

Python allow users to specify function arguments that can have default values.This means that
a function can be called with fewer arguments than it is defined to have.

That is,if the function accepts three parameters,but function call provide only two
arguments, then the third parameter will be assigned the default (already specified)value.
The default value to an argument is provided by using the assignment
operator(=).Userscanspecifyadefaultvalueforoneormorearguments.

Example:

Variable-lengthArguments

In some situations,it is not known in advance how many arguments will be passed to a
function.In such cases,Python allows programmers to make function calls with arbitrary(orany)
number of arguments.

When we use arbitrary arguments or variable length arguments, then the function
definition use an asterisk(*) before the parameter name.The syntax for a function using
variable arguments can be given as,

RecursiveFunctions
A recursive function is defined as a function that calls smaller version of its task until a
final call is made which does not require a call
toitself.Everyrecursivesolutionhastwomajorcases,whichareasfollows:

• basecase,in which the problem is simple enough to be solved directly with out
making any further calls to the same function.
• recursivecase,in which first the problemat hand is divided into simpler sub
parts.Recursion utilized divide and conquer technique of problem solving.

Example

DocumentationStrings

Docstrings(documentationstrings) serve the same purpose a that of comments,as they are


designed to explain code.However,they are more specific and have a propersyntax.

.
Modules

 We have seen that functions help us to reuse a particular piece of code.


Module goes a stepa head.It allows you to reuse one or more functions in your programs, even in the
programs in which those functions have not been defined.
 Putting simply, module is a file with a.py extension that definitions of all functions and
variables that you would like to use even in other programs.The programming which
you want to use functions or variables defined in the module will simply import that
particular module(or.pyfile).
 Modules are pre-written pieces of code that are used to perform common tasks like
generating random numbers,performing mathematical operations,etc.
 Thebasicwaytouseamoduleistoaddimportmodule_nameasthefirstlineofyourprogra
mandthenwritingmodule_name.vartoaccessfunctionsandvalueswiththenamevarint
hemodule.
Thefrom…importStatement

A module may containd definition for many variable sand functions.When you import a
module,you can use any variable or function defined in that module. But if you want to
use only selected variable sor functions,then you can use the from...import
statement.Forexample, in the aforementioned program you are using only the path variable in
the sysmodule,so you could have better written from sysimportpath.

A module may contain definition for many variable sand functions.When you import a module,you can
use any variable or function defined in that module. But if you want to use only selected variables
or functions, then you can use the from...import statement.Forexample,in the a for mentioned program
you are using only the path variable in the sysmodule,so you could have better written from
sysimportpath.

Example:

To import more than one item from a module,use a comma separated


list.Forexample,to import the value of pian sqrt() from them a the module you can
write,
MakingyourownModules

Every Python program is a module,that is,every file that you save as.py extension is a
module.

 Modules should be placed in the same directory as that of the program in which it is

imported. It can also be stored in one of the directories list edinsys.path.

Thedir()function

dir() is a built-in function that list the identifiers defined in a module. These identifiers may
include functions, classes and variables.If no name is specified,thedir() will return the list of
names defined in the current module.

Example:demonstrate the use of dir() function.

ThePythonModule:

 We have seen that a Pythonmodule is a file that contain ssome definitions and
statements.When a Python file is executed directly,it is considered the main
module of a program.
 Main modules are given the special name main and provide the basis for
acomplete Pythonprogram.
 The main module may import any number of other modules which may in turn
import other modules.But the main moduleof a Python program cannot be
imported into other modules.
ModulesandNamespaces
A namespace is a container that provide sanamed context for identifiers. However,in some
situations we need to have same name identifiers.Tocaterto such situations, namespaces is
the keyword. Namespaces enable programs to avoid potential name clashes by associating
each identifier with the namespace from which it originates.

Example:

Local,Global,andBuilt-inNamespaces

During a program‟s execution, there are three main namespaces that are referenced -
thebuilt-innamespace,theglobalnamespace,andthelocalnamespace.Thebuilt -
innamespace,asthenamesuggestscontainsnamesofallthebuilt-
infunctions,constants,etcthatarealreadydefinedinPython.Theglobalnamespacecontainsident
ifiers of the currently executing module and the local namespace has
identifiersdefinedinthecurrentlyexecutingfunction(ifany).

WhenthePythoninterpreterseesanidentifier,itfirstsearchesthelocalnamespace,thentheglobal
namespace, and finallythebuilt-innamespace. Therefore,
iftwoidentifierswithsamenamearedefinedinmorethanoneofthesenamespaces,itbecomesmasked
.
ModulePrivateVariables

 In Python, all identifiers defined in a module are public by default.This meanst all
identifiers are accessible by any other module that imports it.But,ifyou want some
variables or functions in a module to be privately used within the module,but not
to be accessed from outside it,thenyou need to declare those identifiers as private.
 In Python identifiers whose name starts with two under scores()are known as private
identifiers.Theseidentifierscanbeusedonlywithinthemodule.Innoway,theycanbeaccess
edfromoutsidethemodule.
 Therefore,whenthemoduleisimportedusingtheimport*formmodulename,alltheidentifie
rsofamodule‟snamespaceisimportedexcepttheprivateones(onesbeginningwithdoub leun
derscores).Thus,privateidentifiersbecomeinaccessiblefromwithintheimportingmodule.
AdvantagesofModules:

 Python modules provide all the benefits of modular software design.


Thesemodulesprovideservicesandfunctionalitythatcanbereusedinotherprograms
.
 EventhestandardlibraryofPythoncontainsasetofmodules.Itallowsyoutologicallyorga
nizethecodesothatitbecomeseasiertounderstandanduse.

Strings

 Python treats strings as contiguous series of characters delimited by single,double or


even triple quotes.Python has a built-in string classnamed"str" that has many useful
features.We can simultaneously declare and define a string by creating a variable of
string type.This can be done in several ways which are as follows:
name="India"graduate='N'country=namenationality=str("Indian")

 Indexing:Individual characters in a string are accessed using the subscript([])


operator.The expression in brackets is called an index.The index specifies a member of
an ordered set specifies the character we want to access from the given set of
characters in the string.
 The index of the first character is 0 and that of the last character is n -1 where n isthe
number of characters in the string. If you try to exceed the bounds (below 0 oraboven -
1),thenanerrorisraised.
 TraversingaString:
A string can be traversed by accessing character(s) from one index to
another.Forexample,the following program uses indexing to traverse a string from first
character to the last.
Example:

Concatenating,AppendingandMultiplyingStrings

Example:Programtoconcatenatetwostringsusing+operator
StringsareImmutable

Python strings are immutable which means that once created they cannot be
changed. Whenever you try to modify an existing string variable, a new string is
created.

Example:

StringFormattingOperator

 The %operator takes a format string o nthe left(thathas%d,%s,etc)and the


corresponding valuesinatupleon the right. The format operator, % allow users to
construct strings,replacing parts of the strings with the data stored in variables.The
syntax for the string formatting operation is:
 "<Format>"%(<Values>)
Example:
Built in string methods and functions
Unit -IV

LISTS

The most basic data structure in Python is the sequence. Each element of a sequence is assigned a number - its
position or index. The first index is zero, the second index is one, and so forth.

There are certain things you can do with all sequence types. These operations include indexing, slicing, adding,
multiplying, and checking for membership.

Creating a List:

Creating a list is as simple as putting different comma-separated values between square brackets. Similar to string
indices, list indices start at 0, and lists can be sliced, concatenated and so on.

Syntax:

List_variable = [val1,val2,…]

Example:

1)list_A =[1,2,3,4]
print(list_A)
Output [1,2,3,4]
2)list_C=[„Good”,”Going”]
print(list_C)
Output [‘Good’,’Going’]
Accessing values in lists:
 Similar to strings, lists can be sliced and concatenated
 To access values in lists, square brackets are used to slice along with index or indices to get value stored at that
index.

Syntax

s=list[start:stop:step]
For Example:

Seq=List[::2] # get every other element, starting with index 0.


Seq=List[1::2] # get every other element, starting with index 1.

Example 1
num_list=[1,2,3,4,5,6,7,8,9,10]
print(“num_list is:”,num_list)
print(“first elemnent in the list is”,num_list[0])
print(“num_list[2:5]=”,num_list[2:5])
print(“num_list[::2]=”,num_list[::2])
print(“num_list[1::3]=”,num_list[1::3])

Output:
num_list is: [1,2,3,4,5,6,7,8,9,10]
first elemnent in the list is 1
num_list[2:5]= [3,4,5]
num_list[::2]= [1,3,5,7,9]
num_list[1::3]= [2,5,8]

Updating values in the lists:


 once created, one or more elements of a list can be easily updated by giving the slice on the left-hand
side of the assignment operator
 You can also append new values in the list and remove existing values from the list using the append(
) method and del statement respectively.
Example:
num_list= [1,2,3,4,5,6,7,8,9,10]
print(“list is:”,num_list)
num_list[5]=100
print(“List after updation is:”,num_list)
num_list.append(200)
print(“List after appending a value is: “,num_list)
del num_list[3]
print(“List after deleting a value is:”,num_list)
Output:
list is: [1,2,3,4,5,6,7,8,9,10]
List after updation is: [1,2,3,4,5,100,7,8,9,10]
List after appending a value is: [1,2,3,4,5,100,7,8,9,10,200]
List after deleting a value is: [1,2,3,5,100,7,8,9,10,200]
Basic list operations:
Operation Description Example Output len Returns length of list len([1,2,3,4,5,6,7,8,9,1])

Append()
The append() method adds elements at the end of the list. This method can only add a single element at a time. You
can use the append() method inside a loop to add multiple elements.

example

myList =[1,2,3,'EduCBA','makes learning fun!']


myList.append(4)
myList.append(5)
myList.append(6)
for i inrange(7,9):
myList.append(i)
print(myList)
Output:

1,2,3,'EduCBA','makes learning fun!',4,5,6,7,8

extend()
The extend() method adds more than one element at the end of the list. Although it can add more than one element,
unlike append(), it adds them at the end of the list like append().

Code:

myList =[1,2,3,'EduCBA','makes learning fun!']


myList.extend([4,5,6])
for i inrange(7,11):
myList.append(i)
print(myList)
Output:

[1,2,3,'EduCBA','makes learning fun!',4,5,6,7,8,9,10]

insert()
The insert() method can add an element at a given position in the list. Thus, unlike append(), it can add elements at
any position, but like append(), it can add only one element at a time. This method takes two arguments. The first
argument specifies the position, and the second argument specifies the element to be inserted.

Code:

myList =[1,2,3,'EduCBA','makes learning fun!']


myList.insert(3,4)
myList.insert(4,5)
myList.insert(5,6)
print(myList)
output

[1,2,3,4,5,6'EduCBA','makes learning fun!']

remove()
The remove() method removes an element from the list. Only the first occurrence of the same element is removed
in the case of multiple occurrences.

Code:

myList =[1,2,3,'EduCBA','makes learning fun!']


myList.remove('makes learning fun!')
print(myList)
Output:

pop()
The method pop() can remove an element from any position in the list. The parameter supplied to this method is the
element index to be removed.
Code:

myList =[1,2,3,'EduCBA','makes learning fun!']


myList.pop(3)
print(myList)
slice
The slice operation is used to print a section of the list. The slice operation returns a specific range of elements. It
does not modify the original list.

Code:

myList =[1,2,3,'EduCBA','makes learning fun!']


print(myList[:4])# prints from beginning to end index
print(myList[2:])# prints from start index to end of list
print(myList[2:4])# prints from start index to end index
print(myList[:])# prints from beginning to end of list
reverse()
You can use the reverse() operation to reverse the elements of a list. This method modifies the original list. We use
the slice operation with negative indices to reverse a list without modifying the original. Specifying negative
indices iterates the list from the rear end to the front end of the list.

Code:

myList =[1,2,3,'EduCBA','makes learning fun!']


print(myList[::-1])# does not modify the original list
myList.reverse()# modifies the original list
print(myList)
len()
The len() method returns the length of the list, i.e., the number of elements in the list.

Code:

myList =[1,2,3,'EduCBA','makes learning fun!']


print(len(myList))
min() & max()
The min() method returns the minimum value in the list. The max() method returns the maximum value in the list.
Both methods accept only homogeneous lists, i.e., lists with similar elements.

Code:

myList =[1,2,3,4,5,6,7]
print(min(myList))
print(max(myList))
count()
The function count() returns the number of occurrences of a given element in the list.

Code:

myList =[1,2,3,4,3,7,3,8,3]
print(myList.count(3))
concatenate
The concatenate operation merges two lists and returns a single list. The concatenation is performed using the +
sign. It’s important to note that the individual lists are not modified, and a new combined list is returned.

Code:

myList =[1,2,3,'EduCBA','makes learning fun!']


yourList =[4,5,'Python','is fun!']
print(myList+yourList)
multiply
Python also allows multiplying the list n times. The resultant list is the original list iterated n times.

Code:

myList =['EduCBA','makes learning fun!']


print(myList*2)

Tuple Definition:

1.A tuple is a sequence of immutable objects. That is, you can change the value of one or more items in a list;
you cannot change the values in a tuple.

2. Tuples use parenthesis to define its elements. Whereas lists use square brackets.

Creating a Tuple:

Creating a tuple is as simple as putting different comma-separated values. Optionally you can put these comma-
separated values between parentheses.

Syntax:

Tup1=(val1,val2,….)

Where val (or values) can be an integer, a floating number, a character, or a string.

Examples:

1. Tup1=( ) #creates an empty tuple.

print(Tup1)
output: note: no ouput will be displayed.

2. Tup1=(5) #creates a tuple with single element

print(Tup1)

Output: 5

3. Tup1=(1,2,3,4,5) #creates a tuple of integers

print (Tup1)

Tup2=(„a‟,‟b‟,‟c‟,‟d‟) #creates a tuple of characters

print(Tup2)

Tup3=(“abc”,”def”,”ghi”) #creates a tuple of strings

print(Tup3)

Tup4=(1.2,2.3,3.4,4.5,5.6) #creates a tuple of floating point numbers

print(Tup4)

Tup5=(1,”abc”,2.3,‟d‟) #creates a tuple of mixed values

print(Tup5)

Output:

1,2,3,4,5,

a‟,‟b‟,‟c‟,‟d‟ „abc‟,‟def‟,‟ghi‟

1.2,2.3,3.4,4.5,5.6 1,

‟abc‟,2.3,‟d‟

4) A Tuple with parenthesis

print(„a‟,”bcd”,2,4.6)

Output: A bcd2 4.6

5) Default Tuple without parenthesis

a,b=10,20

print(a,b)

Output: 10 20

Accessing values of tuples:

Like strings and lists tuples indices also starts with 0.

 The operations performed are slice, concatenate etc.,


 To access values in tuple, slice operation is used along with the index

 Example :

1) Tup1=(1,2,3,4,5,6,7,8,9,10)
print(“Tup[3:6]=”,Tup1[3:6])
print(“Tup[:8]=”,Tup1[:4])
print(“Tup[4:]=”,Tup1[4:])
print(“Tup[:]=”,Tup1[:])
Output:
Tup[3:6]=(4,5,6)
Tup[:8]=(1,2,3,4)
Tup[4:]=5,6,7,8,9,10)
Tup[:]=(1,2,3,4,5,6,7,8,9,10)
The tuple values can be accessed using square brackets:
2) Tuple =(1,2,3,4,5.5,‟str‟)
Input:
1.print tuple
2.print tuple[5]
3.print tuple[1:5]
Output:
1. 1,2,3,4,5.5,‟str‟
2. ‟str‟
3. 2,3,4,5.5

Updating tuples:
As we all know tuples are immutable objects so we cannot update the values but we can just extract the
values from a tuple to form another tuple.
Example:
1. Tup1=(1,2,3,4,5)
Tup2=(6,7,8,9,10)
Tup3=Tup1+Tup2
print(Tup3)
Output: (1,2,3,4,5,6,7,8,9,10) 2)

2.Tup1=(1,2,3,4,5)
Tup2=(„sree‟,‟vidya‟,‟ram‟)
Tup3=Tup1+Tup2
print Tup3
Output: (1,2,3,4,5,‟sree‟,‟vidya‟,‟ram‟

Deleting elements of a tuple:

Deleting a single element in a tuple is not possible as we know tuple is a immutable object. Hence there
is another option to delete a single element of a tuple i.e..,you can create a new tuple that has all elements in
your tuple except the ones you don‟t want.
Example:
Tup1=(1,2,3,4,5)
del Tup1[3]
print Tup1
Output: Traceback (most recent call last): File "test.py", line 9, in del Tup1[3] Type error: „tuple‟
object doesn‟t support item deletion

however, you can always delete the entire tuple by using del statement.

Tup1=(1,2,3,4,5)

del Tup1
print Tup1
Output: Traceback (most recent call last): File "test.py", line 9, in print Tup1; NameError: name
'Tup1' is not define

Nested Tuples
A nested tuple is a Python tuple that has been placed inside of another tuple.
Using the + operator and "," during initialization

# Python program to concatenate tuples to make a nested tuple

# initializing the tuples


tup1 = (5, 4),
tup2 = (1, 6),

# printing the original tuples


print("Tuple 1 : " + str(tup1))
print("Tuple 2 : " + str(tup2))

# Concatenating the two tuples to a nested tuple using the + operator


nested = tup1 + tup2

# printing the result


print("The nested tuple : " + str(nested))
Differences between List and Tuple in Python
LIST TUPLE
Sno

1 Lists are mutable Tuples are immutable

The implication of iterations is comparatively


2 The implication of iterations is Time-consuming
Faster

The list is better for performing operations, such as A Tuple data type is appropriate for accessing
3
insertion and deletion. the elements

Tuple consumes less memory as compared to


4 Lists consume more memory
the list

5 Lists have several built-in methods Tuple does not have many built-in methods.

6 Unexpected changes and errors are more likely to occur In a tuple, it is hard to take place.

Dictionary:
It is a data structure in which we store values as a pair of key and value.
Each key is separated from its value by a colon (:), and consecutive items are separated by commas.
The entire items in a dictionary are enclosed in curly brackets ({}).
Syntax:
dictionary_name = {key_1: value_1, key_2: value_2, key_3: value_3}

If there are many keys and values in dictionaries, then we can also write just one key-value pair on a line to
make the code easier to read and understand. This is shown below.
dictionary_name = {key_1: value_1, key_2: value_2, key_3: value_3 , ….}
Keys in the dictionary must be unique and be of any immutable data type (like Strings, numbers, or tuples), there is
no strict requirement for uniqueness and type of values.
Values of a key can be of any type.
Dictionaries are not Sequences, rather they are mappings.
Mappings are collections of objects that are store objects by key instead of by relative position.

Creating a Dictionary:

The Syntax to create an empty dictionary can be given as: Dictionary_variable= { }

The Syntax to create a dictionary with key-value pair is:

Dictionary_variable= {key1:val1, key2:val2……}


o A dictionary can be also created by specifying key-value pairs separated by a colon in curly brackets as shown
below.

o Note that one key value pair is separated from the other using a comma.

Example:

d= {'roll_no':'18/001','Name:':'Arav','Course':'B.tech'}

print(d)

Output: {'Name:': 'Arav', 'Course': 'B.tech', 'roll_no': '18/001'}

Accessing Values:

In Dictionary, through key accessing values,

Example:

d={'Name': 'Arav', 'Course': 'B.tech', 'roll_no': '18/001'}

print('d[Name]:',d['Name'])

print('d[course]:',d['Course'])

print('d[roll_no]:',d['roll_no'])

output:

d[Name]: Arav d[course]: B.tech d[roll_no]: 18/001

Adding and Modifying an Item in a Dictionary:

To add a new entry or a key-value pair in a dictionary, just specify the keyvalue pair as you had done for the
existing pairs.

Syntax:

dictionary_ variable[key ]= val

Example:

1.Program to add a new item in the dictionary


d={'Name': 'Arav', 'Course': 'B.tech', 'roll_no': '18/001'} d['marks']=99 #new entry
print('d[Name]:',d['Name'])
print('d[course]:',d['Course'])
print('d[roll_no]:',d['roll_no'])
print('d[marks]:',d['marks'])
Output:
d[Name]: Arav d[course]: B.tech d[roll_no]: 18/001 d[marks]: 99

Modifying an Entry:
To modify an entry, just overwrite the existing value as shown in the following example: 1. program
to modify an item in the dictionary
d={'Name': 'Arav', 'Course': 'B.tech', 'roll_no': '18/001'} d['marks']=99 #new entry
print('d[Name]:',d['Name'])
print('d[course]:',d['Course'])
print('d[roll_no]:',d['roll_no'])
print('d[marks]:',d['marks'])
d[‘Course’]=’BCA’ #Updated entry
print('d[course]:',d['Course'])
Output:
d[Name]: Arav
d[course]: B.tech
d[roll_no]: 18/001
d[marks]: 99
d[course]: BCA

Deleting Items :
 You can delete one or more items using the del keyword.
 To delete or remove all the items in just one statement, use the clear () function.
 Finally, to remove an entire dictionary from the memory, we can gain use the del statement as del
Dict_name.
 The syntax to use the del statement can be given as,
del dictionary_variable[key]
Example:
1.Program to demonstrate the use of del statement and clear() function
Keys must have unique values.

Not even a single key can be duplicated in a dictionary. If you try to add a duplicate key, then the last assignment
is retained.

In a dictionary, keys should be strictly of a type that is immutable. This means that a key can be of strings,
numbers, or tuple type but it cannot be a list which is mutable.

In case you try to make your key of mutable type, then a Type error will be granted.

Tuples can be used as keys only if they contain immutable objects like strings, numbers, or other tuples.

If a tuple used as key contains any mutable object either directly or indirectly, then an error is generated.

The in keyword can be used to check whether a single key is present in the dictionary

Sorting Items in a Dictionary:

The keys() method of dictionary returns a list of all the keys used in the dictionary in a arbitrary order. The sorted()
function is used to sort the keys as shown below:

Example: 1. Program to sort keys of a dictionary

d={'roll_no':653,'name':'python','course':'b.tech'}

print(sorted(d.keys()))

output:

['course', 'name', 'roll_no']

Looping Over a Dictionary:


You can loop over a dictionary to access only values, only keys,and both using the for loop as shown the code
given below:

1.Program to access
d={'roll_no':653,'name':'python','course':'b.tech'}
print("KEYS:",end=' ')
for key in d: print(key,end=' ')
print("\n VALUES:",end=' ')
for val in d.values():
print(val,end=' ')
print("\n Dictionary:",end=' ')
for key,val in d.items():
print(key,val,end=';')
output:
KEYS: course name roll_no
VALUES: b.tech python 653
Dictionary: course b.tech;name python;roll_no 653;

Dictionary Functions

Python provides several built-in functions for working with dictionaries.


Here are some dictionary functions in python :

 len(dict): Returns the length (i.e., the number of key-value pairs) of the dictionary.

 dict[key]: Returns the value associated with the specified key. If the key is not found, a KeyError is raised.

 dict.get(key, default=None): Returns the value associated with the specified key, or the default value if the
key is not found. If the default parameter is not specified, it defaults to None.

 dict.keys(): Returns a list of all the keys in the dictionary.

 dict.values(): Returns a list of all the values in the dictionary.

 dict.items(): Returns a list of all the key-value pairs in the dictionary, as tuples.

 dict.clear(): Removes all key-value pairs from the dictionary.

 dict.pop(key, default=None): Removes the key-value pair with the specified key from the dictionary and
returns the value. If the key is not found and the default is not specified, a KeyError is raised.

 dict.popitem(): Removes and returns an arbitrary key-value pair from the dictionary. If the dictionary is
empty, a KeyError is raised.

 dict.update(other_dict): Updates the dictionary with key-value pairs from another dictionary. If a key
exists in both dictionaries, the value in the other dictionary overwrites the value in the original dictionary.

 dict.fromkeys(seq, value=None): Creates a new dictionary with keys from the specified sequence (e.g., a
list, tuple, or set) and values set to the specified value. If the value parameter is not specified, it defaults to None.
Difference between a List and a Dictionary
The following table shows some differences between a list and a dictionary in Python:

List Dictionary

The list is a collection of index value The dictionary is a hashed structure of the key and value
pairs like that of the array in C++. pairs.

The list is created by placing elements in [ The dictionary is created by placing elements in { } as
] separated by commas “,” “key”:”value”, each key-value pair is separated by commas “, “

The indices of the list are integers starting


The keys of the dictionary can be of any data type.
from 0.

The elements are accessed via indices. The elements are accessed via key-value pairs.

The order of the elements entered is


There is no guarantee for maintaining order.
maintained.
UNIT V

Introduction to Files:
When a program is being executed, its data is stored in RAM. Though RAM can be accessed faster by the
CPU,it is also volatile, which means when the program ends, or the computer shuts down, all the data is lost.
If you want to use the data in future,then you need to store this data on a permanent or nonvolatile storage
media such as hard disk, USB drive and DVD e.t.c.,
A file is a collection of data stored on a secondary storage device like hard disk.
A file is basically used because real-life applications involve large amounts of data and in such situations
the console oriented I/O operations pose two major problems:
First, it becomes cumbersome and time consuming to handle huge amount of data through terminals.
Second, when doing I/O using terminal, the entire data is lost when either the program is terminated or
computer is turned off. Therefore, it becomes necessary to store data on a permanent storage (the disks) and
read whenever necessary, without destroying the data.

File Types Like C and C++,


Python also supports two types of files
1.ASCII Text Files
2.Binary Files
ASCII Text Files
 A text file is a stream of characters that can be sequentially processed by a computer in forward
direction. For this reason a text file is usually opened for only one kind of operation (reading,
writing, or appending) at any given time.
 Because text files can process characters, they can only read or write data one character at a time. In
Python, a text stream is treated as a special kind of file.
 Depending on the requirements of the operating system and on the operation that has to be performed
(read/write operation) on the file, the newline characters may be converted to or from carriage-
return/linefeed combinations.
 Besides this, other character conversions may also be done to satisfy the storage requirements of the
operating system. However, these conversions occur transparently to process a text file. In a text file,
each line contains zero or more characters and ends with one or more characters.
 Another important thing is that when a text file is used, there are actually two representations of data -
internal or external. For example, an integer value will be represented as a number that occupies 2 or
4 bytes of memory internally but externally the integer value will be represented as a string of
characters representing its decimal or hexadecimal value.

Binary Files

A binary file is a file which may contain any type of data, encoded in binary form for computer
storage and processing purposes. It includes files such as word processing documents, PDFs,
images, spreadsheets, videos, zip files and other executable programs.
Like a text file, a binary file is a collection of bytes. A binary file is also referred to as a character
stream with following two essential differences.
A binary file does not require any special processing of the data and each byte of data is
transferred to or from the disk unprocessed.
 Python places no constructs on the file, and it may be read from, or written to,in any manner the
programmer wants. While text files can be processed sequentially, binary files, on the other
hand, can be either processed sequentially or randomly depending on the needs of the
application.

File Operations

When we want to read from or write to a file we need to open it first. When we are done, it needs to be closed, so
that resources that are tied with the file are freed.

Python has many in-built functions and methods to manipulate files.

a file operation takes place in the following order.

1. Open a file

2. Read or write (perform operation)

3. Close the file

Opening A File

Before reading from or writing to a file, you must first open it using Python‟s built-in open() function.

This function creates a file object, which will be used to invoke methods associated with it.

The Syntax of open() is:

fileObj = open(file_name [, access_mode])

Where file_name is a string value that specifies name of the file that you want to access.

access_mode indicates the mode in which the file has to be opened, i.e., read, write, append, etc.

Example:Write a Program to print the details of file object

File=open(“file1.txt”,”rb”)

Print(file)

Access modes

Python supports the following access modes for opening a file those are

1. Read Only (‘r’) : Open text file for reading. The handle is positioned at the beginning of the file. If the
file does not exists, raises the I/O error. This is also the default mode in which a file is opened.
2. Read and Write (‘r+’): Open the file for reading and writing. The handle is positioned at the beginning
of the file. Raises I/O error if the file does not exist.
3. Write Only (‘w’) : Open the file for writing. For the existing files, the data is truncated and over -written.
The handle is positioned at the beginning of the file. Creates the file if the file does not exist.
4. Write and Read (‘w+’) : Open the file for reading and writing. For an existing file, data is truncated and
over-written. The handle is positioned at the beginning of the file.
5. Append Only (‘a’): Open the file for writing. The file is created if it does not exist. The handle is
positioned at the end of the file. The data being written will be inserted at the end, after the existing data.
6. Append and Read (‘a+’) : Open the file for reading and writing. The file is created if it does not exist.
The handle is positioned at the end of the file. The data being written will be inserted at the end, after the
existing data.
7. Read only(rb) : this mode opens only for binary file. This file pointer only is placed at the beginning of
the file.

File object Attributes


File object has the following attributes that we can use to accessing various details of a file, such as a file name
and under which mode the file is opened.

 name: Return the name of the file. It is a read-only attribute and may not be present on all file-like objects.
If the file object was created using the open() function, the file’s name is returned. Otherwise, some string
indicates the source of the file object is returned.
 encoding: It returns the encoding this file uses, such as UTF-8. This attribute is read-only. When Unicode
strings are written to a file, they will be converted to byte strings using this encoding. It may also be None. In
that case, the file uses the system default encoding for converting Unicode strings.
 mode: Returns the file access mode used while opening a file.
 closed: Returns True if a file is closed. It is a boolean value indicating the current state of the file object.
 newline: Files opened in universal newline read mode keep track of the newlines encountered while reading
the file. The values are ‘\r’, ‘\n’, ‘\r\n’, None (no newlines read yet), or a tuple containing all the newline
Closing A File

The close() method is used to close the file object. Once a file object is closed, you cannot further read from or
write into the file associated with the file object.

While closing the file object the close() flushes any unwritten information.

Although, Python automatically closes a file when the reference object of a file is reassigned to another file, but as
a good programming habit you should always explicitly use the close() method to close a file.

The syntax of close() is

fileObj.close()

The close() method frees up any system resources such as file descriptors, file locks, etc. that are associated with
the file.

Once the file is closed using the close() method, any attempt to use the file object will result in an error. Example2:

Write a Python program to assess if a file is closed or not..)

file = open('File1.txt','wb')

print('Name of the file :',file.name)

print('File is closed:',file.closed)

print('File is now being closed')

file.close()
print('File is closed',file.closed

print(file.read())

Output:

Name of the file : File1.txt

File is closed: False

File is now being closed

File is closed True

Traceback (most recent call last): File "D:/Python/sample.py", line 7,

in print(file.read())

io.UnsupportedOperation: rea

Writing A File

The write() method is used to write a string to an already opened file

Of course this string may include numbers, special characters or other symbols.

While writing data to a file, you must remember that the write() method does not add a newline character ('\n') to
the end of the string.

The syntax of write() method is:

fileObj.write(string)

Example:

Program that writes a message in the file,data.txt

file=open('data.txt','w')

file.write('hello cse we are learning python programming')

file.close()

print('file writing successful')

Output:

file writing successful

writeline() method:

The writelines() method is used to write a list of strings.


Example:

Program to write to a file using the writelines() method

file=open('data.txt','w')

lines=['hello','cse','hope to enjoy','learning','python programming']

file.writelines(lines)

file.close( )

print('file writing successful')

Output:

file writing successful

append() method:

Once you have stored some data in a file,you can always open that file again to write more data or append data
to it

To append a file, you must open it using „a‟ or „ab‟ mode depending on whether it is text file or binary file.

 Note that if you open a file with „w‟ or „wb‟ mode and then start writing data into it, then the existing
contents would be overwritten.

Example:

Program to append data to an already existing file

file=open('data.txt','a')

file.write('\nHave a nice day')

file.close()

print('Data appended successful')

Output: Data appended successful

Reading A File

The read() method is used to read a string from an already opened file.

As said before, the string can include, alphabets, numbers, characters or other symbols.

The syntax of read() method is

fileObj.read([count])
count is an optional parameter which if passed to the read() method specifies the number of bytes to be read
from the opened file.

The read() method starts reading from the beginning of the file and if count is missing or has a negative
value then, it reads the entire contents of the file (i.e., till the end of file)

Example1:

Program to print the first 8 characters of the file data.txt

file=open('data.txt','r')

print(file.read(8))

file.close()

Output: hellocse

Example2:

Program to display the content of file using for loop

file=open('data.txt','r')

for line in file: print(line)

file.close()

Output: hellocsehope to enjoylearningpython programming

Have a nice day

readline() Method

It is used to read single line from the file.

This method returns an empty string when end of the file has been reached.

Example

Program to demonstrate the usage of readline() function

file=open('data.txt','r')

print('firtsline:',file.readline())

print('second line:',file.readline())

print('third line:',file.readline())

file.close()

Output: firtsline: hellocsehope to enjoylearningpython programming


second line: Have a nice day

third line

readlines() Method

readlines() Method is used to read all the lines in the file

Example:Programtodemonstratereadlines()function

file=open('data.txt','r')prin
data.txt
t(file.readlines())file.clos
e() hellocsehope to enjoylearningpython

Output: programmingHaveanice day

['hellocsehopetoenjoylearningpythonprogramming\n','Haveaniceday']

4.4.1 ist()Method
 list() method is also used to display entire contents of the file.you need to
passthefileobjectasanargumenttothelist()method.
Example:Program todisplaythecontentsofthefiledata.txtusingthelist()

methodfile=open('data.tx
t','r')print(list(file))file.cl data.txt
ose()
hellocsehope to enjoylearningpython
Output:
programmingHaveanice day
['hellocsehopetoenjoylearningpythonprogramming\n','Haveaniceday']

4.4.2 Openingafileusingwithkeyword:
 It is good programming habit to use the with keyword when working with file
objects.
 Thishastheadvantagethatthefileisproperlyclosedafteritisusedevenifanerroroccursduringr
eadorwriteoperationorevenwhenyouforgettoexplicitlyclosethefile.
4.4.3 SplittingWords:
 Python allows you to read line(s) from a file and splits the line (treated as
astring)basedonacharacter.Bydefault,thischaracterisspacebutyoucanevenspecify
anyothercharactertosplitwordsinthestring.
Example:

Program to split the line into series of words and use space to perform the split operation

withopen('data.txt','r')asfile:line=file.readline()words=line.split()print(words)

open('data.txt','r')asfile:line=file.readline()words=line.split()print(words)

Output:

['hellocsehope','to','enjoylearningpython','programming']

FileMethods:
4.1 FilePositions:
 With every file, the file management system associates a pointer often
knownasfilepointerthatfacilitatesthemovementacrossthefileforreadingand/orwriting
data.
 The filepointer specifiesa locationfromwherethecurrent read
orwriteoperationisinitiated.Oncetheread/writeoperationiscompleted,thepointerisau
tomaticallyupdated.
 Pythonhasvariousmethodsthattellsorsetsthepositionofthefilepointer.
 Forexample,thetell()methodtellsthecurrentpositionwithinthefileatwhichthenextreadorwr
iteoperationwilloccur.Itisspecifiedasnumberofbytesfromthebeginningofthefile.
 When you just open a file for reading, the file pointer is positioned at
location0,whichisthebeginningofthefile.
 Thesyntaxforseek() functionis
seek(offset[,from])

 The offset argument indicates the number of bytes to be moved and the from
argument specifies the reference position from where the bytes are to be moved.

File1.txt
HelloAll,

Hopeyouareenjoyinglearningpython

Example: Programthat tellsand sets the position of file pointer

Renaming and Deleting Files:


 The o smodule in Python has various methods that can be used to perform file-
processing operations like renaming and deleting files.To use the methods defined
in the osmodule,you should first importiting your program then call any related
functions.
 The rename() Method:
 Therename()methodtakestwoarguments,thecurrentfilenameandthenewfilename.
Itssyntaxis:os.rename(old_file_name,new_file_name)
 The remove()Method: This method canbe used todelete file(s).The method takes a
filename(nameofthefiletobedeleted) as an argument and deletes that file.
Itssyntaxis:os.remove(file_name)

Example:Programtorenamefile‘File1.txt’to‘student.txt’

Example:Programtodeleteafilename

You might also like