0% found this document useful (0 votes)
2 views93 pages

Python Programming

Uploaded by

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

Python Programming

Uploaded by

abisriyaabisriya
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

II M.

Sc – Computer Science
PAPER X - PYTHON PROGRAMMING
Subject Code – 33B

UNIT-I
Python Overview
Python is a high-level, interpreted, interactive and object-oriented scripting language. Python is designed to be highly readable. It
uses English keywords frequently where as other languages use punctuation, and it has fewer syntactical constructions than other
languages.

 Python is Interpreted − Python is processed at runtime by the interpreter. You do not need to compile your program
before executing it. This is similar to PERL and PHP.

 Python is Interactive − You can actually sit at a Python prompt and interact with the interpreter directly to write your
programs.

 Python is Object-Oriented − Python supports Object-Oriented style or technique of programming that encapsulates
code within objects.

 Python is a Beginner's Language − Python is a great language for the beginner-level programmers and supports the
development of a wide range of applications 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 − You 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 - Numbers
Number data types store numeric values. They are immutable data types, means that changing the value of a number data type
results in a newly allocated object.
Number objects are created when you assign a value to them. For example −
var1 = 1
var2 = 10

You can also delete the reference to a number object by using the del statement. The syntax of the del statement is −
del var1[,var2[,var3[....,varN]]]]

You can delete a single object or multiple objects by using the del statement. For example −
del var
del var_a, var_b

Python supports four different numerical types −

 int (signed integers) − They are often called just integers or ints, are positive or negative whole numbers with no
decimal point.

 long (long integers ) − Also called longs, they are integers of unlimited size, written like integers and f ollowed by an
uppercase or lowercase L.

 float (floating point real values) − Also called floats, they represent real numbers and are written with a decimal point
dividing the integer and fractional parts. Floats may also be in scientific notation, with E or e indicating the power of 10
(2.5e2 = 2.5 x 102 = 250).

 complex (complex numbers) − are of the form a + bJ, where a and b are floats and J (or j) represents the square root of
-1 (which is an imaginary number). The real part of the number is a, and the imaginary part is b. Complex numbers are
not used much in Python programming.

Examples
Here are some examples of numbers

int long float complex

10 51924361L 0.0 3.14j

100 -0x19323L 15.20 45.j

-786 0122L -21.9 9.322e-36j

080 0xDEFABCECBDAECBFBAEL 32.3+e18 .876j

-0490 535633629843L -90. -.6545+0J

-0x260 -052318172735L -32.54e100 3e+26J

0x69 -4721885298529L 70.2-E12 4.53e-7j

 Python allows you to use a lowercase L with long, but it is recommended that you use only an uppercase L to avoid
confusion with the number 1. Python displays long integers with an uppercase L.

 A complex number consists of an ordered pair of real floating point numbers denoted by a + bj, where a is the real part
and b is the imaginary part of the complex number.
Number Type Conversion
Python converts numbers internally in an expression containing mixed types to a common type for evaluation. But sometimes, yo u
need to coerce a number explicitly from one type to another to satisfy the requirements of an operator or function parameter.

 Type int(x) to convert x to a plain integer.

 Type long(x) to convert x to a long integer.

 Type float(x) to convert x to a floating-point number.

 Type complex(x) to convert x to a complex number with real part x and imaginary part zero.

 Type complex(x, y) to convert x and y to a complex number with real part x and imaginary part y. x and y are numeric
expressions

Mathematical Functions
Python includes following functions that perform mathematical calculations.

[Link]. Function & Returns ( description )

1 abs(x)
The absolute value of x: the (positive) distance between x and zero.

2 ceil(x)
The ceiling of x: the smallest integer not less than x

3 cmp(x, y)
-1 if x < y, 0 if x == y, or 1 if x > y

4 exp(x)
The exponential of x: ex

5 fabs(x)
The absolute value of x.

6 floor(x)
The floor of x: the largest integer not greater than x

7 log(x)
The natural logarithm of x, for x> 0

8 log10(x)
The base-10 logarithm of x for x> 0.

9 max(x1, x2,...)
The largest of its arguments: the value closest to positive infinity

10 min(x1, x2,...)
The smallest of its arguments: the value closest to negative infinity

11 modf(x)
The fractional and integer parts of x in a two-item tuple. Both parts have the same sign as x. The
integer part is returned as a float.

12 pow(x, y)
The value of x**y.

13 round(x [,n])
x rounded to n digits from the decimal point. Python rounds away from zero as a tie-breaker:
round(0.5) is 1.0 and round(-0.5) is -1.0.

14 sqrt(x)
The square root of x for x > 0

Random Number Functions


Random numbers are used for games, simulations, testing, security, and privacy applications. Python includes following functions
that are commonly used.

[Link]. Function & Description

1 choice(seq)
A random item from a list, tuple, or string.

2 randrange ([start,] stop [,step])


A randomly selected element from range(start, stop, step)

3 random()
A random float r, such that 0 is less than or equal to r and r is less than 1

4 seed([x])
Sets the integer starting value used in generating random numbers. Call this function before
calling any other random module function. Returns None.

5 shuffle(lst)
Randomizes the items of a list in place. Returns None.

6 uniform(x, y)
A random float r, such that x is less than or equal to r and r is less than y

Trigonometric Functions
Python includes following functions that perform trigonometric calculations.

[Link]. Function & Description

1 acos(x)
Return the arc cosine of x, in radians.

2 asin(x)
Return the arc sine of x, in radians.

3 atan(x)
Return the arc tangent of x, in radians.

4 atan2(y, x)
Return atan(y / x), in radians.

5 cos(x)
Return the cosine of x radians.

6 hypot(x, y)
Return the Euclidean norm, sqrt(x*x + y*y).

7 sin(x)
Return the sine of x radians.

8 tan(x)
Return the tangent of x radians.

9 degrees(x)
Converts angle x from radians to degrees.

10 radians(x)
Converts angle x from degrees to radians.

Mathematical Constants
The module also defines two mathematical constants −

[Link]. Constants & Description

1 pi
The mathematical constant pi.

2 e
The mathematical constant e.

Python - Basic Syntax


The Python language has many similarities to Perl, C, and Java. However, there are some definite differences between the
languages.

First Python Program


Let us execute programs in different modes of programming.
Interactive Mode Programming
Invoking the interpreter without passing a script file as a parameter brings up the following prompt –
$ python
Python 2.4.3 (#1, Nov 11 2010, 13:34:43)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-48)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>

Type the following text at the Python prompt and press the Enter −

>>> print "Hello, Python!"

If you are running new version of Python, then you would need to use print statement with parenthesis as in print ("Hello,
Python!");. However in Python version 2.4.3, this produces the following result −
Hello, Python!

Script Mode Programming


Invoking the interpreter with a script parameter begins execution of the script and continues until the script is finished. W hen the
script is finished, the interpreter is no longer active.
Let us write a simple Python program in a script. Python files have extension .py. Type the following source code in a [Link] file −

print "Hello, Python!"

We assume that you have Python interpreter set in PATH variable. Now, try to run this program as follows −

$ python [Link]

This produces the following result −


Hello, Python!

Let us try another way to execute a Python script. Here is the modified [Link] file −

#!/usr/bin/python

print "Hello, Python!"

We assume that you have Python interpreter available in /usr/bin directory. Now, try to run this program as follows −

$ chmod +x [Link] # This is to make file executable


$./[Link]

This produces the following result −


Hello, Python!

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. Thus, Manpower and manpower are two different identifiers in Python.
Here are naming conventions for Python identifiers −

 Class names start with an uppercase letter. All other identifiers start with a lowercase letter.

 Starting an identifier with a single leading underscore indicates that the identifier is private.

 Starting an identifier with two leading underscores indicates a strongly private identifier.

 If the identifier also ends with two trailing underscores, the identifier is a language-defined special name.

Reserved Words
The following list shows the Python keywords. These are reserved words and you cannot use them as constant or variabl e or any
other identifier names. All the Python keywords contain lowercase letters only.
and exec not

assert finally or

break for pass

class from print

continue global raise

def if return

del import try

elif in while

else is with

except lambda 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 d enoted
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"

However, the following block generates an error −

if True:
print "Answer"
print "True"
else:
print "Answer"

print "False"

Thus, in Python all the continuous lines indented with same number of spaces would form a block. The following example has
various statement blocks −
Note − Do not try to understand the logic at this point of time. Just make sure you understood various blocks even if they are
without braces.

#!/usr/bin/python

import sys

try:
# open file stream

file = open(file_name, "w")


except IOError:
print "There was an error writing to", file_name
[Link]()
print "Enter '", file_finish,
print "' When finished"
while file_text != file_finish:
file_text = raw_input("Enter text: ")
if file_text == file_finish:
# close the file
[Link]
break
[Link](file_text)
[Link]("\n")
[Link]()
file_name = raw_input("Enter filename: ")
if len(file_name) == 0:
print "Next time please enter something"
[Link]()
try:
file = open(file_name, "r")
except IOError:
print "There was an error reading file"
[Link]()
file_text = [Link]()
[Link]()

print file_text

Multi-Line Statements
Statements in Python typically end with a new line. Python does, however, allow the use of the line continuation character ( \) to
denote that the line should continue. For example −
total = item_one + \
item_two + \
item_three

Statements contained within the [], {}, or () brackets do not need to use the line continuation character. For example −
days = ['Monday', 'Tuesday', 'Wednesday',
'Thursday', 'Friday']

Quotation in Python
Python accepts single ('), double (") and triple (''' or """) quotes to denote string literals, as long as the same type of quote starts
and ends the string.
The triple quotes are used to span the string across multiple lines. For example, all the following are legal −
word = 'word'
sentence = "This is a sentence."
paragraph = """This is a paragraph. It is
made up of multiple lines and sentences."""
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.

#!/usr/bin/python

# First comment
print "Hello, Python!" # second comment

This produces the following result −


Hello, Python!

You can type a comment on the same line after a statement or expression −
name = "Madisetti" # This is again comment

You can comment multiple lines as follows −


# This is a comment.
# This is a comment, too.
# This is a comment, too.
# I said that already.

Using Blank Lines


A line containing only whitespace, possibly with a comment, is known as a blank line and Python totally ignores it.
In an interactive interpreter session, you must enter an empty physical line to terminate a multiline statement.

Waiting for the User


The following line of the program displays the prompt, the statement saying “Press the enter key to exit”, and waits for the user to
take action −

#!/usr/bin/python

raw_input("\n\nPress the enter key to exit.")

Here, "\n\n" is used to create two new lines before displaying the actual line. Once the user presses the key, the program ends.
This is a nice trick to keep a console window open until the user is done with an application.

Multiple Statements on a Single Line


The semicolon ( ; ) allows multiple statements on the single line given that neither statement starts a new code block. Here is a
sample snip using the semicolon −

import sys; x = 'foo'; [Link](x + '\n')

Multiple Statement Groups as Suites


A group of individual statements, which make a single code block are called suites in Python. Compound or complex statements,
such as if, while, def, and class require a header line and a suite.
Header lines begin the statement (with the keyword) and terminate with a colon ( : ) and are followed by one or more lines which
make up the suite. For example −
if expression :
suite
elif expression :
suite
else :
suite
Command Line Arguments
Many programs can be run to provide you with some basic information about how they should be run. Python enables you to do
this with -h −

$ python -h
usage: python [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-c cmd : program passed in as string (terminates option list)
-d : debug output from parser (also PYTHONDEBUG=x)
-E : ignore environment variables (such as PYTHONPATH)
-h : print this help message and exit

[ etc. ]

You can also program your script in such a way that it should accept various options. Command Line Arguments is an advanced
topic and should be studied a bit later once you have gone through rest of the Python concepts.

Python - Variable Types


Variables are nothing but reserved memory locations to store values. This means that when you create a variable you reserve
some space in memory.
Based on the data type of a variable, the interpreter allocates memory and decides what can be stored in the reserved memory.
Therefore, by assigning different data types to variables, you can store integers, decimals or characters in these variables.

Assigning Values to Variables


Python variables do not need explicit declaration to reserve memory space. The declaration happens automatically when you
assign a value to a variable. The equal sign (=) is used to assign values to variables.
The operand to the left of the = operator is the name of the variable and the operand to the right of the = operator is the value
stored in the variable. For example −

counter = 100 # An integer assignment


miles = 1000.0 # A floating point
name = "John" # A string

print counter
print miles
print name

Here, 100, 1000.0 and "John" are the values assigned to counter, miles, and name variables, respectively. This produces the
following result −
100
1000.0
John

Multiple Assignment
Python allows you to assign a single value to several variables simultaneously. For example −
a=b=c=1

Here, an integer object is created with the value 1, and all three variables are assigned to the same memory location. You can also
assign multiple objects to multiple variables. For example −
a,b,c = 1,2,"john"

Here, two integer objects with values 1 and 2 are assigned to variables a and b respectively, and one string object with the value
"john" is assigned to the variable c.
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
Number data types store numeric values. Number objects are created when you assign a value to them. For example −
var1 = 1
var2 = 10

You can also delete the reference to a number object by using the del statement. The syntax of the del statement is −
del var1[,var2[,var3[....,varN]]]]

You can delete a single object or multiple objects by using the del statement. For example −
del var
del var_a, var_b

Python supports four different numerical types −

 int (signed integers)

 long (long integers, they can also be represented in octal and hexadecimal)

 float (floating point real values)

 complex (complex numbers)

Examples
Here are some examples of numbers −

int long float complex

10 51924361L 0.0 3.14j

100 -0x19323L 15.20 45.j

-786 0122L -21.9 9.322e-36j

080 0xDEFABCECBDAECBFBAEl 32.3+e18 .876j

-0490 535633629843L -90. -.6545+0J

-0x260 -052318172735L -32.54e100 3e+26J

0x69 -4721885298529L 70.2-E12 4.53e-7j


 Python allows you to use a lowercase l with long, but it is recommended that you use only an uppercase L to avoid
confusion with the number 1. Python displays long integers with an uppercase L.

 A complex number consists of an ordered pair of real floating-point numbers denoted by x + yj, where x and y are the real
numbers and j is the imaginary unit.

Python Strings
Strings in Python are identified as a contiguous set of characters represented in the quotation marks. Python allows for eith er pairs
of single or double quotes. Subsets of strings can be taken using the slice operator ([ ] and [:] ) with indexes starting at 0 in the
beginning of the string and working their way from -1 at the end.
The plus (+) sign is the string concatenation operator and the asterisk (*) is the repetition operator. For example −

#!/usr/bin/python

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

This will produce the following result −


Hello World!
H
llo
llo World!
Hello World!Hello World!
Hello World!TEST

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 bel onging to
a list can be of different data type.
The values stored in a list can be accessed using the slice operator ([ ] and [:]) with indexes starting at 0 in the beginning of the list
and working their way to end -1. The plus (+) sign is the list concatenation operator, and the asterisk (*) is the repetition operator.
For example −

#!/usr/bin/python

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

This produce the following result −


['abcd', 786, 2.23, 'john', 70.2]
abcd
[786, 2.23]
[2.23, 'john', 70.2]
[123, 'john', 123, 'john']
['abcd', 786, 2.23, 'john', 70.2, 123, 'john']

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 −

#!/usr/bin/python
tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )
tinytuple = (123, 'john')
print tuple # Prints the complete tuple
print tuple[0] # Prints first element of the tuple
print tuple[1:3] # Prints elements of the tuple starting from 2nd till 3rd
print tuple[2:] # Prints elements of the tuple starting from 3rd element
print tinytuple * 2 # Prints the contents of the tuple twice
print tuple + tinytuple # Prints concatenated tuples

This produce the following result −


('abcd', 786, 2.23, 'john', 70.2)
abcd
(786, 2.23)
(2.23, 'john', 70.2)
(123, 'john', 123, 'john')
('abcd', 786, 2.23, 'john', 70.2, 123, 'john')

The following code is invalid with tuple, because we attempted to update a tuple, which is not allowed. Similar case is possi ble with
lists −

#!/usr/bin/python
tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )
list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
tuple[2] = 1000 # Invalid syntax with tuple
list[2] = 1000 # Valid syntax with list

Python Dictionary
Python's dictionaries are kind of hash table type. They work like associative arrays or hashes found in Perl and consist of k ey-
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 −

#!/usr/bin/python
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 [Link]() # Prints all the keys
print [Link]() # Prints all the values

This produce the following result −


This is one
This is two
{'dept': 'sales', 'code': 6734, 'name': 'john'}
['dept', 'code', 'name']
['sales', 6734, 'john']

Dictionaries have no concept of order among elements. It is incorrect to say that the elements are "out of order"; they are s imply
unordered.

Data Type Conversion


Sometimes, you may need to perform conversions between the built-in types. To convert between types, you 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.

[Link]. Function & Description

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

2 long(x [,base] )
Converts x to a long integer. base specifies the base if x is a string.

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

4 complex(real [,imag])
Creates a complex number.

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

6 repr(x)
Converts object x to an expression string.

7 eval(str)
Evaluates a string and returns an object.

8 tuple(s)
Converts s to a tuple.

9 list(s)
Converts s to a list.

10 set(s)
Converts s to a set.

11 dict(d)
Creates a dictionary. d must be a sequence of (key,value) tuples.

12 frozenset(s)
Converts s to a frozen set.

13 chr(x)
Converts an integer to a character.

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

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

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

17 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 Operator
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 operator. a + b = 30

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

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


Multiplication

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

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

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

// Floor Division - The division of operands where the result is the quotient in which the digits 9//2 = 4 and 9.0//2.0
after the decimal point are removed. But if one of the operands is negative, the result is = 4.0, -11//3 = -4, -
floored, i.e., rounded away from zero (towards negative infinity) − 11.0//3 = -4.0

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 −
[ Show Example ]

Operator Description Example

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

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

<> If values of two operands are not equal, then condition becomes true. (a <> b) is true. This is similar to !=
operator.

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

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

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

<= If the value of left operand is less than or equal to the value of right operand, (a <= b) is true.
then condition becomes true.
Python Assignment Operators
Assume variable a holds 10 and variable b holds 20, then −
[ Show Example ]

Operator Description Example

= Assigns values from right side operands to left side operand


c = a + b assigns value of a +
b into c

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

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

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

/= Divide AND It divides left operand with the right operand and assign the result to
c /= a is equivalent to c = c /
left operand
a

%= Modulus It takes modulus using two operands and assign the result to left
c %= a is equivalent to c = c
AND operand
%a

**= Exponent Performs exponential (power) calculation on operators and assign


c **= a is equivalent to c = c
AND value to the left operand
** a

//= Floor It performs floor division on operators and assign value to the left
c //= a is equivalent to c = c //
Division operand
a

Python Bitwise Operators


Bitwise operator works on bits and performs bit by bit operation. Assume if a = 60; and b = 13; Now in the binary format their
values will be 0011 1100 and 0000 1101 respectively. Following table lists out the bitwise operators supported by Python language
with an example each in those, we use the above two variables (a and b) as operands −
a = 0011 1100
b = 0000 1101
-----------------
a&b = 0000 1100
a|b = 0011 1101
a^b = 0011 0001
~a = 1100 0011
There are following Bitwise operators supported by Python language
[ Show Example ]

Operator Description Example

& Binary AND Operator copies a bit to the result if it exists in both (a & b) (means 0000
operands 1100)

| Binary OR It copies a bit if it exists in either operand. (a | b) = 61 (means


0011 1101)

^ Binary XOR It copies the bit if it is set in one operand but not both. (a ^ b) = 49 (means
0011 0001)

~ Binary Ones (~a ) = -61 (means


Complement 1100 0011 in 2's
It is unary and has the effect of 'flipping' bits. complement form
due to a signed
binary number.

<< Binary Left Shift The left operands value is moved left by the number of bits a << 2 = 240
specified by the right operand. (means 1111 0000)

>> Binary Right Shift The left operands value is moved right by the number of a >> 2 = 15 (means
bits specified by the right operand. 0000 1111)

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 If both the operands are true then condition becomes true. (a and b)
is true.
Logical
AND

Or If any of the two operands are non-zero then condition (a or b)


becomes true. is true.
Logical OR

not Used to reverse the logical state of its operand. Not(a


and b) is
Logical
false.
NOT

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 −

Operator Description Example

in Evaluates to true if it finds a variable in the specified sequence and false x in y,


otherwise. here in
results in
a 1 if x is
a
member
of
sequence
y.

not in Evaluates to true if it does not finds a variable in the specified sequence x not in y,
and false otherwise. here not
in results
in a 1 if x
is not a
member
of
sequence
y.

Python Identity Operators


Identity operators compare the memory locations of two objects. There are two Identity operators explained below −
[ Show Example ]

Operator Description Example

is Evaluates to true if the variables on either side of the operator point to the same x is y,
object and false otherwise. here is results
in 1 if id(x)
equals id(y).

is not Evaluates to false if the variables on either side of the operator point to the x is not y,
same object and true otherwise. here is
not results in
1 if id(x) is not
equal to id(y).

Python Operators Precedence


The following table lists all operators from highest precedence to lowest.
[ Show Example ]

[Link]. Operator & Description

1 **
Exponentiation (raise to the power)

2 ~+-
Complement, unary plus and minus (method names for the last two are +@
and -@)

3 * / % //
Multiply, divide, modulo and floor division
4 +-
Addition and subtraction

5 >> <<
Right and left bitwise shift

6 &
Bitwise 'AND'

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

8 <= < > >=


Comparison operators

9 <> == !=
Equality operators

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

11 is is not
Identity operators

12 in not in
Membership operators

13 not or and
Logical operators

Python Collections (Arrays)


There are four collection data types in the Python programming language:

 List is a collection which is ordered and changeable. Allows duplicate members.

 Tuple is a collection which is ordered and unchangeable. Allows duplicate members.

 Set is a collection which is unordered and unindexed. No duplicate members.

 Dictionary is a collection which is unordered, changeable and indexed. No duplicate members.


When choosing a collection type, it is useful to understand the properties of that type. Choosing the right type for a particular data
set could mean retention of meaning, and, it could mean an increase in efficiency or security.

List
A list is a collection which is ordered and changeable. In Python lists are written with square brackets.

Example
Create a List:
thislist = ["apple", "banana", "cherry"]
print(thislist)

Access Items
You access the list items by referring to the index number:

Example
Print the second item of the list:
thislist = ["apple", "banana", "cherry"]
print(thislist[1])

Negative Indexing
Negative indexing means beginning from the end, -1 refers to the last item, -2 refers to the second last item etc.

Example
Print the last item of the list:
thislist = ["apple", "banana", "cherry"]
print(thislist[-1])

Range of Indexes
You can specify a range of indexes by specifying where to start and where to end the range.
When specifying a range, the return value will be a new list with the specified items.

Example
Return the third, fourth, and fifth item:
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[2:5])
Note: The search will start at index 2 (included) and end at index 5 (not included).
Remember that the first item has index 0.
By leaving out the start value, the range will start at the first item:

Example
This example returns the items from the beginning to "orange":
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[:4])
By leaving out the end value, the range will go on to the end of the list:

Example
This example returns the items from "cherry" and to the end:
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[2:])

Range of Negative Indexes


Specify negative indexes if you want to start the search from the end of the list:

Example
This example returns the items from index -4 (included) to index -1 (excluded)
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[-4:-1])
Change Item Value
To change the value of a specific item, refer to the index number:

Example
Change the second item:
thislist = ["apple", "banana", "cherry"]
thislist[1] = "blackcurrant"
print(thislist)

Python Tuples
Tuple
A tuple is a collection which is ordered and unchangeable. In Python tuples are written with round brackets.

Example
Create a Tuple:
thistuple = ("apple", "banana", "cherry")
print(thistuple)

Access Tuple Items


You can access tuple items by referring to the index number, inside square brackets:

Example
Print the second item in the tuple:
thistuple = ("apple", "banana", "cherry")
print(thistuple[1])

Negative Indexing
Negative indexing means beginning from the end, -1 refers to the last item, -2 refers to the second last item etc.

Example
Print the last item of the tuple:
thistuple = ("apple", "banana", "cherry")
print(thistuple[-1])

Range of Indexes
You can specify a range of indexes by specifying where to start and where to end the range.
When specifying a range, the return value will be a new tuple with the specified items.

Example
Return the third, fourth, and fifth item:
thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
print(thistuple[2:5])

Note: The search will start at index 2 (included) and end at index 5 (not included).
Remember that the first item has index 0.

Range of Negative Indexes


Specify negative indexes if you want to start the search from the end of the tuple:
Example
This example returns the items from index -4 (included) to index -1 (excluded)
thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
print(thistuple[-4:-1])

Python Sets
Set

 A set is a collection which is unordered and unindexed.


 In Python sets are written with curly brackets.
Example
Create a Set:
thisset = {"apple", "banana", "cherry"}
print(thisset)

Result1: {'apple', 'cherry', 'banana'}

Result2: {'banana','apple', 'cherry'}

Result3: {'banana', 'cherry', 'apple' }

Note: Sets are unordered, so you cannot be sure in which order the items will appear.
Access Items
 You cannot access items in a set by referring to an index, since sets are unordered the items has no index.
 But you can loop through the set items using a for loop, or ask if a specified value is present in a set, by using the
in keyword.
Example
Loop through the set, and print the values:
thisset = {"apple", "banana", "cherry"}
for x in thisset:
print(x)

apple
banana
cherry

Example
Check if "banana" is present in the set:
thisset = {"apple", "banana", "cherry"}
print("banana" in thisset)

True
Change Items
 Once a set is created, you cannot change its items, but you can add new items.
Add Items
 To add one item to a set use the add() method.
 To add more than one item to a set use the update() method.
Example
Add an item to a set, using the add() method:
thisset = {"apple", "banana", "cherry"}
[Link]("orange")
print(thisset)

Example
Add multiple items to a set, using the update() method:

thisset = {"apple", "banana", "cherry"}


[Link](["orange", "mango", "grapes"])
print(thisset)

Get the Length of a Set


 To determine how many items a set has, use the len() method.
Example
Get the number of items in a set:
thisset = {"apple", "banana", "cherry"}
print(len(thisset))

3
Remove Item
 To remove an item in a set, use the remove(), or the discard() method.
Example
Remove "banana" by using the remove() method:
thisset = {"apple", "banana", "cherry"}
[Link]("banana")
print(thisset)

Note: If the item to remove does not exist, remove() will raise an error.
Example
Remove "banana" by using the discard() method:
thisset = {"apple", "banana", "cherry"}
[Link]("banana")
print(thisset)

Note: If the item to remove does not exist, discard() will NOT raise an error.
You can also use the pop(), method to remove an item, but this method will remove the last item. Remember that sets are
unordered, so you will not know what item that gets removed.
The return value of the pop() method is the removed item.
Example
Remove the last item by using the pop() method:
thisset = {"apple", "banana", "cherry"}
x = [Link]()
print(x)
print(thisset)

Note: Sets are unordered, so when using the pop() method, you will not know which item that gets removed.
Example
The clear() method empties the set:
thisset = {"apple", "banana", "cherry"}
[Link]()
print(thisset)

Example
The del keyword will delete the set completely:
thisset = {"apple", "banana", "cherry"}
del thisset
print(thisset)

Join Two Sets


 There are several ways to join two or more sets in Python.

 You can use the union() method that returns a new set containing all items from both sets, or the update()method that
inserts all the items from one set into another:
Example
The union() method returns a new set with all items from both sets:
set1 = {"a", "b" , "c"}
set2 = {1, 2, 3}
set3 = [Link](set2)
print(set3)

Example
The update() method inserts the items in set2 into set1:
set1 = {"a", "b" , "c"}
set2 = {1, 2, 3}
[Link](set2)
print(set1)

Note: Both union() and update() will exclude any duplicate items.
There are other methods that joins two sets and keeps ONLY the duplicates, or NEVER the duplicates, check the full list of set
methods in the bottom of this page.
The set() Constructor

 It is also possible to use the set() constructor to make a set.


Example
Using the set() constructor to make a set:
thisset = set(("apple", "banana", "cherry")) # note the double round-brackets
print(thisset)

Set Methods
Python has a set of built-in methods that you can use on sets.

Method Description

add() Adds an element to the set

clear() Removes all the elements from the set

copy() Returns a copy of the set


difference() Returns a set containing the difference between two or more sets

difference_update() Removes the items in this set that are also included in another, specified set

discard() Remove the specified item

intersection() Returns a set, that is the intersection of two other sets

intersection_update() Removes the items in this set that are not present in other, specified set(s)

isdisjoint() Returns whether two sets have a intersection or not

issubset() Returns whether another set contains this set or not

issuperset() Returns whether this set contains another set or not

pop() Removes an element from the set

remove() Removes the specified element

symmetric_difference() Returns a set with the symmetric differences of two sets

symmetric_difference_update() inserts the symmetric differences from this set and another

union() Return a set containing the union of sets

update() Update the set with the union of this set and others

Python Dictionaries
Dictionary
 A dictionary is a collection which is unordered, changeable and indexed.
 In Python dictionaries are written with curly brackets, and they have keys and values.

Example
Create and print a dictionary:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964}

Accessing Items
 You can access the items of a dictionary by referring to its key name, inside square brackets:
Example

Get the value of the "model" key:


x = thisdict["model"]

Mustang

 There is also a method called get() that will give you the same result:

Example
Get the value of the "model" key:
x = [Link]("model")
Mustang

Change Values
 You can change the value of a specific item by referring to its key name:

Example
Change the "year" to 2018:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["year"] = 2018

print(thisdict)
{'brand': 'Ford', 'model': 'Mustang', 'year': 2018}

Loop Through a Dictionary


 You can loop through a dictionary by using a for loop.

 When looping through a dictionary, the return value are the keys of the dictionary, but there are methods to return
the values as well.

Example
Print all key names in the dictionary, one by one:
for x in thisdict:
print(x)

brand
model
year

Example
Print all values in the dictionary, one by one:
for x in thisdict:
print(thisdict[x])

Ford
Mustang
1964

Example
You can also use the values() method to return values of a dictionary:
for x in [Link]():
print(x)

Ford
Mustang
1964

Example
Loop through both keys and values, by using the items() method:
for x, y in [Link]():
print(x, y)

brand Ford
model Mustang
year 1964

Check if Key Exists


 To determine if a specified key is present in a dictionary use the in keyword:

Example
Check if "model" is present in the dictionary:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
if "model" in thisdict:
print("Yes, 'model' is one of the keys in the thisdict dictionary")

Dictionary Length
 To determine how many items (key-value pairs) a dictionary has, use the len() function.

Example
Print the number of items in the dictionary:
print(len(thisdict))

Adding Items
 Adding an item to the dictionary is done by using a new index key and assigning a value to it:

Example
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["color"] = "red"
print(thisdict)
{'model': 'Mustang', 'year': 1964, 'color': 'red', 'brand': 'Ford'} el': 'Mustang', 'y

Removing Items
There are several methods to remove items from a dictionary:

Example
The pop() method removes the item with the specified key name:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
[Link]("model")
print(thisdict)

Example
The popitem() method removes the last inserted item (in versions before 3.7, a random item is removed instead):
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
[Link]()
print(thisdict)

Example
The del keyword removes the item with the specified key name:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
del thisdict["model"]
print(thisdict)

Example
The del keyword can also delete the dictionary completely:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
del thisdict
print(thisdict) #this will cause an error because "thisdict" no longer exists.

Example
The clear() method empties the dictionary:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
[Link]()
print(thisdict)

Copy a Dictionary
You cannot copy a dictionary simply by typing dict2 = dict1, because: dict2 will only be a reference to dict1, and changes made
in dict1 will automatically also be made in dict2.
There are ways to make a copy, one way is to use the built-in Dictionary method copy().
Example
Make a copy of a dictionary with the copy() method:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
mydict = [Link]()
print(mydict)

Another way to make a copy is to use the built-in function dict().

Example
Make a copy of a dictionary with the dict() function:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
mydict = dict(thisdict)
print(mydict)

Nested Dictionaries
A dictionary can also contain many dictionaries, this is called nested dictionaries.

Example
Create a dictionary that contain three dictionaries:
myfamily = {
"child1" : {
"name" : "Emil",
"year" : 2004
},
"child2" : {
"name" : "Tobias",
"year" : 2007
},
"child3" : {
"name" : "Linus",
"year" : 2011
}
}

Or, if you want to nest three dictionaries that already exists as dictionaries:

Example
Create three dictionaries, then create one dictionary that will contain the other three dictionaries:
child1 = {
"name" : "Emil",
"year" : 2004
}
child2 = {
"name" : "Tobias",
"year" : 2007
}
child3 = {
"name" : "Linus",
"year" : 2011
}

myfamily = {
"child1" : child1,
"child2" : child2,
"child3" : child3
}

The dict() Constructor


It is also possible to use the dict() constructor to make a new dictionary:

Example
thisdict = dict(brand="Ford", model="Mustang", year=1964)
# note that keywords are not string literals
# note the use of equals rather than colon for the assignment
print(thisdict)

Dictionary Methods
Python has a set of built-in methods that you can use on dictionaries.

Method Description

clear() Removes all the elements from the dictionary

copy() Returns a copy of the dictionary

fromkeys() Returns a dictionary with the specified keys and value

get() Returns the value of the specified key

items() Returns a list containing a tuple for each key value pair

keys() Returns a list containing the dictionary's keys

pop() Removes the element with the specified key

popitem() Removes the last inserted key-value pair

setdefault() Returns the value of the specified key. If the key does not exist: insert the key, with the specified value

update() Updates the dictionary with the specified key-value pairs

values() Returns a list of all the values in the dictionary


UNIT-II
Python - Decision Making
Decision making is anticipation of conditions occurring while execution of the program and specifying actions taken according to
the conditions.
Decision structures evaluate multiple expressions which produce TRUE or FALSE as outcome. You need to determine which
action to take and which statements to execute if outcome is TRUE or FALSE otherwise.
Following is the general form of a typical decision making structure found in most of the programming languages –

Python programming language assumes any non-zero and non-null values as TRUE, and if it is either zero or null, then it is
assumed as FALSE value.

Python programming language provides following types of decision making statements. Click the following links to check their
detail.

[Link]. Statement & Description

1 if statements

An if statement consists of a boolean expression followed by one or more


statements.

2 if...else statements

An if statement can be followed by an optional else statement, which


executes when the boolean expression is FALSE.

3 nested if statements

You can use one if or else if statement inside another if or else


if statement(s).
Let us go through each decision making briefly −

Single Statement Suites


If the suite of an if clause consists only of a single line, it may go on the same line as the header statement.
Here is an example of a one-line if clause −

#!/usr/bin/python

var = 100
if ( var == 100 ) : print "Value of expression is 100"
print "Good bye!"

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


Value of expression is 100
Good bye!

Python IF Statement
It is similar to that of other languages. The if statement contains a logical expression using which data is compared and a decision
is made based on the result of the comparison.

Syntax
if expression:
statement(s)

If the boolean expression evaluates to TRUE, then the block of statement(s) inside the if statement is executed. If boolean
expression evaluates to FALSE, then the first set of code after the end of the if statement(s) is executed.

Flow Diagram
Example

#!/usr/bin/python

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

var2 = 0
if var2:
print "2 - Got a true expression value"
print var2
print "Good bye!"

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


1 - Got a true expression value
100
Good bye!

Python - Loops

In general, statements are executed sequentially: The first statement in a function is executed first, followed by the second, and
so on. There may be a situation when you need to execute a block of code several number of times.

Programming languages provide various control structures that allow for more complicated execution paths.

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.

[Link]. Loop Type & Description

1 while loop
Repeats a statement or group of statements while a given condition is TRUE. It tests the condition before executing the loop body.
2 for loop
Executes a sequence of statements multiple times and abbreviates the code that manages the loop variable.

3 nested loops
You can use one or more loop inside any another while, for or do..while loop.

Loop Control Statements


Loop control statements change execution from its normal sequence. When execution leaves a scope, all automatic objects that
were created in that scope are destroyed.

Python supports the following control statements. Click the following links to check their detail. Let us go through the
loop control statements briefly

[Link]. Control Statement & Description

1 break statement
Terminates the loop statement and transfers execution to the statement immediately following the loop.

2 continue statement
Causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating.

3 pass statement
The pass statement in Python is used when a statement is required syntactically but you do not want any command or code to
execute.

Python while Loop Statements

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

Here, statement(s) may be a single statement or a block of statements. The condition may be any expression, and true is any
non-zero value. The loop iterates while the condition is true.
When the condition becomes false, program control passes to the line immediately following the loop.

In Python, all the statements indented by the same number of character spaces after a programming construct are considered
to be part of a single block of code. Python uses indentation as its method of grouping statements.

Flow Diagram

Here, key point of the while loop is that the loop might not ever run. When the condition is tested and the result is false, the loop
body will be skipped and the first statement after the while loop will be executed.

Example

Live Demo

#!/usr/bin/pytho
n
count = 0
while (count < 9):

print 'The count is:', count


count = count + 1
print "Good bye!"

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


The count is: 0
The count is: 1
The count is: 2
The count is: 3
The count is: 4
The count is: 5
The count is: 6
The count is: 7 The
count is: 8 Good bye!

The block here, consisting of the print and increment statements, is executed repeatedly until count is no longer less than 9.
With each iteration, the current value of the index count is displayed and then increased by 1.

The Infinite Loop

A loop becomes infinite loop if a condition never becomes FALSE. You must use caution when using while loops because of the
possibility that this condition never resolves to a FALSE value. This results in a loop that never ends. Such a loop is called an
infinite loop.

An infinite loop might be useful in client/server programming where the server needs to run continuously so that client programs
can communicate with it as and when required.

#!/usr/bin/python

var = 1

while var == 1 : # This constructs an infinite loop


num = raw_input("Enter a number :")

print "You entered: ", num

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


print "Good bye!"
Enter a number :20
You entered: 20
Enter a number :29
You entered: 29
Enter a number :3
You entered: 3

Enter a number between :Traceback (most recent call last): File


"[Link]", line 5, in <module>

num = raw_input("Enter a number :")


KeyboardInterrupt
Above example goes in an infinite loop and you need to use CTRL+C to exit the program.
Using else Statement with While Loop
Python supports to have an else statement associated with a loop statement.
If the else statement is used with a while loop, the else statement is executed when the condition becomes false.
The following example illustrates the combination of an else statement with a while statement that prints a number as long as it is
less than 5, otherwise else statement gets executed.

Live Demo

#!/usr/bin/pytho
n
count = 0

while count < 5:

print count, " is less than 5"


count = count + 1

else:
When the above code is executed, it produces the following result −
print count, " is not less than 5"

0 is less than 5
1 is less than 5
2 is less than 5
3 is less than 5
4 is less than 5
5 is not less than 5

Single Statement Suites


Similar to the if statement syntax, if your while clause consists only of a single statement, it may be placed on the same line as
the while header.

Here is the syntax and example of a one-line while clause −

#!/usr/bin/python

flag = 1

while (flag): print 'Given flag is really true!' print


"Good bye!"
It is better not try above example because it goes into infinite loop and you need to press CTRL+C keys to exit.

Python for Loop Statements

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

Live Demo

#!/ur/bin/python

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

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

Current Letter : P Current


Letter : y Current Letter
: t Current Letter : h
Current Letter : o Current
Letter : n Current fruit :
banana Current fruit :
apple Current fruit :
mango Good bye!

Iterating by Sequence Index

An alternative way of iterating through each item is by index offset into the sequence itself. Following is a simple
example −
Live Demo

#!/usr/bin/pytho
n
fruits = ['banana', 'apple', 'mango']
for index in range(len(fruits)):

print 'Current fruit :', fruits[index]


print "Good bye!"

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

Current fruit : banana


Current fruit : apple
Current fruit : mango Good
bye!

Here, we took the assistance of the len() built-in function, which provides the total number of elements in the tuple as
well as the range() built-in function to give us the actual sequence to iterate over.

Using else Statement with For Loop


Python supports to have an else statement associated with a loop statement
If the else statement is used with a for loop, the else statement is executed when the loop has exhausted iterating
the list.

The following example illustrates the combination of an else statement with a for statement that searches for prime numbers f rom
10 through 20.

Live Demo

#!/usr/bin/pytho
n
for num in range(10,20): #to iterate between 10 to 20

for i in range(2,num): #to iterate on the factors of the number


if num%i == 0: #to determine the first factor

print '%d equals %d * %d'


j=num/i #to %calculate
(num,i,j)the second factor

break #to move to the next number, the #first FOR


else: # else part of the loop

print num, 'is a prime number'

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

10 equals 2 * 5
11 is a prime number
12 equals 2 * 6
13 is a prime number
14 equals 2 * 7
15 equals 3 * 5
16 equals 2 * 8
17 is a prime number
18 equals 2 * 9
19 is a prime number

Python nested loops

Python programming language allows to use one loop inside another loop. Following section shows few examples to illustrate
the concept.

Syntax

for iterating_var in sequence: for


iterating_var in sequence:

statements(s)
statements(s)

The syntax for a nested while loop statement in Python programming language is as follows −

while expression: while


expression:

statement(s)
statement(s)

A final note on loop nesting is that you can put any type of loop inside of any other type of loop. For example a for loop can be
inside a while loop or vice versa.

Example
The following program uses a nested for loop to find the prime numbers from 2 to 100 −
Live Demo
#!/usr/bin/pytho
n
i =2
while(i < 100):

j =2

while(j <= (i/j)):

if not(i%j): break j
=j +1

print
if "Good bye!": print i, " is prime"
(j > i/j)

i =When
i +the1 above code is executed, it produces following result −

2 is prime

3 is prime

5 is prime

7 is prime

11 is prime

13 is prime

17 is prime

19 is prime
Good bye!
23 is prime

29 is prime

31 is prime

37 is prime

41 is prime

43 is prime

47 is prime

53 is prime

59 is prime
61 is prime

67 is prime

71 is prime

73 is prime

79 is prime

83 is prime

89 is prime

97 is prime

Python Functions

Function

 A function is a block of code which only runs when it is called.


 You can pass data, known as parameters, into a function.
 A function can return data as a result.

Function Calls and Definition

The usual syntax for defining a Python function is as follows:

def <function_name>([<parameters>]):

<statement(s)>
The components of the definition are explained in the table below:

Component Meaning

def The keyword that informs Python that a function is being defined

<function_name> A valid Python identifier that names the function

<parameters> An optional, comma-separated list of parameters that may be passed to the


function

: Punctuation that denotes the end of the Python function header (the name and
parameter list)

<statement(s)> A block of valid Python statements

The final item, <statement(s)>, is called the body of the function. The body is a block of statements that will be executed
when the function is called. The body of a Python function is defined by indentation in accordance with the off-side rule. This is the
same as code blocks associated with a control structure, like an if or while statement.
The syntax for calling a Python function is as follows:
<function_name>([<arguments>])

<arguments> are the values passed into the function. They correspond to the <parameters> in the Python function
definition. You can define a function that doesn’t take any arguments, but the parentheses are still required. Both a function
definition and a function call must always include parentheses, even if they’re empty.
Creating a Function

 In Python a function is defined using the def keyword:

Example
def my_function():
print("Hello from a function")

Calling a Function

 To call a function, use the function name followed by parenthesis:

Example

def my_function():
print("Hello from a function")

my_function()

Result

Hello from a function


Arguments
 Information can be passed into functions as arguments.
 Arguments are specified after the function name, inside the parentheses. You can add as many arguments as you want,
just separate them with a comma.
 The following example has a function with one argument (fname). When the function is called, we pass along a first name,
which is used inside the function to print the full name:

Example

def my_function(fname):
print(fname + " Refsnes")
my_function("Emil")
my_function("Tobias")
my_function("Linus")
Result
Emil Refsnes
Tobias Refsnes
Linus Refsnes

Note: Arguments are often shortened to args in Python documentations.

Parameters or Arguments?

 The terms parameter and argument can be used for the same thing: information that are passed into a function.

From a function's perspective:

 A parameter is the variable listed inside the parentheses in the function definition.
 An argument is the value that is sent to the function when it is called.

Number of Arguments
 By default, a function must be called with the correct number of arguments. Meaning that if your function expects 2
arguments, you have to call the function with 2 arguments, not more, and not less.

Example

This function expects 2 arguments, and gets 2 arguments:

def my_function(fname, lname):


print(fname + " " + lname)
my_function("Emil", "Refsnes")
Result

Emil Refsnes

 If you try to call the function with 1 or 3 arguments, you will get an error:
Example

This function expects 2 arguments, but gets only 1:

def my_function(fname, lname):


print(fname + " " + lname)
my_function("Emil")
Result

Traceback (most recent call last):


File "demo_function_args_error.py", line 4, in <module>
my_function("Emil")
TypeError: my_function() missing 1 required positional argument: 'lname'

Arbitrary Arguments, *args

 If you do not know how many arguments that will be passed into your function, add a * before the parameter name in the
function definition.
 This way the function will receive a tuple of arguments, and can access the items accordingly:

Example

If the number of arguments is unknown, add a * before the parameter name:

def my_function(*kids):
print("The youngest child is " + kids[2])

my_function("Emil", "Tobias", "Linus")


Result

The youngest child is Linus

Note: Arbitrary Arguments are often shortened to *args in Python documentations.

Keyword Arguments

 You can also send arguments with the key = value syntax.
 This way the order of the arguments does not matter.

Example

def my_function(child3, child2, child1):


print("The youngest child is " + child3)
my_function(child1 = "Emil", child2 = "Tobias", child3 = "Linus")
Result

The youngest child is Linus


Note: The phrase Keyword Arguments are often shortened to kwargs in Python documentations.

Arbitrary Keyword Arguments, **kwargs

 If you do not know how many keyword arguments that will be passed into your function, add two asterisk: **before the
parameter name in the function definition.
 This way the function will receive a dictionary of arguments, and can access the items accordingly:

Example

If the number of keyword arguments is unknown, add a double ** before the parameter name:

def my_function(**kid):
print("His last name is " + kid["lname"])

my_function(fname = "Tobias", lname = "Refsnes")


Result

His last name is Refsnes

Note: Arbitrary Kword Arguments are often shortened to **kwargs in Python documentations.

Default Parameter Value

 The following example shows how to use a default parameter value.


 If we call the function without argument, it uses the default value:

Example

def my_function(country = "Norway"):


print("I am from " + country)
my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")
Result

I am from Sweden
I am from India
I am from Norway
I am from Brazil

Passing a List as an Argument

 You can send any data types of argument to a function (string, number, list, dictionary etc.), and it will be treated as the
same data type inside the function.
 E.g. if you send a List as an argument, it will still be a List when it reaches the function:

Example

def my_function(food):
for x in food:
print(x)
fruits = ["apple", "banana", "cherry"]
my_function(fruits)
Result

apple
banana
cherry

Return Values

To let a function return a value, use the return statement:


Example
def my_function(x):
return 5 * x
print(my_function(3))
print(my_function(5))
print(my_function(9))

Result

15
25
45
The pass Statement

 function definitions cannot be empty, but if you for some reason have a function definition with no content, put in
the pass statement to avoid getting an error.

Example

def myfunction():
pass
Result

Nothing will be displayed on the screen, because of no action in the function.

Arguments vs. Parameters

The first thing a programmer must be aware of is that parameters and arguments are clearly two different things although peop le
use them synonymously.
Parameters are the variables that are defined or used inside parentheses while defining a function, whereas arguments are the
value passed for these parameters while calling a function. Arguments are the values that are passed to the function at run -time so
that the function can do the designated task using these values.

Now that you know about Python function arguments and parameters, let’s have a look at a simple program to highlight more before
discussing the types of arguments that can be passed to a function.

#Defining a function first to return the value of parameter


def display(x): #x is the parameter
return x
#Calling the function and supplying arguments
print ("Hello " + display('David')) #'David' is the argument
In this example, we have defined a function with parameter ‘x’. Basically, this function will return whatever the value is passed as an
argument while calling.
Output
Hello David

Types of function arguments in Python

There are three types of Python function arguments using which we can call a function.
1. Default Arguments
2. Keyword Arguments
3. Variable-length Arguments

Python Default Arguments

 Sometimes we may want to use parameters in a function that takes default values in case the user doesn’t want to
provide a value for them.
 For this, we can use default arguments which assumes a default value if a value is not supplied as an argument while
calling the function. In parameters list, we can give default values to one or more parameters.
 An assignment operator ‘=’ is used to give a default value to an argument. Here is an example.
def sum(a=4, b=2): #2 is supplied as default argument
""" This function will print sum of two numbers
if the arguments are not supplied
it will add the default value """
print (a+b)

sum(1,2) #calling with arguments


sum( ) #calling without arguments
Output
3
6
In the program above, default arguments 2 and 4 are supplied to the function. First, the user has provided the arguments 1 and 2,
hence the function prints their sum which is 3. In the second call, the user has not provided the arguments. Thus the functio n takes
the default arguments and prints their sum.

Python Keyword Arguments

 In function, the values passed through arguments are assigned to parameters in order, by their position.

 With Keyword arguments, we can use the name of the parameter irrespective of its position while calling the function to
supply the values. All the keyword arguments must match one of the arguments accepted by the function.
Here is an example.
def print_name(name1, name2):
""" This function prints the name """
print (name1 + " and " + name2 + " are friends")

#calling the function


print_name(name2 = 'John',name1 = 'Gary')
Output
Gary and John are friends
Notice in above example, if we had supplied arguments as print_name('John','Gary'), the output would have been John
and Gary are friends as the values would have been assigned by arguments position.
But using keyword arguments by specifying the name of the argument itself, we don’t have to worry about their position.
This makes using function easier as we don’t need to worry about the order of arguments.

Variable-length Arguments

 Sometimes you may need more arguments to process function then you mentioned in the definition. If we don’t know in
advance about the arguments needed in function, we can use variable-length arguments also called arbitrary arguments.
 For this an asterisk (*) is placed before a parameter in function definition which can hold non-keyworded variable-length
arguments and a double asterisk (**) is placed before a parameter in function which can hold keyworded variable-length
arguments.
 If we use one asterisk (*) like *var, then all the positional arguments from that point till the end are collected as
a tuple called ‘var’ and if we use two asterisks (**) before a variable like **var, then all the positional arguments from that
point till the end are collected as a dictionary called ‘var’.
Here is an example.
def display(*name, **address):
for items in name:
print (items)
for items in [Link]():
print (items)

#Calling the function


display('john','Mary','Nina',John='LA',Mary='NY',Nina='DC')
Output
John
Mary
Nina
('John', 'LA')
('Mary', 'NY')
('Nina', 'DC')
As you can see in the example above, *name takes all the non-keyworded arguments John, Mary, and Ninawrapped into
a tuple, whereas **address takes all the keyworded arguments John='LA', Mary ='NY', and Nina='DC' wrapped into a dictionary.
In this particular example, the function took three arbitrary variables using one variable with either asterisk(*) or double
asterisk(**), but using variable length arguments we can take any number of arbitrary arguments.
Recursion

 Python also accepts function recursion, which means a defined function can call itself.
 Recursion is a common mathematical and programming concept. It means that a function calls itself. This has the benefit
of meaning that you can loop through data to reach a result.
 The developer should be very careful with recursion as it can be quite easy to slip into writing a function which never
terminates, or one that uses excess amounts of memory or processor power.
 However, when written correctly recursion can be a very efficient and mathematically-elegant approach to programming.
 In this example, tri_recursion() is a function that we have defined to call itself ("recurse"). We use the kvariable as the
data, which decrements (-1) every time we recurse. The recursion ends when the condition is not greater than 0 (i.e. when
it is 0).
 To a new developer it can take some time to work out how exactly this works, best way to find out is by testing and
modifying it.

Example

Recursion Example

def tri_recursion(k):
if(k > 0):
result = k + tri_recursion(k - 1)
print(result)
else:
result = 0
return result
print("\n\nRecursion Example Results")
tri_recursion(6)

Result
Recursion Example Results
1
3
6
10
15
21

Python Lambda

 A lambda function is a small anonymous function.

 A lambda function can take any number of arguments, but can only have one expression.

Syntax

lambda arguments : expression

 The expression is executed and the result is returned:

Example

A lambda function that adds 10 to the number passed in as an argument, and print the result:

x = lambda a : a + 10
print(x(5))

Result
15

 Lambda functions can take any number of arguments:

Example

A lambda function that multiplies argument a with argument b and print the result:

x = lambda a, b : a * b
print(x(5, 6))

Result
30

Example

 A lambda function that sums argument a, b, and c and print the result:
x = lambda a, b, c : a + b + c
print(x(5, 6, 2))

Result

13

Why Use Lambda Functions?

 The power of lambda is better shown when you use them as an anonymous function inside another function.
 Say you have a function definition that takes one argument, and that argument will be multiplied with an unknown number:

def myfunc(n):
return lambda a : a * n

Use that function definition to make a function that always doubles the number you send in:

Example

def myfunc(n):
return lambda a : a * n
mydoubler = myfunc(2)
print(mydoubler(11))

Result

22

Or, use the same function definition to make a function that always triples the number you send in:

Example

def myfunc(n):
return lambda a : a * n

mytripler = myfunc(3)

print(mytripler(11))

Result

33

Or, use the same function definition to make both functions, in the same program:

Example

def myfunc(n):
return lambda a : a * n

mydoubler = myfunc(2)
mytripler = myfunc(3)
print(mydoubler(11))
print(mytripler(11))

Result

22
33

Note: Use lambda functions when an anonymous function is required for a short period of time.

Generator Function

 It is fairly simple to create a generator in Python. It is defined like a normal function, but with a yield statement instead of
a return statement.
 If a function contains at least one yield statement (it may contain other yield or return statements), it becomes a generator
function. Both yield and return will return some value from a function.
 The difference is that while a return statement terminates a function entirely, yield statement pauses the function saving all its
states and later continues from there on successive calls.

Example-1

# A simple generator function


def my_gen():
n=1
print('This is printed first')
# Generator function contains yield statements
yield n

n += 1
print('This is printed second')
yield n

n += 1
print('This is printed at last')
yield n

# Using for loop


for item in my_gen():
print(item)

When you run the program, the output will be:

This is printed first


1
This is printed second
2
This is printed at last
3
Example-2

import random

def lottery():
# returns 6 numbers between 1 and 40
for i in range(6):
yield [Link](1, 40)

# returns a 7th number between 1 and 15


yield [Link](1,15)

for random_number in lottery():


print("And the next number is... %d!" %(random_number))
Result

And the next number is... 14!


And the next number is... 38!
And the next number is... 20!
And the next number is... 13!
And the next number is... 8!
And the next number is... 18!
And the next number is... 9!

Decorators

Python's decorators allow you to extend and modify the behavior of a callable (functions, methods, and classes) without
permanently modifying the callable itself. Any sufficiently generic functionality you can “tack on” to an existing class or f unction's
behavior makes a great use case for decoration.

Functions and methods are called callable as they can be called.

In fact, any object which implements the special __call__() method is termed callable. So, in the most basic sense, a decorator is a

callable that returns a callable.


Basically, a decorator takes in a function, adds some functionality and returns it.

def make_pretty(func):
def inner():
print("I got decorated")
func()
return inner

def ordinary():
print("I am ordinary")

When you run the following codes in shell,

>>> ordinary()
I am ordinary

>>> # let's decorate this ordinary function


>>> pretty = make_pretty(ordinary)
>>> pretty()
I got decorated
I am ordinary

In the example shown above, make_pretty() is a decorator. In the assignment step:

pretty = make_pretty(ordinary)

The function ordinary() got decorated and the returned function was given the name pretty.

We can see that the decorator function added some new functionality to the original function. This is similar to packing a gift. The

decorator acts as a wrapper. The nature of the object that got decorated (actual gift inside) does not alter. But now, it looks pretty

(since it got decorated).

Generally, we decorate a function and reassign it as,


ordinary = make_pretty(ordinary).

This is a common construct and for this reason, Python has a syntax to simplify this.

We can use the @ symbol along with the name of the decorator function and place it above the definition of the function to be

decorated. For example,

@make_pretty
def ordinary():
print("I am ordinary")

is equivalent to

def ordinary():
print("I am ordinary")
ordinary = make_pretty(ordinary)

This is just a syntactic sugar to implement decorators.

Python Namespace and Scope

What are names in Python?

 Before getting on to namespaces, first, let’s understand what Python means by a name.

 A name in Python is just a way to access a variable like in any other languages.
 However, Python is more flexible when it comes to the variable declaration.

 You can declare a variable by just assigning a name to it.


You can use names to reference values.

num = 5

str = 'Z'

seq = [0, 1, 1, 2, 3, 5]

You can even assign a name to a function.

def function():

print('It is a function.')

foo = function

foo()

You can also assign a name and then reuse it. Check the below example; it is alright for a name to point to different values.

test = -1
print("type <test> :=", type(test))
test = "Pointing to a string now"
print("type <test> :=", type(test))
test = [0, 1, 1, 2, 3, 5, 8]
print("type <test> :=", type(test))
And here is the output follows.

type <test> := <class 'int'>


type <test> := <class 'str'>
type <test> := <class 'list'>
So, you can see that one name is working perfectly fine to hold data of different types.

What are namespaces in Python?

A namespace is a simple system to control the names in a program. It ensures that names are unique and won’t lead
to any conflict.

Also, add to your knowledge that Python implements namespaces in the form of dictionaries. It maintains a name-to-
object mapping where names act as keys and the objects as values. Multiple namespaces may have the same name but
pointing to a different variable. Check out a few examples of namespaces for more clarity.

Local Namespace
This namespace covers the local names inside a function. Python creates this namespace for every function called in
a program. It remains active until the function returns.

Global Namespace
This namespace covers the names from various imported modules used in a project. Python creates this namespace
for every module included in your program. It’ll last until the program ends.

Built-in Namespace
This namespace covers the built-in functions and built-in exception names. Python creates it as the interpreter starts
and keeps it until you exit.

What is Scope in Python?

Namespaces make our programs immune from name conflicts. However, it doesn’t give us a free ride to use a variable name
anywhere we want. Python restricts names to be bound by specific rules known as a scope. The scope determines the parts of
the program where you could use that name without any prefix.

 Python outlines different scopes for locals, function, modules, and built-ins. Check out from the below list.
 A local scope, also known as the innermost scope, holds the list of all local names available in the current function.
 A scope for all the enclosing functions, it finds a name from the nearest enclosing scope and goes outwards.
 A module level scope, it takes care of all the global names from the current module.
 The outermost scope which manages the list of all the built-in names. It is the last place to search for a name that you
cited in the program.

Scope Resolution in Python – Examples

Scope resolution for a given name begins from the inner-most function and then goes higher and higher until the program finds
the related object. If the search ends without any outcome, then the program throws a NameError exception.

Let’s now see some examples which you can run inside any Python IDE or with IDLE.
a_var = 10
print("begin()-> ", dir())
def foo():
b_var = 11
print("inside foo()-> ", dir())

foo()

print("end()-> ", dir())

The output is as follows.

begin()-> ['__builtins__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'a_var']


inside foo()-> ['b_var']

end()-> ['__builtins__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'a_var', 'foo']

In this example, we used the dir() function. It lists all the names that are available in a Python program then.

In the first print() statement, the dir() only displays the list of names inside the current scope. While in the second print(), it finds
only one name, “b_var,” a local function variable.

Calling dir() after defining the foo() pushes it to the list of names available in the global namespace.

In the next example, we’ll see the list of names inside some nested functions. The code in this block continues from the prev ious
block.

def outer_foo():
outer_var = 3
def inner_foo():
inner_var = 5
print(dir(), ' - names in inner_foo')
outer_var = 7
inner_foo()
print(dir(), ' - names in outer_foo')

outer_foo()
The output is as follows.

['inner_var'] - names in inner_foo

['inner_foo', 'outer_var'] - names in outer_foo

The above example defines two variables and a function inside the scope of outer_foo(). Inside the inner_foo(), the dir() fun ction
only displays one name i.e. “inner_var”. It is alright as the “inner_var” is the only variable defined in there.

If you reuse a global name inside a local namespace, then Python creates a new local variable with the same name.

a_var = 5
b_var = 7

def outer_foo():
global a_var
a_var = 3
b_var = 9
def inner_foo():
global a_var
a_var = 4
b_var = 8
print('a_var inside inner_foo :', a_var)
print('b_var inside inner_foo :', b_var)
inner_foo()
print('a_var inside outer_foo :', a_var)
print('b_var inside outer_foo :', b_var)

outer_foo()
print('a_var outside all functions :', a_var)
print('b_var outside all functions :', b_var)
Here goes the output of the above code after execution.

a_var inside inner_foo : 4


b_var inside inner_foo : 8
a_var inside outer_foo : 4
b_var inside outer_foo : 9
a_var outside all functions : 4
b_var outside all functions : 7
We’ve declared a global variable as “a_var” inside both the outer_foo() and inner_foo() functions. However, we’ve assigned
different values in the same global variable. And that’s the reason the value of “a_var” is same (i.e., 4) on all occasions.
Whereas, each function is creating its own “b_var” variable inside the local scope. And the print() function is showing the v alues
of this variable as per its local context.

What is 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 you have some suspicious code that may raise an exception, you can defend your 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 st atements
that may throw different types of exceptions.

 You can also provide a generic except clause, which handles any exception.

 After the except clause(s), you 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 −
Live Demo

#!/usr/bin/python
try:
fh = open("testfile", "w")
[Link]("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"
[Link]()

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 −
Live Demo

#!/usr/bin/python
try:
fh = open("testfile", "r")
[Link]("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 Live Demo

#!/usr/bin/python
try:
fh = open("testfile", "w")
[Link]("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 −Live Demo

#!/usr/bin/python
try:
fh = open("testfile", "w")
try:
[Link]("This is my test file for exception handling!!")
finally:
print "Going to close the file"
[Link]()
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.

Argument of an Exception
An exception can have an argument, which is a value that gives additional information about the problem. The contents of
the argument vary by exception. You capture an exception's argument by supplying a variable in the except clause as
follows –

try:
You do your operations here;
......................
except ExceptionType, Argument:
You can print value of Argument here...

If you write the code to handle a single exception, you can have a variable follow the name of the exception in the except
statement. If you are trapping multiple exceptions, you can have a variable follow the tuple of the exception.
This variable receives the value of the exception mostly containing the cause of the exception. The variable can receive a
single value or multiple values in the form of a tuple. This tuple usually contains the error string, the error number, and an
error location.

Example
Following is an example for a single exception −Live Demo

#!/usr/bin/python
# Define a function here.
def temp_convert(var):
try:
return int(var)
except ValueError, Argument:
print "The argument does not contain numbers\n", Argument
# Call above function here.
temp_convert("xyz");

This produces the following result −


The argument does not contain numbers
invalid literal for int() with base 10: 'xyz'

Raising an Exceptions
You can raise exceptions in several ways by using the raise statement. The general syntax for the raise statement is as
follows.

Syntax
raise [Exception [, args [, traceback]]]
Here, Exception is the type of exception (for example, NameError) and argument is a value for the exception argument.
The argument is optional; if not supplied, the exception argument is None.
The final argument, traceback, is also optional (and rarely used in practice), and if present, is the traceback object used for
the exception.

Example
An exception can be a string, a class or an object. Most of the exceptions that the Python core raises are classes, with an
argument that is an instance of the class. Defining new exceptions is quite easy and can be done as follows −

def functionName( level ):


if level < 1:
raise "Invalid level!", level
# The code below to this would not be executed
# if we raise the exception

Note: In order to catch an exception, an "except" clause must refer to the same exception thrown either class object or
simple string. For example, to capture above exception, we must write the except clause as follows −
try:
Business Logic here...
except "Invalid level!":
Exception handling here...
else:
Rest of the code here...

User-Defined Exceptions
Python also allows you to create your own exceptions by deriving classes from the standard built-in exceptions.
Here is an example related to RuntimeError. Here, a class is created that is subclassed from RuntimeError. This is useful
when you need to display more specific information when an exception is caught.
In the try block, the user-defined exception is raised and caught in the except block. The variable e is used to create an
instance of the class Networkerror.

class Networkerror(RuntimeError):
def __init__(self, arg):
[Link] = arg

So once you defined above class, you can raise the exception as follows −

try:
raise Networkerror("Bad hostname")
except Networkerror,e:
print [Link]

Example-1

a = 12
s = "hello"
try:
print("inside try")
print(a + s) # will raise TypeError
print("Printed using original data types")
except TypeError: # will handle only TypeError
print("inside except")
print(str(a) + s)
print("Printed using type-casted data types")

Example-2

try:
if (3 + 4 - 5) > 0:
a=3
[Link]("hello") # throws AttributeError
else:
print("hello" + 4) # throws TypeError
except (AttributeError, TypeError) as e:
print("Error occurred:", e)

Example-3
try:
if (3 + 4 - 5) > 0:
a=3
[Link]("hello") # throws Attribute Error
else:
print("hello" + 4) # throws TypeError
except (AttributeError, TypeError) as e:
print("Error occurred:", e)
finally:
print("try except block successfully executed"

Example-4

try:
if (3 + 4 - 5) < 0:
a=3
print(a + 5) # simple addition
else:
print("hello" + "4") # string concatenation
except (AttributeError, TypeError) as e:
print("Error occurred:", e)
finally:
print("try except block successfully executed")

UNIT-III
Modules and Packages
What is a Module?

A python module can be defined as a python program file which contains a python code including python functions, class, or
variables. In other words, we can say that our python code file saved with the extension (.py) is treated as the module. We m ay
have a runnable code inside the python module.

Modules in Python provides us the flexibility to organize the code in a logical way.

To use the functionality of one module into another, we must have to import the specific module.

Example

In this example, we will create a module named as [Link] which contains a function func that contains a code to print some message
on the console.

Let's create the module named as [Link].

#displayMsg prints a message to the name being passed.


def displayMsg(name)
print("Hi "+name);

Here, we need to include this module into our main module to call the method displayMsg() defined in the module named file.
Loading the module in our python code

We need to load the module in our python code to use its functionality. Python provides two types of statements as defined below.

1. The import statement


2. The from-import statement

The import statement

The import statement is used to import all the functionality of one module into another. Here, we must notice that we can use the
functionality of any python source file by importing that file as the module into another python source file.

We can import multiple modules with a single import statement, but a module is loaded once regardless of the number of times, it
has been imported into our file.

The syntax to use the import statement is given below.

import module1,module2,........ module n

Hence, if we need to call the function displayMsg() defined in the file [Link], we have to import that file as a module into our module
as shown in the example below.

Example:

import file;
name = input("Enter the name?")
[Link](name)

Output:

Enter the name?John


Hi John

The from-import statement

Instead of importing the whole module into the namespace, python provides the flexibility to import only the specific attribu tes of a
module. This can be done by using from? import statement. The syntax to use the from-import statement is given below.

from < module-name> import <name 1>, <name 2>..,<name n>

Consider the following module named as calculation which contains three functions as summation, multiplication, and divide.

[Link]:

#place the code in the [Link]


def summation(a,b):
return a+b
def multiplication(a,b):
return a*b;
def divide(a,b):
return a/b;

[Link]:
from calculation import summation
#it will import only the summation() from [Link]
a = int(input("Enter the first number"))
b = int(input("Enter the second number"))
print("Sum = ",summation(a,b)) #we do not need to specify the module name while accessing summation()

Output:

Enter the first number10


Enter the second number20
Sum = 30

The from...import statement is always better to use if we know the attributes to be imported from the module in advance. It d oesn't
let our code to be heavier. We can also import all the attributes from a module by using *.

Consider the following syntax.

from <module> import *

Renaming a module

Python provides us the flexibility to import some module with a specific name so that we can use this name to use that module in our
python source file.

The syntax to rename a module is given below.

import <module-name> as <specific-name>

Example

#the module calculation of previous example is imported in this example as cal.


import calculation as cal;
a = int(input("Enter a?"));
b = int(input("Enter b?"));
print("Sum = ",[Link](a,b))

Output:

Enter a?10
Enter b?20
Sum = 30

Using dir() function

The dir() function returns a sorted list of names defined in the passed module. This list contains all the sub-modules, variables and
functions defined in this module.

Consider the following example.

Example
import json
List = dir(json)

print(List)

Output:

['JSONDecoder', 'JSONEncoder', '__all__', '__author__', '__builtins__', '__cached__', '__doc__',


'__file__', '__loader__', '__name__', '__package__', '__path__', '__spec__', '__version__',
'_default_decoder', '_default_encoder', 'decoder', 'dump', 'dumps', 'encoder', 'load', 'loads', 'scanner']

The reload() function

As we have already stated that, a module is loaded once regardless of the number of times it is imported into the python source file.
However, if you want to reload the already imported module to re-execute the top-level code, python provides us the reload()
function. The syntax to use the reload() function is given below.

reload(<module-name>)

for example, to reload the module calculation defined in the previous example, we must use the following line of code.

reload(calculation)

Python packages

The packages in python facilitate the developer with the application development environment by providing a hierarchical directory
structure where a package contains sub-packages, modules, and sub-modules. The packages are used to categorize the
application level code efficiently.

Let's create a package named Employees in your home directory. Consider the following steps.

1. Create a directory with name Employees on path /home.

2. Create a python source file with name [Link] on the path /home/Employees.

[Link]

def getITNames():
List = ["John", "David", "Nick", "Martin"]
return List;

3. Similarly, create one more python file with name [Link] and create a function getBPONames().

4. Now, the directory Employees which we have created in the first step contains two python modules. To make this directory a
package, we need to include one more file here, that is __init__.py which contains the import statements of the modules defin ed in
this directory.

__init__.py

from ITEmployees import getITNames


from BPOEmployees import getBPONames
5. Now, the directory Employees has become the package containing two python modules. Here we must notice that we must have
to create __init__.py inside a directory to convert this directory to a package.

6. To use the modules defined inside the package Employees, we must have to import this in our python source file. Let's create a
simple python source file at our home directory (/home) which uses the modules defined in this package.

[Link]

import Employees
print([Link]())

Output:

['John', 'David', 'Nick', 'Martin']

We can have sub-packages inside the packages. We can nest the packages up to any level depending upon the application
requirements.

OOPS IN PYTHON

Python has been an object-oriented language since it existed. Because of this, creating and using classes and objects are
downright easy. This chapter helps you become an expert in using Python's object-oriented programming support.

If you do not have any previous experience with object-oriented (OO) programming, you may want to consult an introductory
course on it or at least a tutorial of some sort so that you have a grasp of the basic concepts.

However, here is small introduction of Object-Oriented Programming (OOP) to bring you at speed −

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

 The class has a documentation string, which can be accessed via ClassName.__doc__.

 The class_suite consists of all the component statements defining class members, data attributes and functions.

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


[Link] = name
[Link] = salary
[Link] += 1

def displayCount(self):
print "Total Employee %d" % [Link]

def displayEmployee(self):
print "Name : ", [Link], ", Salary: ", [Link]

 The variable empCount is a class variable whose value is shared among all instances of a this class. This can be
accessed as [Link] from inside the class or outside the class.

 The first method __init__() is a special method, which is called class constructor or initialization method that Python calls
when you create a new instance of this class.

 You declare other class methods like normal functions with the exception that the first argument to each method is self.
Python adds the self argument to the list for you; you do not need to include it when you call the methods.

Creating Instance Objects

To create instances of a class, you 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

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

[Link]()
[Link]()
print "Total Employee %d" % [Link]
Now, putting all the concepts together −

Live Demo
#!/usr/bin/python

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

def __init__(self, name, salary):


[Link] = name
[Link] = salary
[Link] += 1

def displayCount(self):
print "Total Employee %d" % [Link]

def displayEmployee(self):
print "Name : ", [Link], ", Salary: ", [Link]

"This would create first object of Employee class"


emp1 = Employee("Zara", 2000)
"This would create second object of Employee class"
emp2 = Employee("Manni", 5000)
[Link]()
[Link]()
print "Total Employee %d" % [Link]

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 −
[Link] = 7 # Add an 'age' attribute.
[Link] = 8 # Modify 'age' attribute.
del [Link] # Delete 'age' attribute.
Instead of using the normal statements to access attributes, you can use the following functions −

 The getattr(obj, name[, default]) − to access the attribute of object.

 The hasattr(obj,name) − to check if an attribute exists or not.

 The setattr(obj,name,value) − to set an attribute. If attribute does not exist, then it would be created.

 The delattr(obj, name) − to delete an attribute.


hasattr(emp1, 'age') # Returns true if 'age' attribute exists
getattr(emp1, 'age') # Returns value of 'age' attribute
setattr(emp1, 'age', 8) # Set attribute 'age' at 8
delattr(empl, 'age') # Delete attribute 'age'

Built-In Class Attributes


Every Python class keeps following built-in attributes and they can be accessed using dot operator like any other
attribute −

 __dict__ − Dictionary containing the class's namespace.

 __doc__ − Class documentation string or none, if undefined.

 __name__ − Class name.

 __module__ − Module name in which the class is defined. This attribute is "__main__" in interactive mode.

 __bases__ − A possibly empty tuple containing the base classes, in the order of their occurrence in the
base class list.
For the above class let us try to access all these attributes –

Live Demo
#!/usr/bin/python

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

def __init__(self, name, salary):


[Link] = name
[Link] = salary
[Link] += 1

def displayCount(self):
print "Total Employee %d" % [Link]

def displayEmployee(self):
print "Name : ", [Link], ", Salary: ", [Link]

print "Employee.__doc__:", Employee.__doc__


print "Employee.__name__:", Employee.__name__
print "Employee.__module__:", Employee.__module__
print "Employee.__bases__:", Employee.__bases__
print "Employee.__dict__:", Employee.__dict__

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


Employee.__doc__: Common base class for all employees
Employee.__name__: Employee
Employee.__module__: __main__
Employee.__bases__: ()
Employee.__dict__: {'__module__': '__main__', 'displayCount':
<function displayCount at 0xb7c84994>, 'empCount': 2,
'displayEmployee': <function displayEmployee at 0xb7c8441c>,
'__doc__': 'Common base class for all employees',
'__init__': <function __init__ at 0xb7c846bc>}

Python Inheritance
Inheritance allows us to define a class that inherits all the methods and properties from another class.

Parent class is the class being inherited from, also called base class.

Child class is the class that inherits from another class, also called derived class.

Create a Parent Class


Any class can be a parent class, so the syntax is the same as creating any other class:

Example
Create a class named Person, with firstname and lastname properties, and a printname method:

class Person:
def __init__(self, fname, lname):
[Link] = fname
[Link] = lname

def printname(self):
print([Link], [Link])

#Use the Person class to create an object, and then execute the printname method:

x = Person("John", "Doe")
[Link]()
Try it Yourself »

Create a Child Class


To create a class that inherits the functionality from another class, send the parent class as a parameter when creating the
child class:

Example
Create a class named Student, which will inherit the properties and methods from the Person class:

class Student(Person):
pass

Note: Use the pass keyword when you do not want to add any other properties or methods to the class.

Now the Student class has the same properties and methods as the Person class.

Example
Use the Student class to create an object, and then execute the printname method:

x = Student("Mike", "Olsen")
[Link]()
Try it Yourself »

Add the __init__() Function


So far we have created a child class that inherits the properties and methods from its parent.

We want to add the __init__() function to the child class (instead of the pass keyword).

Note: The __init__() function is called automatically every time the class is being used to create a new object.

Example
Add the __init__() function to the Student class:

class Student(Person):
def __init__(self, fname, lname):
#add properties etc.

When you add the __init__() function, the child class will no longer inherit the parent's __init__() function.

Note: The child's __init__() function overrides the inheritance of the parent's __init__() function.

To keep the inheritance of the parent's __init__() function, add a call to the parent's __init__() function:

Example
class Student(Person):
def __init__(self, fname, lname):
Person.__init__(self, fname, lname)
Try it Yourself »

Now we have successfully added the __init__() function, and kept the inheritance of the parent class, and we are ready to
add functionality in the __init__() function.

Use the super() Function


Python also has a super() function that will make the child class inherit all the methods and properties from its parent:

Example
class Student(Person):
def __init__(self, fname, lname):
super().__init__(fname, lname)
Try it Yourself »

By using the super() function, you do not have to use the name of the parent element, it will automatically inherit the
methods and properties from its parent.

Add Properties
Example
Add a property called graduationyear to the Student class:

class Student(Person):
def __init__(self, fname, lname):
super().__init__(fname, lname)
[Link] = 2019
Try it Yourself »

In the example below, the year 2019 should be a variable, and passed into the Student class when creating student objects.
To do so, add another parameter in the __init__() function:

Example
Add a year parameter, and pass the correct year when creating objects:

class Student(Person):
def __init__(self, fname, lname, year):
super().__init__(fname, lname)
[Link] = year

x = Student("Mike", "Olsen", 2019)


Try it Yourself »

Add Methods
Example
Add a method called welcome to the Student class:
class Student(Person):
def __init__(self, fname, lname, year):
super().__init__(fname, lname)
[Link] = year

def welcome(self):
print("Welcome", [Link], [Link], "to the class of", [Link])
Try it Yourself »

If you add a method in the child class with the same name as a function in the parent class, the inheritance of the parent
method will be overridden.

Class Inheritance
Instead of starting from scratch, you 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 you 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

ExampleLive Demo

#!/usr/bin/python

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


[Link] = attr

def getAttr(self):
print "Parent attribute :", [Link]

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


[Link]() # child calls its method
[Link]() # calls parent's method
[Link](200) # again call parent's method
[Link]() # 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, you 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


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

Method Overriding in Python


Method overriding is an ability of any object-oriented programming language that allows a subclass or child class to
provide a specific implementation of a method that is already provided by one of its super-classes or parent classes.
When a method in a subclass has the same name, same parameters or signature and same return type(or sub-type)
as a method in its super-class, then the method in the subclass is said to override the method in the super-class.

The version of a method that is executed will be determined by the object that is used to invoke it. If an object of a
parent class is used to invoke the method, then the version in the parent class will be executed, but if an object of the
subclass is used to invoke the method, then the version in the child class will be executed. In other words, it is the
type of the object being referred to (not the type of the reference variable) that determines which version of an
overridden method will be executed.
Example:
# Python program to demonstrate
# method overriding
# Defining parent class
class Parent():

# Constructor
def __init__(self):
[Link] = "Inside Parent"

# Parent's show method


def show(self):
print([Link])

# Defining child class


class Child(Parent):

# Constructor
def __init__(self):
[Link] = "Inside Child"

# Child's show method


def show(self):
print([Link])

# Driver's code
obj1 = Parent()
obj2 = Child()

[Link]()
[Link]()
Output:
Inside Parent
Inside Child
You can always override your parent class methods. One reason for overriding parent's methods is because you
may want special or different functionality in your subclass.

Example

Live Demo
#!/usr/bin/python

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


[Link]() # child calls overridden method

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

Calling child method

METHOD TYPES
Generally, there are three types of methods in Python:
1. Instance Methods.
2. Class Methods
3. Static Methods

1. Instance Method
This is a very basic and easy method that we use regularly when we create classes in python. If we want to print an instance
variable or instance method we must create an object of that required class.
If we are using self as a function parameter or in front of a variable, that is nothing but the calling instance itself.
As we are working with instance variables we use self keyword.
Note: Instance variables are used with instance methods.
Look at the code below

# Instance Method Example in Python


class Student:

def __init__(self, a, b):


self.a = a
self.b = b

def avg(self):
return (self.a + self.b) / 2

s1 = Student(10, 20)
print( [Link]() )
Output:
15.0

In the above program, a and b are instance variables and these get initialized when we create an object for the Student class. If we
want to call avg() function which is an instance method, we must create an object for the class.
If we clearly look at the program, the self keyword is used so that we can easily say that those are instance variables and methods.

2. Class Method
classsmethod() function returns a class method as output for the given function.
Here is the syntax for it:
classmethod(function)

The classmethod() method takes only a function as an input parameter and converts that into a class method.
There are two ways to create class methods in python:
1. Using classmethod(function)
2. Using @classmethod annotation
A class method can be called either using the class (such as C.f()) or using an instance (such as C().f()). The instance is ignored
except for its class. If a class method is called from a derived class, the derived class object is passed as the implied first argument.
As we are working with ClassMethod we use the cls keyword. Class variables are used with class methods.
Look at the code below.

# Class Method Implementation in python


class Student:
name = 'Student'
def __init__(self, a, b):
self.a = a
self.b = b

@classmethod
def info(cls):
return [Link]
print([Link]())
Output:
Student

In the above example, name is a class variable. If we want to create a class method we must use @classmethod decorator
and cls as a parameter for that function.

3. Static Method
A static method can be called without an object for that class, using the class name directly. If you want to do something extra with a
class we use static methods.

For example, If you want to print factorial of a number then we don't need to use class variables or instance variables to pr int the
factorial of a number. We just simply pass a number to the static method that we have created and it returns the factorial.

Look at the below code

# Static Method Implementation in python


class Student:
name = 'Student'
def __init__(self, a, b):
self.a = a
self.b = b

@staticmethod
def info():
return "This is a student class"

print([Link]())
Output
This a student class

NAME MANGLING IN PYTHON


In Python there are no explicit access modifiers so you can’t mark a class member as public/private. Then the question is
how to restrict access to a variable or method outside the class, if required. Class member can be made private (Close to pri vate
actually) using a process called name mangling in Python. Python has a naming convention for attributes that should not be visible
outside of their class definition.

Python Name mangling example

class Person:
def __init__(self, name, age=0):
[Link] = name
self.__age = age

def display(self):
print([Link])
print(self.__age)

person = Person('John', 40)


#accessing using class method
print('Displaying values using class method')
[Link]()
#accessing directly from outside
print('Trying to access variables from outside the class ')
print([Link])
print(person.__age)
Output

Displaying values using class method


John
40
Traceback (most recent call last):
File "F:/NETJS/NetJS_2017/Python/Test/[Link]", line 21, in <module>
Trying to access variables from outside the class
John
print(person.__age)
AttributeError: 'Person' object has no attribute '__age'
As you can see variable __age (having two leading underscores) is not accessible from outside the class. Using a method with in
the class it can still be accessed.

Same way for a method with two leading underscores.

class Person:
def __init__(self, name, age=0):
[Link] = name
self.__age = age

def __displayAge(self):
print([Link])
print(self.__age)

person = Person('John', 40)


person.__displayAge()
Output

Traceback (most recent call last):


File "F:/NETJS/NetJS_2017/Python/Test/[Link]", line 15, in <module>
person.__displayAge()
AttributeError: 'Person' object has no attribute '__displayAge'
As you can see method is not accessible from outside the class.

UNIT-IV
Python - Files I/O
This chapter covers all the basic I/O functions available in Python. For more functions, please refer to standard Python
documentation.

Printing to the Screen

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

#!/usr/bin/python

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

#!/usr/bin/python

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

#!/usr/bin/python

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

Until now, you have been reading and writing to the standard input and output. Now, we will see how to use actual data files.

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

The open Function

Before you can read or write a file, you 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. A complete list of possible values is given below in the table. This is optional parameter and 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 −

[Link]. Modes & Description

1
r

Opens a file for reading only. The file pointer is placed at the beginning of the
file. This is the default mode.
2
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.

3
r+

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

4
rb+

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

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

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

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

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

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

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

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

12
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 you have one file object, you can get various information related to that file.

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

[Link]. Attribute & Description

1
[Link]

Returns true if file is closed, false otherwise.

2
[Link]

Returns access mode with which file was opened.

3
[Link]

Returns name of the file.

4
[Link]

Returns false if space explicitly required with print, true otherwise.

Example

#!/usr/bin/python

# Open a file
fo = open("[Link]", "wb")
print "Name of the file: ", [Link]
print "Closed or not : ", [Link]
print "Opening mode : ", [Link]
print "Softspace flag : ", [Link]

This produces the following result −


Name of the file: [Link]
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

[Link]()
Example

#!/usr/bin/python

# Open a file
fo = open("[Link]", "wb")
print "Name of the file: ", [Link]

# Close opend file


[Link]()

This produces the following result −

Name of the file: [Link]

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

[Link](string)

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

Example

#!/usr/bin/python

# Open a file
fo = open("[Link]", "wb")
[Link]( "Python is a great language.\nYeah its great!!\n")

# Close opend file


[Link]()

The above method would create [Link] 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

[Link]([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 [Link], which we created above.

#!/usr/bin/python

# Open a file
fo = open("[Link]", "r+")
str = [Link](10);
print "Read String is : ", str
# Close opend file
[Link]()

This produces the following result −

Read String is : Python is

File Positions

The tell() method tells you 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 [Link], which we created above.

#!/usr/bin/python

# Open a file
fo = open("[Link]", "r+")
str = [Link](10)
print "Read String is : ", str

# Check current position


position = [Link]()
print "Current file position : ", position

# Reposition pointer at the beginning once again


position = [Link](0, 0);
str = [Link](10)
print "Again read String is : ", str
# Close opend file
[Link]()

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

[Link](current_file_name, new_file_name)

Example

Following is the example to rename an existing file [Link] −

#!/usr/bin/python
import os

# Rename a file from [Link] to [Link]


[Link]( "[Link]", "[Link]" )

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
[Link](file_name)

Example

Following is the example to delete an existing file [Link] −

#!/usr/bin/python
import os

# Delete file [Link]


[Link]("[Link]")

Directories in Python

All files are contained within various directories, and Python has no problem handling these too. The os module has several
methods that help you create, remove, and change directories.

The mkdir() Method

You can use the mkdir() method of the os module to create directories in the current directory. You need to supply an argument to
this method which contains the name of the directory to be created.

Syntax

[Link]("newdir")

Example

Following is the example to create a directory test in the current directory −

#!/usr/bin/python
import os

# Create a directory "test"


[Link]("test")

The chdir() Method

You can use the chdir() method to change the current directory. The chdir() method takes an argument, which is the name of the
directory that you want to make the current directory.
Syntax

[Link]("newdir")

Example

Following is the example to go into "/home/newdir" directory −

#!/usr/bin/python
import os

# Changing a directory to "/home/newdir"


[Link]("/home/newdir")

The getcwd() Method

The getcwd() method displays the current working directory.

Syntax

[Link]()

Example

Following is the example to give current directory −

#!/usr/bin/python
import os

# This would give location of the current directory


[Link]()

The rmdir() Method

The rmdir() method deletes the directory, which is passed as an argument in the method.

Before removing a directory, all the contents in it should be removed.

Syntax

[Link]('dirname')

Example

Following is the example to remove "/tmp/test" directory. It is required to give fully qualified name of the directory, otherwise it
would search for that directory in the current directory.

#!/usr/bin/python
import os

# This would remove "/tmp/test" directory.


[Link]( "/tmp/test" )

File & Directory Related Methods

There are three important sources, which provide a wide range of utility methods to handle and manipulate files & directories on
Windows and Unix operating systems. They are as follows −

 File Object Methods: The file object provides functions to manipulate files.
 OS Object Methods: This provides methods to process files as well as directories.

UNIT-V
Python - MySQL Database Access
The Python standard for database interfaces is the Python DB-API. Most Python database interfaces adhere to this standard.

You can choose the right database for your application. Python Database API supports a wide range of database servers such as

 GadFly
 mSQL
 MySQL
 PostgreSQL
 Microsoft SQL Server 2000
 Informix
 Interbase
 Oracle
 Sybase
Here is the list of available Python database interfaces: Python Database Interfaces and APIs. You must download a separate DB
API module for each database you need to access. For example, if you need to access an Oracle database as well as a MySQL
database, you must download both the Oracle and the MySQL database modules.

The DB API provides a minimal standard for working with databases using Python structures and syntax wherever possible. This
API includes the following −

 Importing the API module.


 Acquiring a connection with the database.
 Issuing SQL statements and stored procedures.
 Closing the connection
We would learn all the concepts using MySQL, so let us talk about MySQLdb module.

Python OS File/Directory Methods

The os Python module provides a big range of useful methods to manipulate files and directories. Most of the useful methods are
listed here −

[Link]. Methods with Description

1 [Link](path, mode)

Use the real uid/gid to test for access to path.

2 [Link](path)

Change the current working directory to path


3 [Link](path, flags)

Set the flags of path to the numeric flags.

4 [Link](path, mode)

Change the mode of path to the numeric mode.

5 [Link](path, uid, gid)

Change the owner and group id of path to the numeric uid and gid.

6 [Link](path)

Change the root directory of the current process to path.

7 [Link](fd)

Close file descriptor fd.

8 [Link](fd_low, fd_high)

Close all file descriptors from fd_low (inclusive) to fd_high (exclusive), ignoring
errors.

9 [Link](fd)

Return a duplicate of file descriptor fd.

10 os.dup2(fd, fd2)

Duplicate file descriptor fd to fd2, closing the latter first if necessary.

11 [Link](fd)

Change the current working directory to the directory represented by the file
descriptor fd.

12 [Link](fd, mode)

Change the mode of the file given by fd to the numeric mode.

13 [Link](fd, uid, gid)

Change the owner and group id of the file given by fd to the numeric uid and
gid.

14 [Link](fd)

Force write of file with filedescriptor fd to disk.

15 [Link](fd[, mode[, bufsize]])

Return an open file object connected to the file descriptor fd.

16 [Link](fd, name)
Return system configuration information relevant to an open file. name
specifies the configuration value to retrieve.

17 [Link](fd)

Return status for file descriptor fd, like stat().

18 [Link](fd)

Return information about the filesystem containing the file associated with file
descriptor fd, like statvfs().

19 [Link](fd)

Force write of file with filedescriptor fd to disk.

20 [Link](fd, length)

Truncate the file corresponding to file descriptor fd, so that it is at most length
bytes in size.

21 [Link]()

Return a string representing the current working directory.

22 [Link]()

Return a Unicode object representing the current working directory.

23 [Link](fd)

Return True if the file descriptor fd is open and connected to a tty(-like) device,
else False.

24 [Link](path, flags)

Set the flags of path to the numeric flags, like chflags(), but do not follow
symbolic links.

25 [Link](path, mode)

Change the mode of path to the numeric mode.

26 [Link](path, uid, gid)

Change the owner and group id of path to the numeric uid and gid. This
function will not follow symbolic links.

27 [Link](src, dst)

Create a hard link pointing to src named dst.

28 [Link](path)

Return a list containing the names of the entries in the directory given by path.
29 [Link](fd, pos, how)

Set the current position of file descriptor fd to position pos, modified by how.

30 [Link](path)

Like stat(), but do not follow symbolic links.

31 [Link](device)

Extract the device major number from a raw device number.

32 [Link](major, minor)

Compose a raw device number from the major and minor device numbers.

33 [Link](path[, mode])

Recursive directory creation function.

34 [Link](device)

Extract the device minor number from a raw device number.

35 [Link](path[, mode])

Create a directory named path with numeric mode mode.

36 [Link](path[, mode])

Create a FIFO (a named pipe) named path with numeric mode mode. The
default mode is 0666 (octal).

37 [Link](filename[, mode=0600, device])

Create a filesystem node (file, device special file or named pipe) named
filename.

38 [Link](file, flags[, mode])

Open the file file and set various flags according to flags and possibly its mode
according to mode.

39 [Link]()

Open a new pseudo-terminal pair. Return a pair of file descriptors (master,


slave) for the pty and the tty, respectively.

40 [Link](path, name)

Return system configuration information relevant to a named file.

41 [Link]()

Create a pipe. Return a pair of file descriptors (r, w) usable for reading and
writing, respectively.
42 [Link](command[, mode[, bufsize]])

Open a pipe to or from command.

43 [Link](fd, n)

Read at most n bytes from file descriptor fd. Return a string containing the
bytes read. If the end of the file referred to by fd has been reached, an empty
string is returned.

44 [Link](path)

Return a string representing the path to which the symbolic link points.

45 [Link](path)

Remove the file path.

46 [Link](path)

Remove directories recursively.

47 [Link](src, dst)

Rename the file or directory src to dst.

48 [Link](old, new)

Recursive directory or file renaming function.

49 [Link](path)

Remove the directory path

50 [Link](path)

Perform a stat system call on the given path.

51 os.stat_float_times([newvalue])

Determine whether stat_result represents time stamps as float objects.

52 [Link](path)

Perform a statvfs system call on the given path.

53 [Link](src, dst)

Create a symbolic link pointing to src named dst.

54 [Link](fd)

Return the process group associated with the terminal given by fd (an open file
descriptor as returned by open()).

55 [Link](fd, pg)
Set the process group associated with the terminal given by fd (an open file
descriptor as returned by open()) to pg.

56 [Link]([dir[, prefix]])

Return a unique path name that is reasonable for creating a temporary file.

57 [Link]()

Return a new file object opened in update mode (w+b).

58 [Link]()

Return a unique path name that is reasonable for creating a temporary file.

59 [Link](fd)

Return a string which specifies the terminal device associated with file
descriptor fd. If fd is not associated with a terminal device, an exception is
raised.

60 [Link](path)

Remove the file path.

61 [Link](path, times)

Set the access and modified times of the file specified by path.

62 [Link](top[, topdown=True[, onerror=None[, followlinks=False]]])

Generate the file names in a directory tree by walking the tree either top-down
or bottom-up.

63 [Link](fd, str)

Write the string str to file descriptor fd. Return the number of bytes actually
written.

Python - Multithreaded Programming


Running several threads is similar to running several different programs concurrently, but with the following benefits −

 Multiple threads within a process share the same data space with the main thread and can therefore share information or
communicate with each other more easily than if they were separate processes.

 Threads sometimes called light-weight processes and they do not require much memory overhead; they are cheaper
than processes.

A thread has a beginning, an execution sequence, and a conclusion. It has an instruction pointer that keeps trac k of where within
its context it is currently running.

 It can be pre-empted (interrupted)

 It can temporarily be put on hold (also known as sleeping) while other threads are running - this is called yielding.

Starting a New Thread


To spawn another thread, you need to call following method available in thread module −

thread.start_new_thread ( function, args[, kwargs] )

This method call enables a fast and efficient way to create new threads in both Linux and Windows.

The method call returns immediately and the child thread starts and calls function with the passed list of args. When function
returns, the thread terminates.

Here, args is a tuple of arguments; use an empty tuple to call function without passing any arguments. kwargs is an optional
dictionary of keyword arguments.

Example

#!/usr/bin/python

import thread
import time

# Define a function for the thread


def print_time( threadName, delay):
count = 0
while count < 5:
[Link](delay)
count += 1
print "%s: %s" % ( threadName, [Link]([Link]()) )

# Create two threads as follows


try:
thread.start_new_thread( print_time, ("Thread-1", 2, ) )
thread.start_new_thread( print_time, ("Thread-2", 4, ) )
except:
print "Error: unable to start thread"

while 1:
pass

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


Thread-1: Thu Jan 22 15:42:17 2009
Thread-1: Thu Jan 22 15:42:19 2009
Thread-2: Thu Jan 22 15:42:19 2009
Thread-1: Thu Jan 22 15:42:21 2009
Thread-2: Thu Jan 22 15:42:23 2009
Thread-1: Thu Jan 22 15:42:23 2009
Thread-1: Thu Jan 22 15:42:25 2009
Thread-2: Thu Jan 22 15:42:27 2009
Thread-2: Thu Jan 22 15:42:31 2009
Thread-2: Thu Jan 22 15:42:35 2009
Although it is very effective for low-level threading, but the thread module is very limited compared to the newer threading module.

The Threading Module

The newer threading module included with Python 2.4 provides much more powerful, high-level support for threads than the thread
module discussed in the previous section.

The threading module exposes all the methods of the thread module and provides some additional methods −

 [Link]() − Returns the number of thread objects that are active.

 [Link]() − Returns the number of thread objects in the caller's thread control.

 [Link]() − Returns a list of all thread objects that are currently active.

In addition to the methods, the threading module has the Thread class that implements threading. The methods provided by
the Thread class are as follows −

 run() − The run() method is the entry point for a thread.

 start() − The start() method starts a thread by calling the run method.
 join([time]) − The join() waits for threads to terminate.

 isAlive() − The isAlive() method checks whether a thread is still executing.

 getName() − The getName() method returns the name of a thread.

 setName() − The setName() method sets the name of a thread.

Creating Thread Using Threading Module

To implement a new thread using the threading module, you have to do the following −

 Define a new subclass of the Thread class.

 Override the __init__(self [,args]) method to add additional arguments.

 Then, override the run(self [,args]) method to implement what the thread should do when started.

Once you have created the new Thread subclass, you can create an instance of it and then start a new thread by invoking
the start(), which in turn calls run() method.

You might also like