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

Python

The document outlines a comprehensive 40-day Python programming course covering topics such as introduction to Python, basic programming concepts, data types, control structures, and string handling. It emphasizes Python's versatility for web development, software development, and data manipulation, while also detailing fundamental programming constructs like variables, operators, loops, and functions. Each day is structured to progressively build knowledge, culminating in advanced topics like object-oriented programming and database interactions.

Uploaded by

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

Python

The document outlines a comprehensive 40-day Python programming course covering topics such as introduction to Python, basic programming concepts, data types, control structures, and string handling. It emphasizes Python's versatility for web development, software development, and data manipulation, while also detailing fundamental programming constructs like variables, operators, loops, and functions. Each day is structured to progressively build knowledge, culminating in advanced topics like object-oriented programming and database interactions.

Uploaded by

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

Day 1 Introduction

Day 2 Your First Programme


Day 3 Python Turtle
Variable a Basic
Day 4-9
Overview
Day 10-12 Operator Basic
Day 13-18 Python Statements
Day 19 Loop in python
Day 20-22 Play with numbers
Day 23-27 String Handling
Day 28 List
Day 29-30 Tuple
Play with Python
Day 31-33
Dictionary
Day 34 Function
Day 35-37 Exception handling
Day 38 File operations
Day 39 OOps concepts
Day 40 Working with database

Contents-

1
2
Day 1 Introduction

What is Python?

Python is a popular programming language. It was created by Guido van Rossum,


and released in 1991.

It is used for:

● web development (server-side),


● software development,
● mathematics,
● system scripting.

What can Python do?

● Python can be used on a server to create web applications.


● Python can be used alongside software to create workflows.
● Python can connect to database systems. It can also read and modify files.
● Python can be used to handle big data and perform complex mathematics.
● Python can be used for rapid prototyping, or for production-ready software
development.

Why Python?

● Python works on different platforms (Windows, Mac, Linux, Raspberry Pi,


etc).
● Python has a simple syntax similar to the English language.
● Python has syntax that allows developers to write programs with fewer lines
than some other programming languages.
● Python runs on an interpreter system, meaning that code can be executed as
soon as it is written. This means that prototyping can be very quick.
● Python can be treated in a procedural way, an object-oriented way or a
functional way.

3
Day 2- Your First Programme

Python Indentation
Indentation refers to the spaces at the beginning of a code line.
Where in other programming languages the indentation in code is for readability
only, the indentation in Python is very important.
� if 5 > 2:
print("Five is greater than two!")

� if 5 > 2:
print("Five is greater than two!")
if 5 > 2:
print("Five is greater than two!")

Comments
Python has commenting capability for the purpose of in-code documentation.
Comments start with a #, and Python will render the rest of the line as a comment:
#This is a comment.
print("Hello, World!")

Multi Line Comments


Python does not really have a syntax for multi line comments.
To add a multiline comment you could insert a # for each line:
#This is a comment
#written in
#more than just one line
print("Hello, World!")

Day 3- Turtle

4
Introduction
“Turtle” is a python feature like a drawing board, which lets you command a turtle
to draw all over it!
You can use functions like turtle.forward(...) and turtle.left(...) which can move the
turtle around.
Before you can use turtle, you have to import it. We recommend playing around
with it in the interactive interpreter first, as there is an extra bit of work required to
make it work from files. Just go to your terminal and type:
import turtle

turtle.forward(25)

The turtle.forward(...) function tells the turtle to move forward by the given
distance. turtle.left(...) takes a number of degrees which you want to rotate to the
left. There is also turtle.backward(...) and turtle.right(...), too

5
Day 4-9

Variable a Basic Overview

Variables are containers for storing data values.


Unlike other programming languages, Python has no command for declaring a
variable.
A variable is created the moment you first assign a value to it.
x=5
y = "John"
print(x)
print(y)

6
Variables do not need to be declared with any particular type and can even change
type after they have been set.
x = 4 # x is of type int
x = "Sally" # x is now of type str
print(x)

Variable Names
A variable can have a short name (like x and y) or a more descriptive name (age,
carname, total_volume). Rules for Python variables:

● A variable name must start with a letter or the underscore character


● A variable name cannot start with a number
● A variable name can only contain alpha-numeric characters and underscores
(A-z, 0-9, and _ )
● Variable names are case-sensitive (age, Age and AGE are three different
variables)

Output Variables
The Python print statement is often used to output variables.
To combine both text and a variable, Python uses the + character:
x = "awesome"
print("Python is " + x)

Global Variables
Variables that are created outside of a function (as in all of the examples above) are
known as global variables.
Global variables can be used by everyone, both inside of functions and outside.
x = "awesome"

def myfunc():
print("Python is " + x)
myfunc()

7
Day 10-12
OPERATOR BASIC-

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

Python Arithmetic Operators

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=


Multiplication 200

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

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

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

8
operators to the
power 20

// 9//2 = 4
and
9.0//2.0
= 4.0,
Floor Division - The division of operands where the result - quotient in wh
is the
11//3 = -
4, -
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

Operator Description Example

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


becomes true. is not
true.

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


becomes true. is true.

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

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

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

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

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

Python Assignment Operators


Assume variable a holds 10 and variable b holds 20, then

= Assigns values from right side c = a + b assigns value of


operands to left side operand a + b into c

+= Add It adds right operand to the left


c += a is equivalent to c =
AND operand and assign the result to left
c+a
operand

-= Subtract It subtracts right operand from the


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

*= Multiply It multiplies right operand with the


c *= a is equivalent to c =
AND left operand and assign the result to
c*a
left operand

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

%= Modulus It takes modulus using two operands c %= a is equivalent to c =


AND and assign the result to left operand c%a

**= Performs exponential (power)


c **= a is equivalent to c
Exponent calculation on operators and assign
= c ** a
AND value to the left operand

//= Floor It performs floor division on


c //= a is equivalent to c =
Division operators and assign value to the left
c // a
operand

Python Logical Operators


There are the following logical operators supported by the Python language.
Assume variable a holds 10 and variable b holds 20 then

Operator Description Example

and Logical If both the operands are true then the condition (a and b)
AND becomes true. is true.

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


condition becomes true. is true.

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

Day 13-18
Python statements
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 the outcome is TRUE or FALSE otherwise.

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.

Sr.No. Statement & Description

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

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.
var = 100
if ( var == 100 ) : print "Value of expression is 100"
print "Good bye!"

Day 19
Loops in python
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 fo

13
Sr.No. 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

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

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

Day 20-22
Play with 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

Python supports four different numerical types


● int (signed integers)

15
● long (long integers )

● float (floating point real values)

2
= 250).
● complex (complex numbers)

● 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, you 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

● Random Number Functions

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

Sr.No. 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 the following functions that perform trigonometric
calculations.

Sr.No. Function & Description

17
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

18
Sr.No. Constants & Description

1 pi
The mathematical constant pi.

2 e
The mathematical constant e.

Day 23-27
String Handling

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

var1 = 'Hello World!'


var2 = "Python Programming"

Accessing Values in Strings


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

To access substrings, use the square brackets for slicing along with the index or indices to obtain

var1 = 'Hello World!'


var2 = "Python Programming"

print "var1[0]: ", var1[0]

19
print "var2[1:5]: ", var2[1:5]

Updating Strings

You can "update" an existing string by (re)assigning a variable to another string. The new value

var1 = 'Hello World!'


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

String Special Operators


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

Operator Description Example

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


operator give
HelloPython

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


multiple copies of the same string give -
HelloHello

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

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

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

20
given string give 1

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


exist in the given string will give 1

String Formatting Operator

One of Python's coolest features is the string format operator %. This operator is unique to string

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


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

My name is Zara and my weight is 21 kg!

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

Format Symbol Conversion

%c character

%s string conversion via str() prior to formatting

%i signed decimal integer

%d signed decimal integer

%u unsigned decimal integer

21
%o octal integer

%x hexadecimal integer (lowercase letters)

%X hexadecimal integer (UPPERcase letters)

%e exponential notation (with lowercase 'e')

%E exponential notation (with UPPERcase 'E')

%f floating point real number

String Formatting Operator

One of Python's coolest features is the string format operator %. This operator is unique to string

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

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

My name is Zara and my weight is 21 kg!

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

Format Symbol Conversion

22
%c character

%s string conversion via str() prior to formatting

%i signed decimal integer

%d signed decimal integer

%u unsigned decimal integer

%o octal integer

%x hexadecimal integer (lowercase letters)

%X hexadecimal integer (UPPERcase letters)

%e exponential notation (with lowercase 'e')

%E exponential notation (with UPPERcase 'E')

%f floating point real number

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

23
Python has six built-in types of sequences, but the most common ones are lists and
tuples, which we would see in this tutorial.
There are certain things you can do with all sequence types. These operations
include indexing, slicing, adding, multiplying, and checking for membership. In
addition, Python has built-in functions for finding the length of a sequence and for
finding its largest and smallest elements.
The list is a most versatile datatype available in Python which can be written as a
list of comma-separated values (items) between square brackets. Important thing
about a list is that items in a list need not be of the same type.

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

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


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

Accessing Values in Lists

To access values in lists, use the square brackets for slicing along with the index or indices to ob

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


list2 = [1, 2, 3, 4, 5, 6, 7 ];
print "list1[0]: ", list1[0]
print "list2[1:5]: ", list2[1:5]

Updating Lists

You can update single or multiple elements of lists by giving the slice on the left-hand side of th

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


print "Value available at index 2 : "
print list[2]

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

Delete List Elements

To remove a list element, you can use either the del statement if you know exactly which eleme

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


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

Basic List Operations


Lists respond to the + and * operators much like strings; they mean concatenation
and repetition here too, except that the result is a new list, not a string.
In fact, lists respond to all of the general sequence operations we used on strings
in the prior chapter.

Python Expression Results Description

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

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

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

3 in [1, 2, 3] True Membership

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

Indexing, Slicing, and Matrixes


Because lists are sequences, indexing and slicing work the same way for lists as
they do for strings.
Assuming following input
L = ['spam', 'Spam', 'SPAM!']
Python Expression Results Description

L[2] SPAM! Offsets start at zero

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

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

Built-in List Functions & Methods


Python includes the following list functions

Sr.No. Function with Description

1 cmp(list1, list2)

Compares elements of both lists.

2 len(list)
Gives the total length of the list.

3 max(list)

26
Returns item from the list with max value.

4 min(list)
Returns item from the list with min value.

5 list(seq)
Converts a tuple into list.

Python includes following list methods

Sr.No. Methods with Description

1 list.append(obj)

Appends object obj to list

2 list.count(obj)
Returns count of how many times obj occurs in list

3 list.extend(seq)
Appends the contents of seq to list

4 list.index(obj)
Returns the lowest index in list that obj appears

5 list.insert(index, obj)
Inserts object obj into list at offset index

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

7 list.remove(obj)

27
Removes object obj from list

8 list.reverse()
Reverses objects of list in place

9 list.sort([func])
Sorts objects of list, use compare func if given

Day 29-30
Tuples
A tuple is a sequence of immutable Python objects. Tuples are sequences, just like
lists. The differences between tuples and lists are, the tuples cannot be changed
unlike lists and tuples use parentheses, whereas lists use square brackets.

Creating a tuple is as simple as putting different comma-separated values. Optionally you can pu

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


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

The empty tuple is written as two parentheses containing nothing

tup1 = ();

Accessing Values in Tuples


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

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


tup2 = (1, 2, 3, 4, 5, 6, 7 );
print "tup1[0]: ", tup1[0];
print "tup2[1:5]: ", tup2[1:5];

28
Updating Tuples

Tuples are immutable which means you cannot update or change the values of tuple elements. Y

tup1 = (12, 34.56);


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

# Following action is not valid for tuples


# tup1[0] = 100;

# So let's create a new tuple as follows


tup3 = tup1 + tup2;
print tup3;

Delete Tuple Elements


Removing individual tuple elements is not possible. There is, of course, nothing
wrong with putting together another tuple with the undesired elements discarded.
To explicitly remove an entire tuple, just use the del

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


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

Basic Tuples Operations


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

In fact, tuples respond to all of the general sequence operations we used on strings in the prior c

29
Python Expression Results Description

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

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

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

3 in (1, 2, 3) True Membership

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

Indexing, Slicing, and Matrixes

Because tuples are sequences, indexing and slicing work the same way for tuples as they do for

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

Python Expression Results Description

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

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

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

Built-in Tuple Functions


Python includes the following tuple functions

Sr.No. Function with Description

1 cmp(tuple1, tuple2)

Compares elements of both tuples.

2 len(tuple)
Gives the total length of the tuple.

3 max(tuple)
Returns item from the tuple with max value.

4 min(tuple)
Returns item from the tuple with min value.

5 tuple(seq)
Converts a list into tuple.

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

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

Accessing Values in Dictionary

To access dictionary elements, you can use the familiar square brackets along with the key to ob

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


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

Updating Dictionary

You can update a dictionary by adding a new entry or a key-value pair, modifying an existing en

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


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

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


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

Delete Dictionary Elements


You can either remove individual dictionary elements or clear the entire contents
of a dictionary. You can also delete entire dictionary in a single operation.
To explicitly remove an entire dictionary, just use the del

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


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

32
del dict ; # delete entire dictionary

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


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

Built-in Dictionary Functions & Methods


Python includes the following dictionary functions

Sr.No. Function with Description

1 cmp(dict1, dict2)

Compares elements of both dict.

2 len(dict)
Gives the total length of the dictionary. This would be equal to the
number of items in the dictionary.

3 str(dict)
Produces a printable string representation of a dictionary

4 type(variable)
Returns the type of the passed variable. If passed variable is dictionary,
then it would return a dictionary type.

Python includes following dictionary methods

Sr.No. Methods with Description

1 dict.clear()

Removes all elements of dictionary dict

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

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

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

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

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

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

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

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

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

Day -34
Function
A function is a block of organized, reusable code that is used to perform a single,
related action. Functions provide better modularity for your application and a high
degree of code reusing.
34
As you already know, Python gives you many built-in functions like print(), etc.
but you can also create your own functions. These functions are called user-
defined functions.

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

Syntax
def functionname( parameters ):
"function_docstring"
function_suite
return [expression]
By default, parameters have a positional behavior and you need to inform them in
the same order that they were defined.

Example
The following function takes a string as input parameter and prints it on standard
screen.
def printme( str ):
"This prints a passed string into this function"
print str

35
return

Calling a Function
Defining a function only gives it a name, specifies the parameters that are to be
included in the function and structures the blocks of code.
Once the basic structure of a function is finalized, you can execute it by calling it
from another function or directly from the Python prompt. Following is the
example to call printme() function

Pass by reference vs value

All parameters (arguments) in the Python language are passed by reference. It means if you chan

# Function definition is here


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

# Now you can call changeme function


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

Function Arguments

You can call a function by using the following types of formal arguments

● Required arguments

36
● Keyword arguments
● Default arguments
● Variable-length arguments

Required arguments
Required arguments are the arguments passed to a function in correct positional
order. Here, the number of arguments in the function call should match exactly
with the function definition.

Keyword arguments
Keyword arguments are related to the function calls. When you use keyword
arguments in a function call, the caller identifies the arguments by the parameter
name.

Default arguments
A default argument is an argument that assumes a default value if a value is not
provided in the function call for that argument.

Variable-length arguments
You may need to process a function for more arguments than you specified while
defining the function. These arguments are called variable-length arguments and
are not named in the function definition, unlike required and default arguments.

The Anonymous Functions


These functions are called anonymous because they are not declared in the
standard manner by using the def keyword. You can use the lambda keyword to
create small anonymous functions.
● Lambda forms can take any number of arguments but return just one value
in the form of an expression. They cannot contain commands or multiple
expressions.
● An anonymous function cannot be a direct call to print because lambda
requires an expression
● Lambda functions have their own local namespace and cannot access
variables other than those in their parameter list and those in the global
namespace.

37
● Although it appears that lambda's are a one-line version of a function, they
are not equivalent to inline statements in C or C++, whose purpose is by
passing function stack allocation during invocation for performance
reasons.

Syntax
The syntax of lambda

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

# Function definition is here


sum = lambda arg1, arg2: arg1 + arg2;

# Now you can call sum as a function


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

The return Statement


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

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

38
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.
List of Standard Exceptions

Sr.No. Exception Name & Description

1 Exception
Base class for all exceptions

2 StopIteration
Raised when the next() method of an iterator does not point to any
object.

3 SystemExit
Raised by the sys.exit() function.

4 StandardError
Base class for all built-in exceptions except StopIteration and
SystemExit.

5 ArithmeticError
Base class for all errors that occur for numeric calculation.

6 OverflowError
Raised when a calculation exceeds maximum limit for a numeric type.

7 FloatingPointError
Raised when a floating point calculation fails.

39
8 ZeroDivisionError
Raised when division or modulo by zero takes place for all numeric
types.

9 AssertionError
Raised in case of failure of the Assert statement.

10 AttributeError
Raised in case of failure of attribute reference or assignment.

11 EOFError
Raised when there is no input from either the raw_input() or input()
function and the end of file is reached.

12 ImportError
Raised when an import statement fails.

13 KeyboardInterrupt
Raised when the user interrupts program execution, usually by pressing
Ctrl+c.

14 LookupError
Base class for all lookup errors.

15 IndexError
Raised when an index is not found in a sequence.

16 KeyError
Raised when the specified key is not found in the dictionary.

40
17 NameError
Raised when an identifier is not found in the local or global namespace.

18 UnboundLocalError
Raised when trying to access a local variable in a function or method
but no value has been assigned to it.

19 EnvironmentError
Base class for all exceptions that occur outside the Python environment.

20 IOError
Raised when an input/ output operation fails, such as the print statement
or the open() function when trying to open a file that does not exist.

21 IOError
Raised for operating system-related errors.

22 SyntaxError
Raised when there is an error in Python syntax.

23 IndentationError
Raised when indentation is not specified properly.

24 SystemError
Raised when the interpreter finds an internal problem, but when this
error is encountered the Python interpreter does not exit.

25 SystemExit
Raised when Python interpreter is quit by using the sys.exit() function.

41
If not handled in the code, causes the interpreter to exit.

26 TypeError
Raised when an operation or function is attempted that is invalid for the
specified data type.

27 ValueError
Raised when the built-in function for a data type has the valid type of
arguments, but the arguments have invalid values specified.

28 RuntimeError
Raised when a generated error does not fall into any category.

29 NotImplementedError
Raised when an abstract method that needs to be implemented in an
inherited class is not actually implemented.

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

42
● A single try statement can have multiple except statements. This is useful
when the try block contains statements that may throw different types of
exceptions.
● 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.

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

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

The try-finally Clause


You can use a finally: block along with a try:

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.
Day- 38
File operations

Printing to the Screen


The simplest way to produce output is using the print

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

Reading Keyboard Input

44
Python provides two built-in functions to read a line of text from standard input, which by defau

● raw_input
● input

The raw_input Function


The raw_input([prompt]) function reads one line from standard input and returns
it as a string (removing the trailing newline).
str = raw_input("Enter your input: ")
print "Received input is : ", str

This prompts you to enter any string and it would display same string on the screen. When I typ

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

45
Python provides basic functions and methods necessary to manipulate files by
default. You can do most of the file manipulation 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

● access_mode

● buffering

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

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

46
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

47
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

Sr.No. Attribute & Description

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

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

48
3 file.name
Returns name of the file.

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

Example

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

The close() Method


The close() method of a file object flushes any unwritten information and closes
the file object, after which no more writing can be done.
Python automatically closes a file when the reference object of a file is reassigned
to another file. It is a good practice to use the close() method to close a file.

Syntax
fileObject.close()

Example

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

# Close opend file


fo.close()
This produces the following result
Name of the file: foo.txt

Reading and Writing Files


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

The write() Method


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

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

Syntax
fileObject.write(string)
Here, passed parameter is the content to be written into the opened file.

Example

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

# Close opend file


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

50
Python is a great language.
Yeah its great!!

The read() Method


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

Syntax
fileObject.read([count])
Here, passed parameter is the number of bytes to be read from the opened file.
This method starts reading from the beginning of the file and if count is missing,
then it tries to read as much as possible, maybe until the end of file.

Example
Let's take a file foo.txt, which we created above.
# Open a file
fo = open("foo.txt", "r+")
str = fo.read(10);
print "Read String is : ", str
# Close opend file
fo.close()
This produces the following result
Read String is : Python is

File Positions
The tell() method tells 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.

51
Example
Let us take a file foo.txt, which we created above.
# Open a file
fo = open("foo.txt", "r+")
str = fo.read(10)
print "Read String is : ", str

# Check current position


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

# Reposition pointer at the beginning once again


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

Renaming and Deleting Files


Python os module provides methods that help you perform file-processing
operations, such as renaming and deleting files.
To use this module you need to import it first and then you can call any related
functions.

The rename() Method


The rename() method takes two arguments, the current filename and the new
filename.

52
Syntax
os.rename(current_file_name, new_file_name)

Example
Following is the example to rename an existing file test1.txt
import os

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


os.rename( "test1.txt", "test2.txt" )

The remove() Method


You can use the remove() method to delete files by supplying the name of the file
to be deleted as the argument.

Syntax
os.remove(file_name)

Example
Following is the example to delete an existing file test2.txt
#!/usr/bin/python
import os

# Delete file test2.txt


os.remove("text2.txt")

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.
53
Syntax
os.mkdir("newdir")

Example
Following is the example to create a directory test

import os

# Create a directory "test"


os.mkdir("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
os.chdir("newdir")

Example
Following is the example to go into "/home/newdir" directory
import os

# Changing a directory to "/home/newdir"


os.chdir("/home/newdir")

The getcwd() Method


The getcwd() method displays the current working directory.

Syntax
os.getcwd()

54
Example
Following is the example to give current directory
import os

# This would give location of the current directory


os.getcwd()

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
os.rmdir('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.
import os

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


os.rmdir( "/tmp/test" )

Day- 39
OOps concepts
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.

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

Overview of OOP Terminology


● Class

● Class variable

● Data member

● Function overloading

● Instance variable

● Inheritance

● Instance

● Instantiation
● Method
● Object

● Operator overloading

Built-In Class Attributes


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

● __dict__
● __doc__
● __name__
● __module__

56
● __bases__

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.

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

class Parent: # define parent class


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

class Child(Parent): # define child class


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

c = Child() # instance of child


c.myMethod() # child calls overridden method

Base Overloading Methods


Following table lists some generic functionality that you can override in your own classes

Sr.No. Method, Description & Sample Call

1
__init__ ( self [,args...] )

57
Constructor (with any optional arguments)
Sample Call : obj = className(args)

2
__del__( self )
Destructor, deletes an object
Sample Call : del obj

3
__repr__( self )
Evaluable string representation
Sample Call : repr(obj)

4
__str__( self )
Printable string representation
Sample Call : str(obj)

5
__cmp__ ( self, x )
Object comparison
Sample Call : cmp(obj, x)

Day 40
Working with database
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

● GadFly
● mSQL
● MySQL
● PostgreSQL
● Microsoft SQL Server 2000
● Informix
● Interbase
● Oracle

58
● Sybase

The DB API provides a minimal standard for working with databases using Python structures and syntax where

● Importing the API module.


● Acquiring a connection with the database.
● Issuing SQL statements and stored procedures.
● Closing the connection

Performing Transactions

Transactions are a mechanism that ensures data consistency. Transactions have the following four properties

● Atomicity
● Consistency

● Isolation

● Durability

COMMIT Operation
Commit is the operation, which gives a green signal to database to finalize the
changes, and after this operation, no change can be reverted back.
Here is a simple example to call commit method.
db.commit()

Disconnecting Database
To disconnect Database connection, use close() method.
db.close()
If the connection to a database is closed by the user with the close() method, any
outstanding transactions are rolled back by the DB.

59

You might also like