Python
Python
Contents-
1
2
Day 1 Introduction
What is Python?
It is used for:
Why Python?
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!")
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
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:
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
- Subtraction Subtracts right hand operand from left hand operand. a–b=-
10
% Modulus Divides left hand operand by right hand operand and b%a=
returns remainder 0
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
<> 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.
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
and Logical If both the operands are true then the condition (a and b)
AND 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.
12
1 if 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).
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
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.
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.
1 break statement
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
15
● long (long integers )
2
= 250).
● complex (complex numbers)
16
● Random numbers are used for games, simulations, testing, security, and
privacy applications. Python includes following functions that are
commonly used.
1 choice(seq)
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.
17
1 acos(x)
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
–
To access substrings, use the square brackets for slicing along with the index or indices to obtain
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
[] 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
20
given string give 1
One of Python's coolest features is the string format operator %. This operator is unique to string
Here is the list of complete set of symbols which can be used along with %
%c character
21
%o octal integer
One of Python's coolest features is the string format operator %. This operator is unique to string
Here is the list of complete set of symbols which can be used along with %
22
%c character
%o octal integer
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
To access values in lists, use the square brackets for slicing along with the index or indices to ob
Updating Lists
You can update single or multiple elements of lists by giving the slice on the left-hand side of th
24
list[2] = 2001;
print "New value available at index 2 : "
print list[2]
To remove a list element, you can use either the del statement if you know exactly which eleme
25
for x in [1, 2, 3]: print x, 123 Iteration
1 cmp(list1, list2)
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.
1 list.append(obj)
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 = ();
28
Updating Tuples
Tuples are immutable which means you cannot update or change the values of tuple elements. Y
In fact, tuples respond to all of the general sequence operations we used on strings in the prior c
29
Python Expression Results Description
Because tuples are sequences, indexing and slicing work the same way for tuples as they do for
30
L[1:] ['Spam', 'SPAM!'] Slicing fetches sections
1 cmp(tuple1, tuple2)
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.
To access dictionary elements, you can use the familiar square brackets along with the key to ob
Updating Dictionary
You can update a dictionary by adding a new entry or a key-value pair, modifying an existing en
32
del dict ; # delete entire dictionary
1 cmp(dict1, dict2)
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.
1 dict.clear()
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
All parameters (arguments) in the Python language are passed by reference. It means if you chan
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.
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
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
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.
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.
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.
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.
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
44
Python provides two built-in functions to read a line of text from standard input, which by defau
● raw_input
● input
This prompts you to enter any string and it would display same string on the screen. When I typ
This would produce the following result against the entered input
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.
Syntax
file object = open(file_name [, access_mode][, buffering])
Here are parameter details
● file_name
● access_mode
● buffering
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.
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
Syntax
fileObject.close()
Example
49
# Open a file
fo = open("foo.txt", "wb")
print "Name of the file: ", fo.name
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")
50
Python is a great language.
Yeah its great!!
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
52
Syntax
os.rename(current_file_name, new_file_name)
Example
Following is the example to rename an existing file test1.txt
import os
Syntax
os.remove(file_name)
Example
Following is the example to delete an existing file test2.txt
#!/usr/bin/python
import os
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.
Example
Following is the example to create a directory test
import os
Syntax
os.chdir("newdir")
Example
Following is the example to go into "/home/newdir" directory
import os
Syntax
os.getcwd()
54
Example
Following is the example to give current directory
import os
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
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 –
● Class variable
● Data member
● Function overloading
● Instance variable
● Inheritance
● Instance
● Instantiation
● Method
● Object
● Operator overloading
● __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
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
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