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

Data Science II Notes IV Units

Uploaded by

VENKATESHWARLU
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

Data Science II Notes IV Units

Uploaded by

VENKATESHWARLU
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 73

UNIT-I

STEPS FOR PROBLEM SOLVING

Algorithm A set of exact steps which when followed, solve the problem or
accomplish the required task.

Analysing the problem

It is important to clearly understand a problem before we begin to find the


solution for it. If we are not clear as to what is to be solved, we may end up
developing a program which may not solve our purpose. Thus, we need to
read and analyse the problem statement carefully in order to list the principal
components of the problem and decide the core functionalities that our
solution should have. By analysing a problem, we would be able to figure out
what are the inputs that our program should accept and the outputs that it
should produce.

Developing an Algorithm

It is essential to device a solution before writing a program code for a given


problem. The solution is represented in natural language and is called an
algorithm. We can imagine an algorithm like a very well-written recipe for

Suppose while driving, a vehicle starts making a strange noise. We


might not know how to solve the problem right away. First, we
need to identify from where the noise is coming? In case the
problem cannot be solved by us, then we need to take the vehicle
to a mechanic. The mechanic will analyse the problem to identify
the source of the noise, make a plan about the work to be done
and finally repair the vehicle in order to remove the noise. From
the above example, it is explicit that, finding the solution to a
problem might consist of multiple steps

When problems are straightforward and easy, we can easily find the
solution. But a complex problem requires a methodical approach to
find the right solution. In other words, we have to apply problem
solving techniques. Problem solving begins with the precise
identification of the problem and ends with a complete working
solution in terms of a program or software.
Analysing the problem
It is important to clearly understand a problem before we begin to
find the solution for it. If we are not clear as to what is to be
solved, we may end up developing a program which may not
solve our purpose. Thus, we need to read and analyse the
problem statement carefully in order to list the principal
components of the problem and decide the core functionalities
that our solution should have. By analysing a problem, we would be
able to figure out what are the inputs that our program should
accept and the outputs that it should produce.
Coding
After finalising the algorithm, we need to convert the
algorithm into the format which can be understood by the
computer to generate the desired solution. Different high level
programming languages can be used for writing a program.
It is equally important to record the details of the coding
procedures followed and document the solution. This is helpful
when revisiting the programs at a later stage.
Testing and Debugging
The program created should be tested on various parameters.
The program should meet the requirements of the user. It
must respond within the expected time. It should generate
correct output for all possible inputs. In the presence of
syntactical errors, no output will be obtained. In case the
output generated is incorrect, then the program should be
checked for logical errors, if any. Software industry follows
standardised testing methods like unit or component
testing, integration testing, system testing, and acceptance
testing while developing complex applications. This is to
ensure that the software meets all the business and technical
requirements and works as expected. The errors or defects
found in the testing phases are debugged or rectified and the
program is again tested. This continues
till all the errors are removed from the program.
Once the software application has been developed,
tested and delivered to the user, still problems in terms of
functioning can come up and need to be resolved from time
to time. The maintenance of the solution, thus, involves
fixing the problems faced by the user, answering the
queries of the user and even serving the request for addition
or modification of features.

ALGORITHM:
The word “algorithm” relates to the name of the mathematician Al-
khowarizmi, which means a procedure or a technique. Software Engineer
commonly uses an algorithm for planning and solving the problems. An
algorithm is a sequence of steps to solve a particular problem or algorithm is
an ordered set of unambiguous steps that produces a result and terminates in
a finite time

Algorithm has the following characteristics

• Input: An algorithm may or may not require input

• Output: Each algorithm is expected to produce at least one result

• Definiteness: Each instruction must be clear and unambiguous.

• Finiteness: If the instructions of an algorithm are executed, the


algorithm should terminate after finite number of steps

The algorithm and flowchart include following three types of control


structures.

1. Sequence: In the sequence structure, statements are placed one after


the other and the execution takes place starting from up to down.

2. Branching (Selection): In branch control, there is a condition and


according to a condition, a decision of either TRUE or FALSE is achieved.
In the case of TRUE, one of the two branches is explored; but in the case
of FALSE condition, the other alternative is taken. Generally, the ‘IF-
THEN’ is used to represent branch control.

3. Loop (Repetition): The Loop or Repetition allows a statement(s) to be


executed repeatedly based on certain loop condition e.g. WHILE, FOR
loops.

Advantages of algorithm

• It is a step-wise representation of a solution to a given problem,


which makes it easy to understand.

• An algorithm uses a definite procedure.

• It is not dependent on any programming language, so it is easy to


understand for anyone even without programming knowledge.

• Every step in an algorithm has its own logical sequence so it is


easy to debug.
FLOWCHART:

The first design of flowchart goes back to 1945 which was designed by
John Von Neumann. Unlike an algorithm, Flowchart uses different symbols
to design a solution to a problem. It is another commonly used
programming tool. By looking at a Flowchart one can understand the
operations and sequence of operations performed in a system. Flowchart
is often considered as a blueprint of a design used for solving a specific
problem.
Advantages of flowchart:

 Flowchart is an excellent way of communicating the logic of a


program.
 Easy and efficient to analyze problem using flowchart.
 During program development cycle, the flowchart plays the role of
a blueprint, which makes program development process easier.
 After successful development of a program, it needs continuous
timely maintenance during the course of its operation. The
flowchart makes program or system maintenance easier.
 It is easy to convert the flowchart into any programming language
code.
Flowchart is diagrammatic /Graphical representation of sequence of
steps to solve a problem. To draw a flowchart following standard
symbols are use
Symbol Symbol function
Name

Used to represent
start and end of
Oval
flowchart

Parallelogr Used for input and


am output operation

Processing: Used for


arithmetic
Rectangle
operations and
data-manipulations

Decision making.
Used to represent
Diamond
the operation in
which there are
two/three
alternatives, true
and false etc

Flow line Used to


indicate the flow of
Arrows
logic by connecting
symbols

Circle Page Connector

Pseudocode
A pseudocode (pronounced Soo-doh-kohd) is another way of representing
an algorithm. It is considered as a non-formal language that helps
programmers to write algorithm. It is a detailed description of instructions
that a computer must follow in a particular order. It is intended for human
reading and cannot be executed directly by the computer. No specific
standard for writing a pseudocode exists. The word “pseudo” means “not
real,” so “pseudocode” means “not real code”. Following are some of the
frequently used keywords while writing pseudocode:

• INPUT

• COMPUTE

• PRINT

• INCREMENT

• DECREMENT

• IF/ELSE

• WHILE

• TRUE/FALSE

Pseudocode for the sum of two numbers will be:

 input num1
 input num2
 COMPUTE Result = num1 + num2
 PRINT Result

Introduction:
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 is Interpreted: Python is processed at runtime by the
interpreter. We do not need to compile our program before executing it.
 Python is Interactive: We can actually sit at a Python prompt and
interact with the interpreter directly to write our programs.
 Python is Object-Oriented: Python supports Object-Oriented style or
technique of programming that encapsulates code within objects.
 Python is a Beginner's Language: Python is a great language for the
beginner-level programmers and supports the development of a wide
range of applications from simple text processing to WWW browsers to
games.
Python Features
Python's features include:
 Easy-to-learn: Python has few keywords, simple structure, and a clearly
defined syntax. This allows the student to pick up the language quickly.
 Easy-to-read: Python code is more clearly defined and visible to the
eyes.
 Easy-to-maintain: Python's source code is fairly easy-to-maintain.
 A broad standard library: Python's bulk of the library is very portable
and cross-platform compatible on UNIX, Windows, and Macintosh.
 Interactive Mode: Python has support for an interactive mode which
allows interactive testing and debugging of snippets of code.
 Portable: Python can run on a wide variety of hardware platforms and
has the same interface on all platforms.
 Extendable: We can add low-level modules to the Python interpreter.
These modules enable programmers to add to or customize their tools to
be more efficient.
 Databases: Python provides interfaces to all major commercial
databases.
 GUI Programming: Python supports GUI applications that can be created
and ported to many system calls, libraries and windows systems, such as
Windows MFC, Macintosh, and the X Window system of Unix.
 Scalable: Python provides a better structure and support for large
programs than shell scripting.
Apart from the above-mentioned features, Python has a big list of good
features, few are listed below:
 It supports functional and structured programming methods as well as
OOP.
 It can be used as a scripting language or can be compiled to byte-code for
building large applications.
 It provides very high-level dynamic data types and supports dynamic type
checking.
 IT supports automatic garbage collection.
 It can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java.
Python Identifiers
A Python identifier is a name used to identify a variable, function, class,
module or other object. An identifier starts with a letter A to Z or a to z or
an underscore (_) followed by zero or more letters, underscores and digits
(0 to 9). Python does not allow punctuation characters such as @, $, and
% within identifiers. Python is a case sensitive programming language.
Keywords
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
['and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else',
'except', 'exec', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is',
'lambda', 'not', 'or', 'pass', 'print', 'raise', 'return', 'try', 'while', 'with',
'yield']
Lines and Indentation
Python provides no braces to indicate blocks of code for class and function
definitions or flow control. Blocks of code are denoted by line indentation,
which is rigidly enforced.
The number of spaces in the indentation is variable, but all statements
within the block must be indented the same amount. For example −
if True:
print "True"
else:
print "False"
Comments in Python
A hash sign (#) that is not inside a string literal begins a comment. All
characters after the # and up to the end of the physical line are part of the
comment and the Python interpreter ignores them.
Standard Data Types
The data stored in memory can be of many types. For example, a person's
age is stored as a numeric value and his or her address is stored as
alphanumeric characters. Python has various standard data types that are
used to define the operations possible on them and the storage method
for each of them.
Python has five standard data types −
 Numbers
 String
 List
 Tuple
 Dictionary
Python Numbers:
Python supports four different numerical types −
 int (signed integers)
 long (long integers, they can also be represented in octal and
hexadecimal)
 float (floating point real values)
 complex (complex numbers)
Examples
Here are some examples of numbers −
int long float complex

10 51924361L 0.0 3.14j


Python Strings
Strings in Python are identified as a contiguous set of characters
represented in the quotation marks. Python allows for either pairs of single
or double quotes.
The plus (+) sign is the string concatenation operator and the asterisk (*)
is the repetition operator.
Examples:
str = 'Hello World!'

print str # Prints complete string


print str[0] # Prints first character of the string
print str[2:5] # Prints characters starting from 3rd to 5th
print str[2:] # Prints string starting from 3rd character
print str * 2 # Prints string two times
print str + "TEST" # Prints concatenated string
Python Lists
Lists are the most versatile of Python's compound data types. A list
contains items separated by commas and enclosed within square brackets
([]). To some extent, lists are similar to arrays in C. One difference
between them is that all the items belonging to a list can be of different
data type.
Example:
list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
tinylist = [123, 'john']

print list # Prints complete list


print list[0] # Prints first element of the list
print list[1:3] # Prints elements starting from 2nd till 3rd
print list[2:] # Prints elements starting from 3rd element
print tinylist * 2 # Prints list two times
print list + tinylist # Prints concatenated lists
Python Tuples
A tuple is another sequence data type that is similar to the list. A tuple
consists of a number of values separated by commas. Unlike lists,
however, tuples are enclosed within parentheses.
The main differences between lists and tuples are: Lists are enclosed in
brackets ( [ ] ) and their elements and size can be changed, while tuples
are enclosed in parentheses ( ( ) ) and cannot be updated. Tuples can be
thought of as read-only lists. For example –
tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )
tinytuple = (123, 'john')

print tuple # Prints complete list


print tuple[0] # Prints first element of the list
print tuple[1:3] # Prints elements starting from 2nd till 3rd
print tuple[2:] # Prints elements starting from 3rd element
print tinytuple * 2 # Prints list two times
print tuple + tinytuple # Prints concatenated lists
Python Dictionary
Python's dictionaries are kind of hash table type. They work like
associative arrays or hashes found in Perl and consist of key-value pairs. A
dictionary key can be almost any Python type, but are usually numbers or
strings. Values, on the other hand, can be any arbitrary Python object.
Dictionaries are enclosed by curly braces ({ }) and values can be assigned
and accessed using square braces ([]). For example −
dict = {}
dict['one'] = "This is one"
dict[2] = "This is two"
tinydict = {'name': 'john','code':6734, 'dept': 'sales'}
print dict['one'] # Prints value for 'one' key
print dict[2] # Prints value for 2 key
print tinydict # Prints complete dictionary
print tinydict.keys() # Prints all the keys
print tinydict.values() # Prints all the values
Data Type Conversion
Sometimes, we may need to perform conversions between the built-in
types. To convert between types, we simply use the type name as a
function.
There are several built-in functions to perform conversion from one data
type to another. These functions return a new object representing the
converted value.
Function Description

int(x [,base]) Converts x to an integer. base specifies the base if x


is a string.

long(x [,base] ) Converts x to a long integer. base specifies the base


if x is a string.

float(x) Converts x to a floating-point number.

complex(real Creates a complex number.


[,imag])

str(x) Converts object x to a string representation.

tuple(s) Converts s to a tuple.


list(s) Converts s to a list.

set(s) Converts s to a set.

chr(x) Converts an integer to a character.

unichr(x) Converts an integer to a Unicode character.

ord(x) Converts a single character to its integer value.

hex(x) Converts an integer to a hexadecimal string.

oct(x) Converts an integer to an octal string.

Python Basic Operators


Operators are the constructs which can manipulate the value of operands.
Consider the expression 4 + 5 = 9. Here, 4 and 5 are called operands and
+ is called operator.
Types of Operators
Python language supports the following types of operators.
 Arithmetic Operators
 Comparison (Relational) Operators
 Assignment Operators
 Logical Operators
 Bitwise Operators
 Membership Operators
 Identity Operators
Let us have a look on all operators one by one.

Python Arithmetic Operators


Assume variable a holds 10 and variable b holds 20, then −
Operator Description Example

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


operator.

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


hand operand.

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


Multiplication operator

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


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

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


on operators the power
20

// Floor Division - The division of operands 9//2 = 4


where the result is the quotient in which
the digits after the decimal point are
removed.
Python Comparison Operators
These operators compare the values on either sides of them and decide
the relation among them. They are also called Relational operators.
Assume variable a holds 10 and variable b holds 20, then −
Operato Description Example
r

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


the condition becomes true. not true.

!= If values of two operands are not equal, then


condition becomes true.

> If the value of left operand is greater than the (a > b) is


value of right operand, then condition becomes not true.
true.

< If the value of left operand is less than the (a < b) is


value of right operand, then condition becomes true.
true.

>= If the value of left operand is greater than or (a >= b) is


equal to the value of right operand, then not true.
condition becomes true.

<= If the value of left operand is less than or equal (a <= b) is


to the value of right operand, then condition true.
becomes true.
Python Assignment Operators
Assume variable a holds 10 and variable b holds 20, then −
Operator Description Example
= Assigns values from right side operands to left c=a+b
side operand assigns
value of a
+ b into c

+= Add It adds right operand to the left operand and c += a is


AND assign the result to left operand equivalen
t to c = c
+a
Python Bitwise Operators
Bitwise operator works on bits and performs bit by bit operation. Assume if
a = 60; and b = 13; Now in binary format they will be as follows −
a = 0011 1100
b = 0000 1101
-----------------
a&b = 0000 1100
a|b = 0011 1101
a^b = 0011 0001
~a = 1100 0011
Python Logical Operators
There are following logical operators supported by Python language.
Assume variable a holds 10 and variable b holds 20 then
Operator Description Example

and Logical If both the operands are true then (a and b) is


AND condition becomes true. true.

or Logical OR If any of the two operands are non-zero (a or b) is true.


then condition becomes true.

not Logical NOT Used to reverse the logical state of its Not(a and b) is
operand. false.

Python Membership Operators


Python’s membership operators test for membership in a sequence, such
as strings, lists, or tuples. There are two membership operators as
explained below
Operato Description
r

in Evaluates to true if it finds a variable in the specified sequence


and false otherwise.
not in Evaluates to true if it does not finds a variable in the specified
sequence and false otherwise.
Python Identity Operators
Identity operators compare the memory locations of two objects. There are
two Identity operators explained below:
Operato Description
r

is Evaluates to true if the variables on either side of the operator


point to the same object and false otherwise.

is not Evaluates to false if the variables on either side of the operator


point to the same object and true otherwise.
Python Operators Precedence
The following table lists all operators from highest precedence to lowest.
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


Python Decision Making
Decision Making in programming refers selection of statements when
conditions are involved. Python supports three types of Decision Making
statements.
Python IF Statement
Syntax
if expression:
statement(s)
Flow Diagram

Example
var1 = 100
if var1:
print "1 - Got a true expression value"
print var1

var2 = 0
if var2:
print "2 - Got a false expression value"
print var2
print "Good bye!"
Python IF...ELIF...ELSE Statements
syntax
if expression1:
statement(s)
elif expression2:
statement(s)
elif expression3:
statement(s)
else:
statement(s)
Example
var = 100
if var == 200:
print "1 - Got a true expression value"
print var
elif var == 150:
print "2 - Got a true expression value"
print var
elif var == 100:
print "3 - Got a true expression value"
print var
else:
print "4 - Got a false expression value"
print var

print "Good bye!"


Python nested IF statements
In a nested if construct, we can have an if...elif...else construct inside
another if...elif...else construct.
Syntax:
if expression1:
statement(s)
if expression2:
statement(s)
elif expression3:
statement(s)
else:
statement(s)
elif expression4:
statement(s)
else:
statement(s)

Python Loops
A loop statement allows us to execute a statement or group of
statements multiple times. The following diagram illustrates a loop
statement −

Python programming language provides following types of loops to handle


looping requirements.

while loop

while loop statement in Python programming language repeatedly


executes a target statement as long as a given condition is true.

Syntax

The syntax of a while loop in Python programming language is −

while expression:
statement(s)

Flow Diagram
Example

count = 0
while (count < 9):
print 'The count is:', count
count = count + 1
print "Good bye!"

Python for Loop Statement:

It has the ability to iterate over the items of any sequence, such as a list
or a string.

Syntax

for iterating_var in sequence:


statements(s)

If a sequence contains an expression list, it is evaluated first. Then, the


first item in the sequence is assigned to the iterating
variable iterating_var. Next, the statements block is executed. Each item
in the list is assigned to iterating_var, and the statement(s) block is
executed until the entire sequence is exhausted.
Flow Diagram

Example

for letter in 'Python': # First Example


print 'Current Letter :', letter

fruits = ['banana', 'apple', 'mango']


for fruit in fruits: # Second Example
print 'Current fruit :', fruit

print "Good bye!"

Python break statement

It terminates the current loop and resumes execution at the next


statement, just like the traditional break statement in C.

Syntax

The syntax for a break statement in Python is as follows −

break
Flow Diagram

Example

for letter in 'Python': # First Example


if letter == 'h':
break
print 'Current Letter :', letter

var = 10 # Second Example


while var > 0:
print 'Current variable value :', var
var = var -1
if var == 5:
break

print "Good bye!"

Python continue statement


It returns the control to the beginning of the while loop..
The continue statement rejects all the remaining statements in the
current iteration of the loop and moves the control back to the top of the
loop.
The continue statement can be used in both while and for loops.

Syntax
continue

Flow Diagram

Example
for letter in 'Python': # First Example
if letter == 'h':
continue
print 'Current Letter :', letter

print "Good bye!"


UNIT – II

Python Functions
 A function is a block of organized, reusable code that is used to
perform a single, related action.
 Functions provide better modularity for our application
 Functions support a high degree of code reusing.

Python gives us many built-in functions like print(), etc. but we can also
create our own functions. These functions are called user-defined
functions.

Defining a Function

We can define functions to provide the required functionality. The rules to


define a function in Python are given below.

 Function blocks begin with the keyword def followed by the function
name and parentheses ( ( ) ).
 Any input parameters or arguments should be placed within these
parentheses. we can also define parameters inside these
parentheses.
 The first statement of a function can be an optional statement - the
documentation string of the function or docstring.
 The code block within every function starts with a colon (:) and is
indented.
 The statement return [expression] exits in a function, optionally
passing back an expression to the caller. A return statement with no
arguments is same as return None.

Syntax

def functionname( parameters ):


"function_docstring"
function_suite
return [expression]

Example

def printme( str ):


"This prints a passed string into this function"
print str
return
Calling a Function

Defining a function only gives it a name, specifies the parameters that are
to be included in the function and structures the blocks of code.

Once the basic structure of a function is finalized, we can execute it by


calling it from another function or directly from the Python prompt.
Following is the example to call printme() function –

# Now you can call printme function


printme("I'm first call to user defined function!")
printme("Again second call to the same function")

Pass by reference vs value

All parameters (arguments) in the Python language are passed by


reference. It means if we change what a parameter refers to within a
function, the change also reflects back in the calling function. For
example −

# Function definition is here


def changeme( mylist ):
"This changes a passed list into this function"
mylist.append([1,2,3,4]);
print "Values inside the function: ", mylist
return

# Now you can call changeme function


mylist = [10,20,30];
changeme( mylist );
print "Values outside the function: ", mylist

Here, we are maintaining reference of the passed object and appending


values in the same object. So, this would produce the following result −

Values inside the function: [10, 20, 30, [1, 2, 3, 4]]


Values outside the function: [10, 20, 30, [1, 2, 3, 4]]
There is one more example where argument is being passed by reference
and the reference is being overwritten inside the called function.

# Function definition is here


def changeme( mylist ):
"This changes a passed list into this function"
mylist = [1,2,3,4]; # This would assign new reference in mylist
print "Values inside the function: ", mylist
return

# Now you can call changeme function


mylist = [10,20,30];
changeme( mylist );
print "Values outside the function: ", mylist

The parameter mylist is local to the function changeme. Changing mylist


within the function does not affect mylist. The function accomplishes
nothing and finally this would produce the following result:

Values inside the function: [1, 2, 3, 4]


Values outside the function: [10, 20, 30]

Function Arguments
we can call a function by using the following types of formal arguments:
 Required arguments
 Keyword arguments
 Default arguments
 Variable-length arguments
Required arguments
Required arguments are the arguments passed to a function in correct
positional order. Here, the number of arguments in the function call
should match exactly with the function definition.
To call the function printme(), you definitely need to pass one argument,
otherwise it gives a syntax error as follows −
# Function definition is here
def printme( str ):
"This prints a passed string into this function"
print str
return;
# Now you can call printme function
printme()
When the above code is executed, it produces the following result:
Traceback (most recent call last):
File "test.py", line 11, in <module>
printme();
TypeError: printme() takes exactly 1 argument (0 given)
Keyword arguments
Keyword arguments are related to the function calls. When we use
keyword arguments in a function call, the caller identifies the arguments
by the parameter name.
This allows us to skip arguments or place them out of order because the
Python interpreter is able to use the keywords provided to match the
values with parameters. We can also make keyword calls to
the printme() function in the following ways −
# Function definition is here
def printme( str ):
"This prints a passed string into this function"
print str
return;

# Now you can call printme function


printme( str = "My string")
When the above code is executed, it produces the following result −
My string
The following example gives more clear picture. Here the order of
parameters does not matter.
# Function definition is here
def printinfo( name, age ):
"This prints a passed info into this function"
print "Name: ", name
print "Age ", age
return;

# Now you can call printinfo function


printinfo( age=50, name="miki" )
When the above code is executed, it produces the following result −
Name: miki
Age 50
Default arguments
A default argument is an argument that assumes a default value if a
value is not provided in the function call for that argument. The following
example gives an idea on default arguments, it prints default age if it is
not passed −
#!/usr/bin/python

# Function definition is here


def printinfo( name, age = 35 ):
"This prints a passed info into this function"
print "Name: ", name
print "Age ", age
return;

# Now you can call printinfo function


printinfo( age=50, name="miki" )
printinfo( name="miki" )
When the above code is executed, it produces the following result −
Name: miki
Age 50
Name: miki
Age 35
Variable-length arguments
We may need to process a function for more arguments than you
specified while defining the function. These arguments are
called variable-length arguments and are not named in the function
definition, unlike required and default arguments.
Syntax for a function with non-keyword variable arguments is this −
def functionname([formal_args,] *var_args_tuple ):
"function_docstring"
function_suite
return [expression]
An asterisk (*) is placed before the variable name that holds the values of
all nonkeyword variable arguments. This tuple remains empty if no
additional arguments are specified during the function call. Following is a
simple example −
# Function definition is here
def printinfo( arg1, *vartuple ):
"This prints a variable passed arguments"
print "Output is: "
print arg1
for var in vartuple:
print var
return;

# Now you can call printinfo function


printinfo( 10 )
printinfo( 70, 60, 50 )
When the above code is executed, it produces the following result −
Output is:
10
Output is:
70
60
50
The Anonymous Functions
These functions are called anonymous because they are not declared in
the standard manner by using the def keyword. You can use
the lambda keyword to create small anonymous functions.

 Lambda forms can take any number of arguments but return just
one value in the form of an expression. They cannot contain
commands or multiple expressions.
 An anonymous function cannot be a direct call to print because
lambda requires an expression
 Lambda functions have their own local namespace and cannot
access variables other than those in their parameter list and those
in the global namespace.
 Although it appears that lambda's are a one-line version of a
function, they are not equivalent to inline statements in C or C++,
whose purpose is by passing function stack allocation during
invocation for performance reasons.

Syntax
The syntax of lambda functions contains only a single statement, which is
as follows −

lambda [arg1 [,arg2,.....argn]]:expression

Following is the example to show how lambda form of function works −


# Function definition is here
sum = lambda arg1, arg2: arg1 + arg2;

# Now we can call sum as a function


print "Value of total : ", sum( 10, 20 )
print "Value of total : ", sum( 20, 20 )

When the above code is executed, it produces the following result −

Value of total : 30
Value of total : 40

The return Statement


The statement return [expression] exits a function, optionally passing
back an expression to the caller. A return statement with no arguments is
the same as return None.

All the above examples are not returning any value. we can return a
value from a function as follows −

# Function definition is here


def sum( arg1, arg2 ):
# Add both the parameters and return them."
total = arg1 + arg2
print "Inside the function : ", total
return total;
# Now you can call sum function
total = sum( 10, 20 );
print "Outside the function : ", total

When the above code is executed, it produces the following result −

Inside the function : 30


Outside the function : 30

Scope of Variables
All variables in a program may not be accessible at all locations in that
program. This depends on where you have declared a variable.
The scope of a variable determines the portion of the program where you
can access a particular identifier. There are two basic scopes of variables
in Python −

 Global variables
 Local variables

Global vs. Local variables


Variables that are defined inside a function body have a local scope, and
those defined outside have a global scope.

This means that local variables can be accessed only inside the function
in which they are declared, whereas global variables can be accessed
throughout the program body by all functions. When we call a function,
the variables declared inside it are brought into scope. Following is a
simple example −

total = 0; # This is global variable.


# Function definition is here
def sum( arg1, arg2 ):
# Add both the parameters and return them."
total = arg1 + arg2; # Here total is local variable.
print "Inside the function local total : ", total
return total;

# Now you can call sum function


sum( 10, 20 );
print "Outside the function global total : ", total

When the above code is executed, it produces the following result −

Inside the function local total : 30


Outside the function global total : 0

Python Modules
A module allows us to logically organize our 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 we 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. Here's an example of a simple module, support.py

def print_func( par ):


print "Hello : ", par
return

The import Statement


We can use any 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.

# Import module support


import support
# Now you can call defined function that module as follows
support.print_func("Zara")

When the above code is executed, it produces the following result −

Hello : Zara

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 us 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 fibonacci from the module fib, use the
following statement −

from fib import fibonacci

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

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

This provides an easy way to import all the items from a module into the
current namespace;

Random numbers

Using the random module, we can generate pseudo-random numbers. The


function random() generates a random number between zero and one [0,
0.1 .. 1]. Numbers generated with this module are not truly random but
they are enough random for most purposes.

from random import *


print random() # Generate a pseudo-random number between 0 and 1.

Generate a random number between 1 and 100

To generate a whole number (integer) between one and one hundred use:
from random import *
print randint(1, 100) # Pick a random number between 1 and 100.

This will print a random integer. If you want to store it in a variable you
can use:

from random import *


x = randint(1, 100) # Pick a random number between 1 and 100.
print x

Random number between 1 and 10

To generate a random floating point number between 1 and 10 we can use


the uniform() function
from random import *
print uniform(1, 10)

Picking a random item from a list


We can shuffle a list with this code:
from random import *
items = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
shuffle(items)
print items

To pick a random number from a list:

from random import *


items = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
x = sample(items, 1) # Pick a random item from the list
print x[0]

math module in Python

This module is always available. It provides access to the mathematical


functions defined by the C standard.

math.ceil(x)
Return the ceiling of x as a float, the smallest integer value greater
than or equal to x.

math.copysign(x, y)
Return x with the sign of y.

math.fabs(x)
Return the absolute value of x.

math.factorial(x)
Return x factorial.
math.trunc(x)
Return the Real value x truncated to an Integral

math.pow(x, y)
Return x raised to the power y.

math.sqrt(x)
Return the square root of x.

math.degrees(x)
Convert angle x from radians to degrees.

math.radians(x)
Convert angle x from degrees to radians.

math.pi
The mathematical constant π = 3.141592..., to available precision.

math.e
The mathematical constant e = 2.718281..., to available precision.

Python Recursive Function

In Python, a function can call other functions. It is even possible for the
function to call itself. These type of construct are termed as recursive
functions.

Following is an example of recursive function to find the factorial of an


integer.

Factorial of a number is the product of all the integers from 1 to that


number. For example, the factorial of 6 (denoted as 6!) is 1*2*3*4*5*6 =
720.

Example of recursive function


# An example of a recursive function to
# find the factorial of a number

def calc_factorial(x):
"""This is a recursive function
to find the factorial of an integer"""

if x == 1:
return 1
else:
return (x * calc_factorial(x-1))

num = 4
print("The factorial of", num, "is", calc_factorial(num))

Strings
Strings are the most popular types in Python. We can create them simply
by enclosing characters in quotes. Python treats single quotes the same
as double quotes. Creating strings is as simple as assigning a value to a
variable. For example −

var1 = 'Hello World!'


var2 = "Python Programming"

Accessing Values in Strings


Python does not support a character type; these are treated as strings of
length one, thus also considered a substring.

To access substrings, use the square brackets for slicing along with the
index or indices to obtain your substring. For example −

var1 = 'Hello World!'


var2 = "Python Programming"
print "var1[0]: ", var1[0]
print "var2[1:5]: ", var2[1:5]

When the above code is executed, it produces the following result −

var1[0]: H
var2[1:5]: ytho

Updating Strings
We can "update" an existing string by (re)assigning a variable to another
string. The new value can be related to its previous value or to a
completely different string altogether. For example −

var1 = 'Hello World!'


print "Updated String :- ", var1[:6] + 'Python'

When the above code is executed, it produces the following result −


Updated String :- Hello Python

Escape Characters
Following table is a list of escape or non-printable characters that can be
represented with backslash notation.

An escape character gets interpreted; in a single quoted as well as double


quoted strings.

Backslash Description
notation

\a Bell or alert

\b Backspace

\n Newline

\r Carriage return

\s Space

\t Tab

\v Vertical tab

String Special Operators


Assume string variable a holds 'Hello' and variable b holds 'Python', then

Operato Description Example


r

+ Concatenation - Adds values on either side of a + b will


the operator give
HelloPytho
n

* Repetition - Creates new strings, concatenating a*2 will


multiple copies of the same string give -
HelloHello

[] Slice - Gives the character from the given index a[1] will
give e

[:] Range Slice - Gives the characters from the a[1:4] will
given range give ell

in Membership - Returns true if a character exists H in a will


in the given string give 1

not in Membership - Returns true if a character does M not in a


not exist in the given string will give 1

String Formatting Operator


One of Python's coolest features is the string format operator %. This
operator is unique to strings and makes up for the pack of having
functions from C's printf() family. Following is a simple example −

print "My name is %s and weight is %d kg!" % ('Zara', 21)

When the above code is executed, it produces the following result −

My name is Zara and weight is 21 kg!


Here is the list of complete set of symbols which can be used along with
%−

Format Symbol Conversion

%c character
%s string conversion via str() prior to formatting

%i signed decimal integer

%d signed decimal integer

%u unsigned decimal integer

%o octal integer

%x hexadecimal integer (lowercase letters)

%X hexadecimal integer (UPPERcase letters)

Unicode String
Normal strings in Python are stored internally as 8-bit ASCII, while
Unicode strings are stored as 16-bit Unicode. This allows for a more
varied set of characters, including special characters from most
languages in the world. I'll restrict my treatment of Unicode strings to the
following −

#!/usr/bin/python

print ('Hello, world!')

When the above code is executed, it produces the following result −

Hello, world!

Built-in String Methods


Python includes the following built-in methods to manipulate strings −

Methods with Description

capitalize()

Capitalizes first letter of string


find(str, beg=0 end=len(string))

Determine if str occurs in string or in a substring of string if starting


index beg and ending index end are given returns index if found
and -1 otherwise.

index(str, beg=0, end=len(string))

Same as find(), but raises an exception if str not found.

isalnum()

Returns true if string has at least 1 character and all characters are
alphanumeric and false otherwise.

isalpha()

Returns true if string has at least 1 character and all characters are
alphabetic and false otherwise.

isdigit()

Returns true if string contains only digits and false otherwise.

islower()

Returns true if string has at least 1 cased character and all cased
characters are in lowercase and false otherwise.

isnumeric()

Returns true if a unicode string contains only numeric characters


and false otherwise.

isspace()

Returns true if string contains only whitespace characters and false


otherwise.

isupper()

Returns true if string has at least one cased character and all cased
characters are in uppercase and false otherwise.

len(string)

Returns the length of the string

lower()
Converts all uppercase letters in string to lowercase.

lstrip()

Removes all leading whitespace in string.

max(str)

Returns the max alphabetical character from the string str.

min(str)

Returns the min alphabetical character from the string str.

replace(old, new [, max])

Replaces all occurrences of old in string with new or at most max


occurrences if max given.

upper()

Converts lowercase letters in string to uppercase.


UNIT – III
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.

Python has six built-in types of sequences, but the most common ones
are lists and tuples.

Python Lists
The list is a most flexible datatype available in Python which can be
written as a list of comma-separated values (items) between square
brackets. Important thing about a list is that items in a list need not be of
the same type.

Creating a list is as simple as putting different comma-separated values


between square brackets. For example −

list1 = ['physics', 'chemistry', 1997, 2000];


list2 = [1, 2, 3, 4, 5 ];
list3 = ["a", "b", "c", "d"]

Similar to string indices, list indices start at 0, and lists can be sliced,
concatenated and so on.

Accessing Values in Lists


To access values in lists, use the square brackets for slicing along with
the index or indices to obtain value available at that index. For example −

#!/usr/bin/python

list1 = ['physics', 'chemistry', 1997, 2000];


list2 = [1, 2, 3, 4, 5, 6, 7 ];

print "list1[0]: ", list1[0]


print "list2[1:5]: ", list2[1:5]

When the above code is executed, it produces the following result −

list1[0]: physics
list2[1:5]: [2, 3, 4, 5]
Updating Lists
We can update single or multiple elements of lists by giving the slice on
the left-hand side of the assignment operator, and we can add to
elements in a list with the append() method. For example −

list = ['physics', 'chemistry', 1997, 2000];


print "Value available at index 2 : "
print list[2]
list[2] = 2001;
print "New value available at index 2 : "
print list[2]

When the above code is executed, it produces the following result −

Value available at index 2 :


1997
New value available at index 2 :
2001

Delete List Elements


To remove a list element, we can use either the del statement if we know
exactly which element(s) we are deleting or the remove() method if we do
not know. For example −

list1 = ['physics', 'chemistry', 1997, 2000];


print list1
del list1[2];
print "After deleting value at index 2 : "
print list1

When the above code is executed, it produces following result −

['physics', 'chemistry', 1997, 2000]


After deleting value at index 2 :
['physics', 'chemistry', 2000]

Basic List Operations


Lists respond to the + and * operators much like strings; they mean
concatenation and repetition here too, except that the result is a new list,
not a string.
Operations on lists

Python Expression Results Description

len([1, 2, 3]) 3 Length

[1, 2, 3] + [4, 5, 6] [1, 2, 3, 4, 5, 6] Concatenation

['Hi!'] * 4 ['Hi!', 'Hi!', 'Hi!', Repetition


'Hi!']

3 in [1, 2, 3] True Membership

for x in [1, 2, 3]: print x, 123 Iteration

Indexing, Slicing, and Matrixes


Because lists are sequences, indexing and slicing work the same way for
lists as they do for strings.

Assuming following input −

L = ['spam', 'Spam', 'SPAM!']

Python Expression Results Description

L[2] 'SPAM!' Offsets start at zero

L[-2] 'Spam' Negative: count from the


right

L[1:] ['Spam', 'SPAM!'] Slicing fetches sections

Built-in List Functions & Methods:


Python includes the following list functions −
S Function with Description
N

1 cmp(list1, list2)

Compares elements of both lists.

2 len(list)

Gives the total length of the list.

3 max(list)

Returns item from the list with max value.

4 min(list)

Returns item from the list with min value.

5 list(seq)

Converts a tuple into list.

Python includes following list methods

S Methods with Description


N

1 list.append(obj)

Appends object obj to list

2 list.count(obj)

Returns count of how many times obj occurs in list

3 list.extend(seq)

Appends the contents of seq to list

4 list.index(obj)

Returns the lowest index in list that obj appears

5 list.insert(index, obj)

Inserts object obj into list at offset index

6 list.pop(obj=list[-1])
Removes and returns last object or obj from list

7 list.remove(obj)

Removes object obj from list

8 list.reverse()

Reverses objects of list in place

9 list.sort([func])

Sorts objects of list, use compare func if given

Tuples

A tuple is a sequence of immutable Python objects. Tuples are sequences,


just like lists. The differences between tuples and lists are, the tuples
cannot be changed unlike lists and tuples use parentheses, whereas lists
use square brackets.

Creating a tuple is as simple as putting different comma-separated values


between parentheses. For example −

tup1 = ('physics', 'chemistry', 1997, 2000);


tup2 = (1, 2, 3, 4, 5 );
tup3 = "a", "b", "c", "d";

The empty tuple is written as two parentheses containing nothing −

tup1 = ();

To write a tuple containing a single value you have to include a comma,


even though there is only one value −

tup1 = (50,);

Like string indices, tuple indices start at 0, and they can be sliced,
concatenated, and so on.

Accessing Values in Tuples:


To access values in tuple, use the square brackets for slicing along with
the index or indices to obtain value available at that index. For example −
tup1 = ('physics', 'chemistry', 1997, 2000);
tup2 = (1, 2, 3, 4, 5, 6, 7 );

print "tup1[0]: ", tup1[0]


print "tup2[1:5]: ", tup2[1:5]

When the above code is executed, it produces the following result −

tup1[0]: physics
tup2[1:5]: [2, 3, 4, 5]

Updating Tuples
Tuples are immutable which means you cannot update or change the
values of tuple elements. we are able to take portions of existing tuples to
create new tuples as the following example demonstrates −

tup1 = (12, 34.56);


tup2 = ('abc', 'xyz');

# Following action is not valid for tuples


# tup1[0] = 100;

# So let's create a new tuple as follows


tup3 = tup1 + tup2;
print tup3

When the above code is executed, it produces the following result −

(12, 34.56, 'abc', 'xyz')

Delete Tuple Elements


Removing individual tuple elements is not possible.

To explicitly remove an entire tuple, just use the del statement. For
example:

tup = ('physics', 'chemistry', 1997, 2000);


print tup
del tup;
print "After deleting tup : "
print tup

Basic Tuples Operations


Tuples respond to the + and * operators much like strings; they mean
concatenation and repetition here too, except that the result is a new
tuple, not a string.

In fact, tuples respond to all of the general sequence operations we used


on strings in the prior chapter −

Python Expression Results Description

len((1, 2, 3)) 3 Length

(1, 2, 3) + (4, 5, 6) (1, 2, 3, 4, 5, 6) Concatenation

('Hi!',) * 4 ('Hi!', 'Hi!', 'Hi!', 'Hi!') Repetition

3 in (1, 2, 3) True Membership

for x in (1, 2, 3): print x, 123 Iteration

Indexing, Slicing, and Matrixes


Because tuples are sequences, indexing and slicing work the same way
for tuples as they do for strings. Assuming following input −

L = ('spam', 'Spam', 'SPAM!')

Python Expression Results Description

L[2] 'SPAM!' Offsets start at zero

L[-2] 'Spam' Negative: count from the


right

L[1:] ['Spam', 'SPAM!'] Slicing fetches sections

Built-in Tuple Functions


Python includes the following tuple functions −

S Function with Description


N

1 cmp(tuple1, tuple2)

Compares elements of both tuples.

2 len(tuple)

Gives the total length of the tuple.

3 max(tuple)

Returns item from the tuple with max value.

4 min(tuple)

Returns item from the tuple with min value.

5 tuple(seq)

Converts a list into tuple.

Python Dictionary
Each key is separated from its value by a colon (:), the items are
separated by commas, and the whole thing is enclosed in curly braces. An
empty dictionary without any items is written with just two curly braces,
like this: {}.

Keys are unique within a dictionary while values may not be. The values
of a dictionary can be of any type, but the keys must be of an immutable
data type such as strings, numbers, or tuples.

Accessing Values in Dictionary:


To access dictionary elements, we can use the familiar square brackets
along with the key to obtain its value. Following is a simple example −

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}

print "dict['Name']: ", dict['Name']


print "dict['Age']: ", dict['Age']

When the above code is executed, it produces the following result −

dict['Name']: Zara
dict['Age']: 7
If we attempt to access a data item with a key, which is not part of the
dictionary, we get an error as follows −

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}


print "dict['Alice']: ", dict['Alice']

When the above code is executed, it produces the following result −

dict['Alice']:
Traceback (most recent call last):
File "test.py", line 4, in <module>
print "dict['Alice']: ", dict['Alice'];
KeyError: 'Alice'

Updating Dictionary
We can update a dictionary by adding a new entry or a key-value pair,
modifying an existing entry, or deleting an existing entry as shown below
in the simple example −

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}


dict['Age'] = 8; # update existing entry
dict['School'] = "DPS School"; # Add new entry
print "dict['Age']: ", dict['Age']
print "dict['School']: ", dict['School']

When the above code is executed, it produces the following result −

dict['Age']: 8
dict['School']: DPS School

Delete Dictionary Elements


We can either remove individual dictionary elements or clear the entire
contents of a dictionary. We can also delete entire dictionary in a single
operation.
To explicitly remove an entire dictionary, just use the del statement.
Following is a simple example −

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}


del dict['Name']; # remove entry with key 'Name'
dict.clear(); # remove all entries in dict
del dict ; # delete entire dictionary

print "dict['Age']: ", dict['Age']


print "dict['School']: ", dict['School']

This produces the following result. Note that an exception is raised


because after del dict dictionary does not exist any more

Properties of Dictionary Keys


Dictionary values have no restrictions. They can be any arbitrary Python
object, either standard objects or user-defined objects. However, same is
not true for the keys.

There are two important points to remember about dictionary keys −

(a) More than one entry per key not allowed. Which means no duplicate
key is allowed. When duplicate keys encountered during assignment, the
last assignment wins. For example −

dict = {'Name': 'Zara', 'Age': 7, 'Name': 'Manni'}


print "dict['Name']: ", dict['Name']

When the above code is executed, it produces the following result −

dict['Name']: Manni
(b) Keys must be immutable. Which means we can use strings, numbers
or tuples as dictionary keys but something like ['key'] is not allowed.
Following is a simple example:

dict = {['Name']: 'Zara', 'Age': 7}


print "dict['Name']: ", dict['Name']

When the above code is executed, it produces an


Built-in Dictionary Functions & Methods −
Python includes the following dictionary functions −
S Function with Description
N

1 cmp(dict1, dict2)

Compares elements of both dict.

2 len(dict)

Gives the total length of the dictionary. This would be equal to the
number of items in the dictionary.

3 str(dict)

Produces a printable string representation of a dictionary

4 type(variable)

Returns the type of the passed variable. If passed variable is


dictionary, then it would return a dictionary type.

Python includes following dictionary methods −

S Methods with Description


N

1 dict.clear()
Removes all elements of dictionary dict

2 dict.copy()
Returns a shallow copy of dictionary dict

3 dict.fromkeys()
Create a new dictionary with keys from seq and
values set to value.

4 dict.get(key, default=None)
For key key, returns value or default if key not in dictionary

5 dict.has_key(key)
Returns true if key in dictionary dict, false otherwise

6 dict.items()
Returns a list of dict's (key, value) tuple pairs

7 dict.keys()
Returns list of dictionary dict's keys

8 dict.setdefault(key, default=None)
Similar to get(), but will set dict[key]=default if key is not already
in dict

9 dict.update(dict2)
Adds dictionary dict2's key-values pairs to dict

10 dict.values()
Returns list of dictionary dict's values

Python Files I/O


Printing to the Screen:
The simplest way to produce output is using the print statement where
we can pass zero or more expressions separated by commas. This
function converts the expressions we pass into a string and writes the
result to standard output as follows −

print "Python is really a great language,", "isn't it?"

This produces the following result on your standard screen −

Python is really a great language, isn't it?

Reading Keyboard Input


Python provides two built-in functions to read a line of text from standard
input, which by default comes from the keyboard. These functions are −

 raw_input
 input

The raw_input Function


The raw_input([prompt]) function reads one line from standard input and
returns it as a string (removing the trailing newline).

str = raw_input("Enter your input: ");


print "Received input is : ", str

This prompts you to enter any string and it would display same string on
the screen. When I typed "Hello Python!", its output is like this −

Enter your input: Hello Python


Received input is : Hello Python

The input Function


The input([prompt]) function is equivalent to raw_input, except that it
assumes the input is a valid Python expression and returns the evaluated
result to us.

str = input("Enter your input: ");


print "Received input is : ", str

This would produce the following result against the entered input −

Enter your input: [x*5 for x in range(2,10,2)]


Recieved input is : [10, 20, 30, 40]

Opening and Closing Files


Python provides basic functions and methods necessary to manipulate
files by default. we can do most of the file manipulation using
a file object.

The open Function


Before we can read or write a file, we have to open it using Python's built-
in open() function. This function creates a file object, which would be
utilized to call other support methods associated with it.

Syntax
file object = open(file_name [, access_mode][, buffering])

Here are parameter details:

 file_name: The file_name argument is a string value that contains


the name of the file that you want to access.
 access_mode: The access_mode determines the mode in which the
file has to be opened, i.e., read, write, append, etc. the default file
access mode is read (r).
 buffering: If the buffering value is set to 0, no buffering takes
place. If the buffering value is 1, line buffering is performed while
accessing a file. If you specify the buffering value as an integer
greater than 1, then buffering action is performed with the
indicated buffer size. If negative, the buffer size is the system
default(default behavior).

Here is a list of the different modes of opening a file −

Mode Description
s

r Opens a file for reading only. The file pointer is placed at the
beginning of the file. This is the default mode.

rb Opens a file for reading only in binary format. The file pointer is
placed at the beginning of the file. This is the default mode.

r+ Opens a file for both reading and writing. The file pointer
placed at the beginning of the file.

rb+ Opens a file for both reading and writing in binary format. The
file pointer placed at the beginning of the file.

w Opens a file for writing only. Overwrites the file if the file exists.
If the file does not exist, creates a new file for writing.

wb Opens a file for writing only in binary format. Overwrites the file
if the file exists. If the file does not exist, creates a new file for
writing.

w+ Opens a file for both writing and reading. Overwrites the


existing file if the file exists. If the file does not exist, creates a
new file for reading and writing.

wb+ Opens a file for both writing and reading in binary format.
Overwrites the existing file if the file exists. If the file does not
exist, creates a new file for reading and writing.

a Opens a file for appending. The file pointer is at the end of the
file if the file exists. That is, the file is in the append mode. If
the file does not exist, it creates a new file for writing.

ab Opens a file for appending in binary format. The file pointer is


at the end of the file if the file exists. That is, the file is in the
append mode. If the file does not exist, it creates a new file for
writing.

a+ Opens a file for both appending and reading. The file pointer is
at the end of the file if the file exists. The file opens in the
append mode. If the file does not exist, it creates a new file for
reading and writing.

ab+ Opens a file for both appending and reading in binary format.
The file pointer is at the end of the file if the file exists. The file
opens in the append mode. If the file does not exist, it creates a
new file for reading and writing.

The file Object Attributes


Once a file is opened and we have one file object, we can get various
information related to that file.

Here is a list of all attributes related to file object:

Attribute Description

file.closed Returns true if file is closed, false otherwise.

file.mode Returns access mode with which file was opened.

file.name Returns name of the file.

file.softspac Returns false if space explicitly required with print, true


e otherwise.
Example
#!/usr/bin/python

# Open a file
fo = open("foo.txt", "wb")
print "Name of the file: ", fo.name
print "Closed or not : ", fo.closed
print "Opening mode : ", fo.mode
print "Softspace flag : ", fo.softspace

This produces the following result −

Name of the file: foo.txt


Closed or not : False
Opening mode : wb
Softspace flag : 0

The close() Method


The close() method of a file object flushes any unwritten information and
closes the file object, after which no more writing can be done.

Python automatically closes a file when the reference object of a file is


reassigned to another file. It is a good practice to use the close() method
to close a file.

Syntax
fileObject.close();

Example
# Open a file
fo = open("foo.txt", "wb")
print "Name of the file: ", fo.name
# Close opend file
fo.close()

This produces the following result −

Name of the file: foo.txt

Reading and Writing Files


The file object provides a set of access methods to make our lives easier.
We would see how to use read() and write() methods to read and write
files.

The write() Method


The write() method writes any string to an open file. It is important to
note that Python strings can have binary data and not just text.

The write() method does not add a newline character ('\n') to the end of
the string −

Syntax
fileObject.write(string);

Here, passed parameter is the content to be written into the opened file.

Example
# Open a file
fo = open("foo.txt", "wb")
fo.write( "Python is a great language.\nYeah its great!!\n");
# Close opend file
fo.close()

The above method would create foo.txt file and would write given content
in that file and finally it would close that file. If you would open this file, it
would have following content.

Python is a great language.


Yeah its great!!

The read() Method


The read() method reads a string from an open file. It is important to note
that Python strings can have binary data. apart from text data.

Syntax
fileObject.read([count]);

Here, passed parameter is the number of bytes to be read from the


opened file. This method starts reading from the beginning of the file and
if count is missing, then it tries to read as much as possible, maybe until
the end of file.
Example
Let's take a file foo.txt, which we created above.

#!/usr/bin/python
# Open a file
fo = open("foo.txt", "r+")
str = fo.read(10);
print "Read String is : ", str
# Close opend file
fo.close()

This produces the following result −

Read String is : Python is

File Positions

The tell() method tells us the current position within the file; in other
words, the next read or write will occur at that many bytes from the
beginning of the file.
The seek(offset[, from]) method changes the current file position.
The offset argument indicates the number of bytes to be moved.
The from argument specifies the reference position from where the bytes
are to be moved.
If from is set to 0, it means use the beginning of the file as the reference
position and 1 means use the current position as the reference position
and if it is set to 2 then the end of the file would be taken as the
reference position.
Example
Let us take a file foo.txt, which we created above.
#!/usr/bin/python

# Open a file
fo = open("foo.txt", "r+")
str = fo.read(10);
print "Read String is : ", str

# Check current position


position = fo.tell();
print "Current file position : ", position

# Reposition pointer at the beginning once again


position = fo.seek(0, 0);
str = fo.read(10);
print "Again read String is : ", str
# Close opend file
fo.close()
This produces the following result −
Read String is : Python is
Current file position : 10
Again read String is : Python is
Renaming and Deleting Files

Python os module provides methods that help you perform file-processing


operations, such as renaming and deleting files.
To use this module you need to import it first and then you can call any
related functions.
The rename() Method

The rename() method takes two arguments, the current filename and the
new filename.
Syntax
os.rename(current_file_name, new_file_name)
Example
Following is the example to rename an existing file test1.txt:
#!/usr/bin/python
import os

# Rename a file from test1.txt to test2.txt


os.rename( "test1.txt", "test2.txt" )
The remove() Method

You can use the remove() method to delete files by supplying the name of
the file to be deleted as the argument.
Syntax
os.remove(file_name)
Example
Following is the example to delete an existing file test2.txt −
#!/usr/bin/python
import os

# Delete file test2.txt


os.remove("text2.txt")

Python File Methods

A file object is created using open function and here is a list of functions
which can be called on this object −
Methods with Description

file.close()
Close the file. A closed file cannot be read or written any more.

file.flush()
Flush the internal buffer, like stdio's fflush. This may be a no-op on
some file-like objects.

file.next()
Returns the next line from the file each time it is being called.

file.read([size])
Reads at most size bytes from the file (less if the read hits EOF
before obtaining size bytes).

file.readline([size])
Reads one entire line from the file. A trailing newline character is
kept in the string.

file.readlines([sizehint])
Reads until EOF using readline() and return a list containing the
lines. If the optional sizehint argument is present, instead of
reading up to EOF, whole lines totalling approximately sizehint
bytes (possibly after rounding up to an internal buffer size) are
read.

file.seek(offset[, whence])
Sets the file's current position

file.tell()
Returns the file's current position

file.write(str)
Writes a string to the file. There is no return value.

file.writelines(sequence)
Writes a sequence of strings to the file. The sequence can be any
iterable object producing strings, typically a list of strings.

Exception
An exception is an event, which occurs during the execution of a program
that disrupts the normal flow of the program's instructions. In general,
when a Python script encounters a situation that it cannot cope with, it
raises an exception. An exception is a Python object that represents an
error.
When a Python script raises an exception, it must either handle the
exception immediately otherwise it terminates and quits.

Handling an exception
If we have some suspicious code that may raise an exception, we can
defend our program by placing the suspicious code in a try: block. After
the try: block, include an except: statement, followed by a block of code
which handles the problem as elegantly as possible.

Syntax
Here is simple syntax of try....except...else blocks −

try:
You do your operations here;
......................
except ExceptionI:
If there is ExceptionI, then execute this block.
except ExceptionII:
If there is ExceptionII, then execute this block.
......................
else:
If there is no exception then execute this block.

Here are few important points about the above-mentioned syntax −

 A single try statement can have multiple except statements. This is


useful when the try block contains statements that may throw
different types of exceptions.
 We can also provide a generic except clause, which handles any
exception.
 After the except clause(s), we can include an else-clause. The code
in the else-block executes if the code in the try: block does not raise
an exception.
 The else-block is a good place for code that does not need the try:
block's protection.
Example
This example opens a file, writes content in the, file and comes out
gracefully because there is no problem at all −

try:
fh = open("testfile", "w")
fh.write("This is my test file for exception handling!!")
except IOError:
print "Error: can\'t find file or read data"
else:
print "Written content in the file successfully"
fh.close()

This produces the following result −

Written content in the file successfully

Example
This example tries to open a file where you do not have write permission,
so it raises an exception −

#!/usr/bin/python

try:
fh = open("testfile", "r")
fh.write("This is my test file for exception handling!!")
except IOError:
print "Error: can\'t find file or read data"
else:
print "Written content in the file successfully"

This produces the following result −

Error: can't find file or read data

The except Clause with No Exceptions


You can also use the except statement with no exceptions defined as
follows −
try:
You do your operations here;
......................
except:
If there is any exception, then execute this block.
......................
else:
If there is no exception then execute this block.

This kind of a try-except statement catches all the exceptions that


occur. Using this kind of try-except statement is not considered a good
programming practice though, because it catches all exceptions but does
not make the programmer identify the root cause of the problem that
may occur.

The except Clause with Multiple Exceptions


You can also use the same except statement to handle multiple
exceptions as follows −

try:
You do your operations here;
......................
except(Exception1[, Exception2[,...ExceptionN]]]):
If there is any exception from the given exception list,
then execute this block.
......................
else:
If there is no exception then execute this block.

The try-finally Clause


You can use a finally: block along with a try: block. The finally block is a
place to put any code that must execute, whether the try-block raised an
exception or not. The syntax of the try-finally statement is this −

try:
You do your operations here;
......................
Due to any exception, this may be skipped.
finally:
This would always be executed.
......................

You cannot use else clause as well along with a finally clause.

Example
#!/usr/bin/python

try:
fh = open("testfile", "w")
fh.write("This is my test file for exception handling!!")
finally:
print "Error: can\'t find file or read data"

If you do not have permission to open the file in writing mode, then this
will produce the following result:

Error: can't find file or read data

Same example can be written more cleanly as follows −

try:
fh = open("testfile", "w")
try:
fh.write("This is my test file for exception handling!!")
finally:
print "Going to close the file"
fh.close()
except IOError:
print "Error: can\'t find file or read data"

When an exception is thrown in the try block, the execution immediately


passes to the finally block. After all the statements in the finally block are
executed, the exception is raised again and is handled in
the except statements if present in the next higher layer of the try-
except statement.
UNIT – IV
OOP Terminology
 Class: A user-defined prototype for an object that defines a set of
attributes that characterize any object of the class. The attributes
are data members (class variables and instance variables) and
methods, accessed via dot notation.
 Class variable: A variable that is shared by all instances of a class.
Class variables are defined within a class but outside any of the
class's methods. Class variables are not used as frequently as
instance variables are.
 Data member: A class variable or instance variable that holds data
associated with a class and its objects.
 Function overloading: The assignment of more than one behavior
to a particular function. The operation performed varies by the
types of objects or arguments involved.
 Instance variable: A variable that is defined inside a method and
belongs only to the current instance of a class.
 Inheritance: The transfer of the characteristics of a class to other
classes that are derived from it.
 Instance: An individual object of a certain class. An object obj that
belongs to a class Circle, for example, is an instance of the class
Circle.
 Instantiation: The creation of an instance of a class.
 Method : A special kind of function that is defined in a class
definition.
 Object: A unique instance of a data structure that's defined by its
class. An object comprises both data members (class variables and
instance variables) and methods.
 Operator overloading: The assignment of more than one function
to a particular operator.

Creating Classes

The class statement creates a new class definition. The name of the class
immediately follows the keyword class followed by a colon as follows −

class ClassName:
'Optional class documentation string'
class_suite
Example
Following is the example of a simple Python class −

class Employee:
'Common base class for all employees'
empCount = 0

def __init__(self, name, salary):


self.name = name
self.salary = salary
Employee.empCount += 1

def displayCount(self):
print "Total Employee %d" % Employee.empCount

def displayEmployee(self):
print "Name : ", self.name, ", Salary: ", self.salary

Creating Instance Objects

To create instances of a class, we call the class using class name and
pass in whatever arguments its __init__ method accepts.

"This would create first object of Employee class"


emp1 = Employee("Zara", 2000)
"This would create second object of Employee class"
emp2 = Employee("Manni", 5000)

Accessing Attributes

we access the object's attributes using the dot operator with object. Class
variable would be accessed using class name as follows −

emp1.displayEmployee()
emp2.displayEmployee()
print "Total Employee %d" % Employee.empCount

Now, putting all the concepts together −

class Employee:
'Common base class for all employees'
empCount = 0
def __init__(self, name, salary):
self.name = name
self.salary = salary
Employee.empCount += 1

def displayCount(self):
print "Total Employee %d" % Employee.empCount

def displayEmployee(self):
print "Name : ", self.name, ", Salary: ", self.salary

"This would create first object of Employee class"


emp1 = Employee("Zara", 2000)
"This would create second object of Employee class"
emp2 = Employee("Manni", 5000)
emp1.displayEmployee()
emp2.displayEmployee()
print "Total Employee %d" % Employee.empCount

When the above code is executed, it produces the following result −

Name : Zara ,Salary: 2000


Name : Manni ,Salary: 5000
Total Employee 2

You can add, remove, or modify attributes of classes and objects at any
time −

emp1.age = 7 # Add an 'age' attribute.


emp1.age = 8 # Modify 'age' attribute.
del emp1.age # Delete 'age' attribute.

Destroying Objects (Garbage Collection)


Python deletes unneeded objects (built-in types or class instances)
automatically to free the memory space. The process by which Python
periodically reclaims blocks of memory that no longer are in use is termed
Garbage Collection.
Python's garbage collector runs during program execution and is
triggered when an object's reference count reaches zero. An object's
reference count changes as the number of aliases that point to it
changes.

An object's reference count increases when it is assigned a new name or


placed in a container (list, tuple, or dictionary). The object's reference
count decreases when it's deleted with del, its reference is reassigned, or
its reference goes out of scope. When an object's reference count reaches
zero, Python collects it automatically.

a = 40 # Create object <40>


b=a # Increase ref. count of <40>
c = [b] # Increase ref. count of <40>

del a # Decrease ref. count of <40>


b = 100 # Decrease ref. count of <40>
c[0] = -1 # Decrease ref. count of <40>

You normally will not notice when the garbage collector destroys an
orphaned instance and reclaims its space. But a class can implement the
special method __del__(), called a destructor, that is invoked when the
instance is about to be destroyed. This method might be used to clean up
any non memory resources used by an instance.

Example
This __del__() destructor prints the class name of an instance that is about
to be destroyed −

#!/usr/bin/python

class Point:
def __init( self, x=0, y=0):
self.x = x
self.y = y
def __del__(self):
class_name = self.__class__.__name__
print class_name, "destroyed"

pt1 = Point()
pt2 = pt1
pt3 = pt1
print id(pt1), id(pt2), id(pt3) # prints the ids of the obejcts
del pt1
del pt2
del pt3

When the above code is executed, it produces following result −

3083401324 3083401324 3083401324


Point destroyed

Class Inheritance
Instead of starting from scratch, we can create a class by deriving it from
a preexisting class by listing the parent class in parentheses after the new
class name.

The child class inherits the attributes of its parent class, and we can use
those attributes as if they were defined in the child class. A child class can
also override data members and methods from the parent.

Syntax
Derived classes are declared much like their parent class; however, a list
of base classes to inherit from is given after the class name −

class SubClassName (ParentClass1[, ParentClass2, ...]):


'Optional class documentation string'
class_suite

Example
class Parent: # define parent class
parentAttr = 100
def __init__(self):
print "Calling parent constructor"

def parentMethod(self):
print 'Calling parent method'
def setAttr(self, attr):
Parent.parentAttr = attr
def getAttr(self):
print "Parent attribute :", Parent.parentAttr

class Child(Parent): # define child class


def __init__(self):
print "Calling child constructor"

def childMethod(self):
print 'Calling child method'

c = Child() # instance of child


c.childMethod() # child calls its method
c.parentMethod() # calls parent's method
c.setAttr(200) # again call parent's method
c.getAttr() # again call parent's method

When the above code is executed, it produces the following result −

Calling child constructor


Calling child method
Calling parent method
Parent attribute : 200

Similar way, we can drive a class from multiple parent classes as follows

class A: # define your class A


.....
class B: # define your class B
.....

class C(A, B): # subclass of A and B


.....

we can use issubclass() or isinstance() functions to check a relationships


of two classes and instances.

 The issubclass(sub, sup) boolean function returns true if the


given subclass sub is indeed a subclass of the superclass sup.
 The isinstance(obj, Class) boolean function returns true if obj is
an instance of class Class or is an instance of a subclass of Class

Overriding Methods
we can always override your parent class methods. One reason for
overriding parent's methods is because you may want special or different
functionality in our subclass.

Example
class Parent: # define parent class
def myMethod(self):
print 'Calling parent method'

class Child(Parent): # define child class


def myMethod(self):
print 'Calling child method'

c = Child() # instance of child


c.myMethod() # child calls overridden method

When the above code is executed, it produces the following result −

Calling child method

Overloading Operators
Here we can give special meaning to operators. The below program adds
two vector objects. Here it gives special meaning to + operator. So we call
it as Operator overloading.
Example

class Vector:
def __init__(self, a, b):
self.a = a
self.b = b

def __str__(self):
return 'Vector (%d, %d)' % (self.a, self.b)

def __add__(self,other):
return Vector(self.a + other.a, self.b + other.b)

v1 = Vector(2,10)
v2 = Vector(5,-2)
print v1 + v2
When the above code is executed, it produces the following result −

Vector(7,8)

Data Hiding
An object's attributes may or may not be visible outside the class
definition. we need to name attributes with a double underscore prefix,
and those attributes then are not be directly visible to outsiders.

Example
class JustCounter:
__secretCount = 0

def count(self):
self.__secretCount += 1
print self.__secretCount

counter = JustCounter()
counter.count()
counter.count()
print counter.__secretCount

When the above code is executed, it produces the following result −

1
2
Traceback (most recent call last):
File "test.py", line 12, in <module>
print counter.__secretCount
AttributeError: JustCounter instance has no attribute '__secretCount'

Python protects those members by internally changing the name to


include the class name. You can access such attributes
as object._className__attrName. If you would replace your last line as
following, then it works for you −

.........................
print counter._JustCounter__secretCount

When the above code is executed, it produces the following result −

1
2
2

You might also like