Python Final Book
Python Final Book
in Python programming
Overview
Python is a popular programming language. It was created by Guido van Rossum, and
released in 1991.
It is used for:
• It provides very high-level dynamic data types and supports dynamic type
checking.
• It can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java.
PAGE 1
www.icit.in Python programming
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-orientated way or a
functional way.
• VxWorks
• Psion
• Python has also been ported to the Java and .NET virtual machines
Installation & Setup Guide
Step 2) Once the download is complete, run the exe for install PyCharm. The setup wizard should have
started. Click “Next”.
Step 3) On the next screen, Change the installation path if required. Click “Next”.
PAGE 3
www.icit.in Python programming
Step 4) On the next screen, you can create a desktop shortcut if you want and click on “Next”.
tep 5) Choose the start menu folder. Keep selected JetBrains and click on “Install”.
PAGE 4
www.icit.in Python programming
Step 7) Once installation finished, you should receive a message screen that PyCharm is installed. If you want
to go ahead and run it, click the “Run PyCharm Community Edition” box first and click “Finish”.
PAGE 5
www.icit.in Python programming
Step 8) After you click on "Finish," the Following screen will appear.
PAGE 6
www.icit.in Python programming
Python Syntax
As we learned in the previous page, Python syntax can be executed by writing directly in
the Command Line:
Or by creating a python file on the server, using the .py file extension, and running it in
the Command Line:
C:\Users\Your Name>python myfile.py
PythonVariables
• 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.
PAGE 7
www.icit.in Python programming
• Therefore, by assigning different data types to variables, you can store integers,
decimals or characters in these variables.
Creating Variables
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:
x =5
y = "John"
print(x)
print(y)
Output
PAGE 8
www.icit.in Python programming
x =4 # x is of type int
x = "Sally" # x is now of type str
print(x)
Output
Output Variables
The Python print statement is often used to output variables.
PAGE 9
www.icit.in Python programming
x = "awesome"
print ("Python is "+ x)
Output
Python Numbers
Int
Int, or integer, is a whole number, positive or negative, without decimals, of unlimited
length.
Program for display type of whole number, positive or negative, without decimals numbers
PAGE 10
www.icit.in Python programming
x =1
y = 35656222554887711
z = -3255522
print(type(x))
print(type(y))
print(type(z))
Output
Float
Float, or "floating point number" is a number, positive or negative, containing one or
more decimals.
Program for Display positive or negative, containing one or more decimals number.
PAGE 11
www.icit.in Python programming
x = 1.10
y = 1.0 z
= -35.59
print(type(x))
print(type(y))
print(type(z))
Output
Float can also be scientific numbers with an "e" to indicate the power of 10.
Program
x = 35e3 y
= 12E4 z =
-87.7e100
print(type(x
))
PAGE 12
www.icit.in Python programming
print(type(y
))
print(type(z
))
Output
Complex
Complex numbers are written with a "j" as the imaginary part:
Program
x = 3+5j
y = 5j
z = -5j
print(type(x))
print(type(y))
print(type(z))
PAGE 13
www.icit.in Python programming
Output
Python Operators
Python Operators
Operators are used to perform operations on variables and values.
• Arithmetic operators
• Assignment operators
• Comparison operators
• Logical operators
• Identity operators
• Membership operators
• Bitwise operators
Python Arithmetic Operators
PAGE 14
www.icit.in Python programming
PAGE 15
www.icit.in Python programming
PAGE 16
www.icit.in Python programming
Output
Program
a=5
b=6
c=7
PAGE 17
www.icit.in Python programming
s = (a + b + c) / 2
Output
PAGE 18
www.icit.in Python programming
1) If Statement
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)
PAGE 19
www.icit.in Python programming
• 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
Program
num = -1
if num >
0:
print(num, "is a positive number.")
PAGE 20
www.icit.in Python programming
Output
2) If -Else statement
• The else statement is an optional statement and there could be at most only one
else statement following if.
Syntax
The syntax of the if...else statement is −
if expression:
statement(s)
PAGE 21
www.icit.in Python programming
else:
statement(s)
Flow Diagram
PAGE 22
www.icit.in Python programming
Output
program to check if the input year is a leap year or not using if else statement
Program year
= 2000
if (year % 4) == 0: if
(year % 100) == 0: if
(year % 400) == 0:
print("{0} is a leap year".format(year))
PAGE 23
www.icit.in Python programming
else:
print("{0} is not a leap year".format(year))
else: print("{0} is a leap
year".format(year)) else:
print("{0} is not a leap year".format(year))
Output
3) nested IF statements
if elif else statement in Python. The if..elif..else statement is used when we need to check multiple
conditions.
Syntax
The syntax of the nested if...elif...else construct may be −
PAGE 24
www.icit.in Python programming
if expression1:
statement(s)
if expression2:
statement(s)
elif expression3:
statement(s)
elif expression4:
statement(s)
else:
statement(s)
else:
statement(s)
Notes:
1. There can be multiple ‘elif’ blocks, however there is only ‘else’ block is allowed.
2. Out of all these blocks only one block_of_code gets executed. If the condition is true then the code
inside ‘if’ gets executed, if condition is false then the next condition (associated with elif) is
evaluated and so on. If none of the conditions is true then the code inside ‘else’ gets executed.
Program
Program on checking multiple conditions using if..elif..else statement.
num = 1122 if 9 < num
< 99: print("Two
digit number") elif 99
< num < 999:
print("Three digit
number") elif 999 < num <
9999: print("Four digit
number") else:
print("number is <= 9 or >=
9999")
Output
PAGE 25
www.icit.in Python programming
Program to display the Fibonacci sequence up to n-th term where n is provided by the user
# change this value for a different result
nterms = 10
Output
PAGE 27
www.icit.in Python programming
# import module
import calendar
yy = 2014
mm = 11
print(calendar.month(yy, mm))
PAGE 28
www.icit.in Python programming
Output
Output
PAGE 29
www.icit.in Python programming
PAGE 30
www.icit.in Python programming
PAGE 31
www.icit.in Python programming
Output
Program to display the multiplication table of 12 using the for loop num = 12
PAGE 32
www.icit.in Python programming
Output
Function range()
In the above example, we have iterated over a list using for loop. However we can also use a range()
function in for loop to iterate over numbers defined by range().
• range(start, stop, step_size): The default step_size is 1 which is why when we didn’t specify
the step_size, the numbers generated are having difference of 1. However by specifying
step_size we can generate numbers having the difference of step_size.
PAGE 33
www.icit.in Python programming
Output
PAGE 34
www.icit.in Python programming
Program
for num1 in range(3): for num2 in
range(10, 14): print(num1,
",", num2)
Output
• While loop is used to iterate over a block of code repeatedly until a given condition returns false.
while condition:
#body_of_while
The body_of_while is set of Python statements which requires repeated execution. These set of
statements execute repeatedly until the given condition returns false.
1. First the given condition is checked, if the condition returns false, the loop is terminated and the
control jumps to the next statement in the program after the loop.
2. If the condition returns true, the set of statements inside loop are executed and then the control
jumps to the beginning of the loop for next iteration.
n = 10
Output
PAGE 37
www.icit.in Python programming
Program
# initialize sum
sum = 0
PAGE 38
www.icit.in Python programming
digit = temp % 10
sum += digit ** 3
temp //= 10
PAGE 39
www.icit.in Python programming
• When a while loop is present inside another while loop then it is called nested while loop. Lets
take an example to understand this concept.
Program
#!/usr/bin/python
i = 2 while(i
< 100):
j = 2 while(j <=
(i/j)): if not(i
%j): break j = j +
1 if (j > i/j) :
print (i, " is prime")
i = i + 1
Output
PAGE 40
www.icit.in Python programming
Program
We can have a ‘else’ block associated with while loop. The ‘else’ block is optional. It executes only
after the loop finished execution.
num = 10 while
num > 6:
print(num) num
= num-1 else:
print("loop is
finished")
Output
PAGE 41
www.icit.in Python programming
• The break statement is used to terminate the loop when a certain condition is met
• The break statement is generally used inside a loop along with a if statement so that when a particular
condition (defined in if statement) returns true, the break statement is encountered and the loop
terminates.
PAGE 42
www.icit.in Python programming
Program
program to display all the elements before number 88
Output:
PAGE 43
www.icit.in Python programming
Note: You would always want to use the break statement with a if statement so that only when the
condition associated with ‘if’ is true then only break is encountered. If you do not use it with ‘if’
statement then the break statement would be encountered in the first iteration of loop and the loop
would always terminate on the first iteration.
• The continue statement is used inside a loop to skip the rest of the statements in the body of
loop for the current iteration and jump to the beginning of the loop for next iteration
• The break and continue statements are used to alter the flow of loop, break terminates the loop
when a condition is met and continue skip the current iteration.
Syntax of continue statement in Python
The syntax of continue statement in Python is similar to what we have seen in Java(except the
semicolon)
continue
PAGE 44
www.icit.in Python programming
PAGE 45
www.icit.in Python programming
Output
• For example, we want to declare a function in our code but we want to implement that function in future,
which means we are not yet ready to write the body of the function. In this case we cannot leave the body
of function empty as this would raise error because it is syntactically incorrect, in such cases we can use
pass statement which does nothing but makes the code syntactically correct.
PAGE 46
www.icit.in Python programming
Program
If the number is even, we are doing nothing and if it is odd then we are displaying the number.
for num in [20,
11, 9, 66, 4, 89,
44]: if num%2
== 0:
pass
else:
print(num)
Output
PAGE 47
www.icit.in Python programming
PAGE 48
www.icit.in Python programming
Program
Program on create string in python
str = 'icit'
print(str)
str2 = "institute"
print(str2)
# multi-line string
str3 = """Welcome to
icit institute """
print(str3)
str4 = '''This is a
tech blog'''
print(str4)
Output
PAGE 49
www.icit.in Python programming
Program
str = "Kevin"
PAGE 50
www.icit.in Python programming
my_str = 'icit'
my_str = my_str.casefold()
PAGE 51
www.icit.in Python programming
print("It is palindrome")
else:
Output
• The + operator does this in Python. Simply writing two string literals together also concatenates
them.
• The * operator can be used to repeat the string for a given number of times.
Program
str1 = 'Hello' str2
='World!'
Output
PAGE 53
www.icit.in Python programming
Using for loop we can iterate through a string. Here is an example to count the number of 'l' in a
string.
PAGE 54
www.icit.in Python programming
# Updating a String
PAGE 55
www.icit.in Python programming
• While printing Strings with single and double quotes in it causes SyntaxError because String
already contains Single and Double Quotes and hence cannot be printed with the use of either
of these.
• Hence, to print such a String either Triple Quotes are used or Escape sequences are used to
print such Strings.
• Escape sequences start with a backslash and can be interpreted differently. If single quotes are
used to represent a string, then all the single quotes present in the string must be escaped and
same is done for Double Quotes.
• To ignore the escape sequences in a String, r or R is used, this implies that the string is a raw
string and escape sequences inside it are to be ignored.
PAGE 56
www.icit.in Python programming
Output:
PAGE 57
www.icit.in Python programming
Formatting of Strings
• Strings in Python can be formatted with the use of format() method which is very versatile and
powerful tool for formatting of Strings.
• Format method in String contains curly braces {} as placeholders which can hold arguments
according to position or keyword to specify the order.
• A string can be left(<), right(>) or center(^) justified with the use of format specifiers, separated
by colon(:). Integers such as Binary, hexadecimal, etc. and floats can be rounded or displayed
in the exponent form with the use of format specifiers.
Program for formatting of strings
# Python Program for
# Formatting of Strings
# Default order
PAGE 58
www.icit.in Python programming
# Positional Formatting
String1 = "{1} {0} {2}".format('Geeks', 'For',
'Life') print("\nPrint String in Positional
order: ") print(String1)
# Keyword Formatting
String1 = "{l} {f} {g}".format(g = 'Geeks', f = 'For',
l = 'Life') print("\nPrint String in order of
Keywords: ") print(String1)
# Formatting of Floats
String1 = "{0:e}".format(165.6458)
print("\nExponent representation of 165.6458
is ") print(String1)
# String alignment
String1 = "|{:<10}|{:^10}|{:>10}|".format('Geeks','for','Geeks')
print("\nLeft, center and right alignment with Formatting: ")
print(String1)
Output:
PAGE 59
www.icit.in Python programming
String methods
BUILT-IN FUNCTION DESCRIPTION
PAGE 60
www.icit.in Python programming
String.endswith() Returns True if a string ends with the given suffix otherwise returns False
String.startswith() Returns True if a string starts with the given prefix otherwise returns False
Returns “True” if all characters in the string are digits, Otherwise, It returns
String.isdigit()
“False”.
PAGE 61
www.icit.in Python programming
BUILT-IN DESCRIPTION
FUNCTION
String.Isalnum Returns true if all the characters in a given string are alphanumeric.
PAGE 62
www.icit.in Python programming
String.partition splits the string at the first occurrence of the separator and returns a tuple.
String.rindex Returns the highest index of the substring inside the string if substring is found.
string.lower Return a copy of s, but with upper case letters converted to lower case.
PAGE 63
www.icit.in Python programming
Return a list of the words of the string,If the optional second argument sep is
absent or None
string.split
string.rsplit() Return a list of the words of the string s, scanning s from the end.
string.splitfields Return a list of the words of the string when only used with two arguments.
string.strip() It return a copy of the string with both leading and trailing characters removed
string.swapcase Converts lower case letters to upper case and vice versa.
PAGE 64
www.icit.in Python programming
string-zfill Pad a numeric string on the left with zero digits until the given width is
reached.
string.replace Return a copy of string s with all occurrences of substring old replaced by
new.
Chapter No 6. Lists
Python Lists
PAGE 65
www.icit.in Python programming
# empty list
my_list = []
# list of integers
my_list = [1, 2, 3]
# nested list
PAGE 66
www.icit.in Python programming
PAGE 67
www.icit.in Python programming
Output
• We can use the index operator [] to access an item in a list. Index starts from 0. So, a list
having 5 elements will have index from 0 to 4.
• Trying to access an element other that this will raise an IndexError. The index must be an
integer. We can't use float or other types, this will result into TypeError.
PAGE 68
www.icit.in Python programming
my_list = ['p','r','o','b','e']
# Output: p print(my_list[0])
# Output: o print(my_list[2])
# Output: e print(my_list[4])
# Output: a print(n_list[0][1])
# Output: 5 print(n_list[1][3])
Output
PAGE 69
www.icit.in Python programming
Program my_list =
['p','r','o','b','e']
# Output: e print(my_list[-1])
# Output: p print(my_list[-5])
PAGE 70
www.icit.in Python programming
Output
PAGE 71
www.icit.in Python programming
# Creating a List
List =
['I','C','I','T','I','N',
'S','T','I','T','U','T','E']
print("Intial List: ")
print(List)
# Print elements of a range
# using Slice operation
Sliced_List = List[3:8]
print("\nSlicing elements in a range
3-8: ") print(Sliced_List)
# Print elements from
beginning
# to a pre-defined point using
Slice Sliced_List = List[:-6]
print("\nElements sliced till 6th element from
last: ") print(Sliced_List)
# Print elements from
a # pre-defined
point to end
Sliced_List =
List[5:]
print("\nElements sliced from 5th "
"element till the end: ")
print(Sliced_List)
# Printing elements from
# beginning till end
Sliced_List = List[:]
PAGE 72
www.icit.in Python programming
Output
Syntax:
set1.update(set2)
PAGE 73
www.icit.in Python programming
Parameters:
Update () method takes only a single argument. The single argument can be a set, list, tuples or a dictionary. It
automatically converts into a set and adds to the set.
Return value: This method adds set2 to set1 and returns nothing.
Program
Python program to demonstrate the use of update () method
list1 = [1, 2, 3, 4]
list2 = [1, 4, 2, 3, 5]
alphabet_set = {'a', 'b',
'c'}
# lists converted to
sets set1 =
set(list2) set2 =
set(list1)
# Update method
set1.update(set2
)
# Print the updated set
print(set1)
set1.update(alphabet_set)
print(set1)
Output
PAGE 74
www.icit.in Python programming
• Dictionary in Python is an unordered collection of data values, used to store data values like a
map, which unlike other Data Types that hold only single value as an element, Dictionary holds
key : value pair.
• In Python Dictionary, update () method updates the dictionary with the elements from
another dictionary object or from an iterable of key/value pairs.
In Python Dictionary, update () method updates the dictionary with the elements from the
another dictionary object or from an iterable of key/value pairs.
Syntax:
dict.update([other])
PAGE 75
www.icit.in Python programming
# Dictionary before
Updation
print("Original
Dictionary:")
print(Dictionary1) #
update the value of key
'B'
Dictionary1.update(Dictionary2)
print("Dictionary after updation:")
print(Dictionary1)
Output
PAGE 76
www.icit.in Python programming
PAGE 77
www.icit.in Python programming
Output
Program
Example 1: Remove Element from The List
# animal list
animal = ['cat', 'dog', 'rabbit', 'guinea pig']
PAGE 78
www.icit.in Python programming
Output
# animal list
animal = ['cat', 'dog', 'dog', 'guinea pig', 'dog']
PAGE 79
www.icit.in Python programming
Output
1 cmp(list1, list2)
PAGE 80
www.icit.in Python programming
2 len(list)
3 max(list)
4 min(list)
5 list(seq)
1 list.append(obj)
2 list.count(obj)
3 list.extend(seq)
4 list.index(obj)
5 list.insert(index, obj)
PAGE 81
www.icit.in Python programming
6 list.pop(obj=list[-1])
7 list.remove(obj)
8 list.reverse()
9 list.sort([func])
PAGE 82
www.icit.in Python programming
Chapter No 7. Tuple
What is tuple?
• In Python programming, a tuple is similar to a list.
• The difference between the two is that we cannot change the elements of a tuple once it is
assigned whereas in a list, elements can be changed.
• We generally use tuple for heterogeneous (different) datatypes and list for homogeneous
(similar) datatypes.
• Since tuple are immutable, iterating through tuple is faster than with list. So there is a slight
performance boost.
• Tuples that contain immutable elements can be used as key for a dictionary. With list, this is not
possible.
• If you have data that doesn't change, implementing it as tuple will guarantee that it remains
writeprotected.
Creating a Tuple
• A tuple is created by placing all the items (elements) inside a parentheses (), separated by
comma.
• A tuple can have any number of items and they may be of different types (integer, float, list,
string etc.).
# nested tuple
# Output: ("mouse", [8, 4, 6], (1, 2, 3)) my_tuple
= ("mouse", [8, 4, 6], (1, 2, 3)) print(my_tuple)
# tuple can be created without parentheses # also called tuple packing # Output: 3, 4.6, "dog"
Output
PAGE 84
www.icit.in Python programming
There are various ways in which we can access the elements of a tuple.
1. Indexing
We can use the index operator [] to access an item in a tuple where the index starts from 0.
So, a tuple having 6 elements will have index from 0 to 5. Trying to access an element other that (6,
7,) will raise an IndexError.
The index must be an integer, so we cannot use float or other types. This will result into TypeError.
Likewise, nested tuple is accessed using nested indexing, as shown in the example below
Program
my_tuple = ('p','e','r','m','i','t')
PAGE 85
www.icit.in Python programming
# Output: 'p'
print(my_tuple[0])
#print(my_tuple[6])
#my_tuple[2.0]
# nested tuple
n_tuple = ("mouse", [8, 4, 6], (1, 2, 3))
# nested index #
Output: 's'
print(n_tuple[0][3])
# nested index #
Output: 4
print(n_tuple[1][1])
PAGE 86
www.icit.in Python programming
Output
2. Negative Indexing
The index of -1 refers to the last item, -2 to the second last item and so on.
Program
my_tuple = ('p','e','r','m','i','t')
PAGE 87
www.icit.in Python programming
Output
3. Slicing
We can access a range of items in a tuple by using the slicing operator - colon ":".
Slicing can be best visualized by considering the index to be between the elements as shown below.
So if we want to access a range, we need the index that will slice the portion from the tuple.
PAGE 88
www.icit.in Python programming
Program
my_tuple = ('p','r','o','g','r','a','m','i','z')
Output
PAGE 89
www.icit.in Python programming
Deleting a Tuple
As discussed above, we cannot change the elements in a tuple. That also means we cannot delete or
remove items from a tuple.
Program
my_tuple = ('p','r','o','g','r','a','m','i','z')
#del my_tuple[3]
PAGE 90
www.icit.in Python programming
Output
PAGE 91
www.icit.in Python programming
Method Description
Program
my_tuple = ('a','p','p','l','e',)
# Count
# Output: 2
print(my_tuple.count('p'))
# Index
# Output: 3
print(my_tuple.index('l'))
PAGE 92
www.icit.in Python programming
Output
Built-in functions like all(), any(), enumerate(), len(), max(), min(), sorted(),
tuple()etc. are commonly used with tuple to perform different tasks.
Built-in Functions with Tuple
Function Description
all() ReturnTru if all elements of the tuple are true (or if the tuple is empty).
e
PAGE 93
www.icit.in Python programming
any()
ReturnTru if any element of the tuple is true. If the tuple is empty, False
e return .
enumerate() Return an enumerate object. It contains the index and value of all the items of tuple as
pairs.
len() Return the length (the number of items) in the tuple.
sorted() Take elements in the tuple and return a new sorted list (does not sort the tuple itself).
PAGE 94
www.icit.in Python programming
Chapter No 8. Dictonaries
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.
Creating a dictionary is as simple as placing items inside curly braces {} separated by comma.
An item has a key and the corresponding value expressed as a pair, key: value.
While values can be of any data type and can repeat, keys must be of immutable type (string,
number or tuple with immutable elements) and must be unique.
Program
Example
Create and print a dictionary:
PAGE 95
www.icit.in Python programming
Output
# Output: 26
print(my_dict.get('age'))
PAGE 96
www.icit.in Python programming
Output
• The update () method updates the dictionary with the elements from another dictionary object or
from an iterable of key/value pairs.
• The update () method adds element(s) to the dictionary if the key is not in the dictionary. If the key
is in the dictionary, it updates the key with the new value.
• dict.update([other])
PAGE 97
www.icit.in Python programming
update() Parameters
• The update() method takes either a dictionary or an iterable object of key/value pairs
(generally tuples).
They update() method updates the dictionary with elements from a dictionary object or an iterable
object of key/value pairs.
d1 = {2: "two"}
d.update(d1)
print(d)
d1 = {3: "three"}
d.update(d1)
print(d)
Output
PAGE 98
www.icit.in Python programming
Program
d = {'x': 2}
d.update(y = 3, z = 0) print(d)
PAGE 99
www.icit.in Python programming
Output
• We can remove a particular item in a dictionary by using the method pop ().
• This method removes as item with the provided key and returns the value.
• The method, pop item () can be used to remove and return an arbitrary item (key, value)
form the dictionary.
• All the items can be removed at once using the clear method. We can also use
()
the del keyword to remove individual items or the entire dictionary itself.
Program
PAGE 100
www.icit.in Python programming
# create a dictionary
# Output: 16
print(squares.pop(4))
# Output: (1, 1)
print(squares.popitem()) #
print(squares)
# Output: {2: 4, 3: 9}
PAGE 101
www.icit.in Python programming
print(squares)
# Output: {}
print(squares)
del squares
# Throws Error
# print(squares)
PAGE 102
www.icit.in Python programming
Output
Dictionary values have no restrictions. They can be any arbitrary Python object, either standard objects
or user-defined objects. However, same is not true for the keys.
(a) More than one entry per key not allowed. Which means no duplicate key is
allowed. When duplicate keys encountered during assignment, the last assignment wins.
For example:
7, ‘Name’: ‘Manni’};
(b) Keys must be immutable. Which means you can use strings, numbers or tuples as
dictionary keys but something like [‘key’] is not allowed. Following is a simple
example:
#!/usr/bin/python
1 cmp(dict1, dict2)
PAGE 104
www.icit.in Python programming
2
len(dict)
3 str(dict)
4
type(variable)
2 dict.copy()
3 dict.fromkeys()
Create a new dictionary with keys from seq and values set to
value.
4 dict.get(key, default=None)
5 dict.has_key(key)
6 dict.items()
PAGE 105
www.icit.in Python programming
7 dict.keys()
8 dict.setdefault(key, default=None)
10 dict.values()
• In Python, date, time and datetime classes provides a number of function to deal with dates, times and
time intervals.
• Date and datetime are an object in Python, so when you manipulate them, you are actually
manipulating objects and not string or timestamps.
• Whenever you manipulate dates or time, you need to import datetime function.
PAGE 106
www.icit.in Python programming
These import statements are pre-defined pieces of functionality in the Python library that let you
manipulates dates and times, without writing any code. Consider the following points before executing
the datetime code
This line tells the Python interpreter that from the datetime module import the date class We are not
writing the code for this date functionality alas just importing it for our use Step 2) Next, we create an
instance of the date object.
PAGE 107
www.icit.in Python programming
PAGE 108
www.icit.in Python programming
Monday 0
Tuesday 1
Wednesday 2
Friday 4
Sunday 6
PAGE 109
www.icit.in Python programming
Thursday 3
Saturday 5
Weekday Number is useful for arrays whose index is dependent on the Day of the week.
PAGE 110
www.icit.in Python programming
When we execute the code for datetime, it gives the output with current date and time.
Step 2) With "DATETIME OBJECT", you can also call time class. Suppose we want
t = datetime.time(datetime.now())
• We had imported the time class. We will be assigning it the current value of time using datetime.now()
• We are assigning the value of the current time to the variable t.
And this will give me just the time. So let's run this program.
PAGE 111
www.icit.in Python programming
Okay, so you can see that here I got the date and time. And then the next line, I've got just the time by itself
Step 3) We will apply our weekday indexer to our weekday's arrayList to know which day is today
• Weekdays operator (wd) is assigned the number from (0-6) number depending on what the current
weekday is. Here we declared the array of the list for days (Mon, Tue, Wed…Sun).
• Use that index value to know which day it is. In our case, it is #2, and it represents Wednesday, so in the
output it will print out "Which is a Wednesday."
PAGE 112
www.icit.in Python programming
Program
from datetime import
date from datetime
import time from
datetime import
datetime def main():
##DATETIME OBJECTS
#Get today's date from
datetime class
today=datetime.now() #print
(today)
# Get the current time
#t = datetime.time(datetime.now())
#print "The current time is", t
#weekday returns 0 (monday) through 6 (sunday)
wd=date.weekday(today) #Days start at 0 for monday
days=
["monday","tuesday","wednesday","thursday","friday","saturday"
,"sunday"] print("Today is day number %d" % wd)
print("which is a " + days[wd])
if __name__==
"__main__":
main()
Output
PAGE 113
www.icit.in Python programming
Calender Module
Python defines an inbuilt module “calendar” which handles operations related to calendar.
Operations on calendar :
1. calendar(year, w, l, c) :- This function displays the year, width of characters, no. of lines per
week and column separations.
2. firstweekday() :- This function returns the first week day number. By default, 0 (Monday).
Program
PAGE 114
www.icit.in Python programming
Output
3. isleap (year) :- This function checks if year mentioned in argument is leap or not.
4.leapdays (year1, year2) :- This function returns the number of leap days between the specified
years in arguments.
PAGE 115
www.icit.in Python programming
Output
PAGE 116
www.icit.in Python programming
1. month (year, month, w, l) :- This function prints the month of a specific year mentioned in
arguments. It takes 4 arguments, year, month, width of characters and no. of lines taken
by a week
Python code to demonstrate the working of month()
Program
Output
PAGE 117
www.icit.in Python programming
• Calendar module allows to output calendars like program, and provides additional useful
functions related to the calendar.
• Functions and classes defined in Calendar module use an idealized calendar, the current
Gregorian calendar extended indefinitely in both directions.
In Python, calendar. isleap() is a function provided in calendar module for simple text
calendars.
isleap() method is used to get value True if the year is a leap year, otherwise gives False.
Syntax: isleap()
Parameter:
year: Year to be tested leap or not.
PAGE 118
www.icit.in Python programming
Output
year = 2017
PAGE 119
www.icit.in Python programming
Output
PAGE 120
www.icit.in Python programming
Defining Function
Syntax of Function
def function_name(parameters):
"""docstring"""
statement(s)
PAGE 121
www.icit.in Python programming
variables defined inside a function is not visible from outside. Hence, they have a local
scope.
2. Lifetime of a variable is the period throughout which the variable exits in the memory.
The lifetime of
3.They are destroyed once we return from the function. Hence, a function does not
remember the
Program
def my_func():
x = 10
PAGE 122
www.icit.in Python programming
x = 20
my_func()
Output
Calling a Function
Program
def my_function():
print("Hello from a function")
my_function()
Output
PAGE 123
www.icit.in Python programming
One important thing to note is, in Python every variable name is a reference. When we pass a variable
to a function, a new reference to the object is created
Program
PAGE 124
www.icit.in Python programming
Output
Note
When we pass a reference and change the received reference to something else, the connection
between passed and received parameter is broken. For example, consider below program.
PAGE 125
www.icit.in Python programming
Program
def myFun(x):
Output
PAGE 126
www.icit.in Python programming
Arguments in Function
1.Default argument
Python has a different way of representing syntax and default values for function arguments. Default
values indicate that the function argument will take that value if no argument value is passed during
function call. The default value is assigned by using assignment(=) operator of the form
keywordname=value.
Let’s understand this through a function student. The function student contains 3-arguments out of
which 2 arguments are assigned with default values. So, function student accept one required
argument (firstname) and rest two arguments are optional.
Program
# 1 positional argument
student('John')
# 3 positional arguments
student('John', 'Gates', 'Seventh')
# 2 positional arguments
student('John', 'Gates')
student('John', 'Seventh')
Output
PAGE 127
www.icit.in Python programming
In the first call, there is only one required argument and the rest arguments use the default values. In
the second call, lastname and standard arguments value is replaced from default value to new passing
value. We can see order of arguments is important from 2nd, 3rd, and 4th call of function.
Program
# 1 keyword argument
student(firstname ='John')
# 2 keyword arguments
student(firstname ='John', standard ='Seventh')
PAGE 128
www.icit.in Python programming
# 2 keyword arguments
student(lastname ='Gates', firstname ='John')
Output
In the first call, there is only one required keyword argument. In the second call, one is required
argument and one is optional(standard), whose value get replaced from default to new passing value.
In the third call, we can see that order in keyword argument is not important.
2.Keyword arguments:
The idea is to allow caller to specify argument name with values so that caller does not need to
remember order of parameters.
Program
PAGE 129
www.icit.in Python programming
# Keyword arguments
student(firstname ='Geeks', lastname ='Practice')
student(lastname ='Practice', firstname ='Geeks')
Output
PAGE 130
www.icit.in Python programming
Program
Output
PAGE 131
www.icit.in Python programming
Anonymous functions:
In Python, anonymous function means that a function is without a name. As we already know that def
keyword is used to define the normal functions and the lambda keyword is used to create anonymous
functions.
Program
PAGE 132
www.icit.in Python programming
Output
In Python, anonymous function means that a function is without a name. As we already know that def
keyword is used to define the normal functions and the lambda keyword is used to create anonymous
functions. It has the following syntax:
lambda arguments: expression
This function can have any number of arguments but only one expression, which is evaluated and
returned.
One is free to use lambda functions wherever function objects are required.
PAGE 133
www.icit.in Python programming
You need to keep in your knowledge that lambda functions are syntactically restricted to a single
expression.
It has various uses in particular fields of programming besides other types of expressions in
functions.
Python Lambda
A lambda function can take any number of arguments, but can only have one expression.
Syntax
lambda arguments: expression
Program
x= lambda a:a+10
print(x(5))
Output
PAGE 134
www.icit.in Python programming
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
Program
PAGE 135
www.icit.in Python programming
def myfunc(n):
return lambda a : a * n
mydoubler = myfunc(2)
print(mydoubler(11))
Output
The return statement is used to exit a function and go back to the place from where it
was called.
PAGE 136
www.icit.in Python programming
Syntax of return
return [expression_list]
This statement can contain expression which gets evaluated and the value is returned. If
there is no expression in the statement or the return statement itself is not present
inside a function, then the function will return the None object.
Program
def absolute_value(num):
"""This function returns the absolute
value of the entered number"""
if num >= 0:
return num
else:
return -num
# Output: 2
print(absolute_value(2))
# Output: 4
print(absolute_value(-4))
Output
PAGE 137
www.icit.in Python programming
What is a Module?
Modules refer to a file containing Python statements and definitions.
• A file containing Python code, for e.g.: example.py, is called a module and its
module name would be example.
• We use modules to break down large programs into small manageable and
organized files. Furthermore, modules provide reusability of code.
• We can define our most used functions in a module and import it, instead of copying
their definitions into different programs.
We can import the definitions inside a module to another module or the interactive
interpreter in Python.
This does not enter the names of the functions defined in example directly in the current
symbol table. It only enters the module name example there.
Using the module name we can access the function using the dot . operator. For
example:
>>> example.add(4,5.5)
9.5
Program
PAGE 139
www.icit.in Python programming
import math
Output
Program
PAGE 140
www.icit.in Python programming
import math as m
Output
We have renamed the math module as m. This can save us typing time in some cases.
Note that the name math is not recognized in our scope. Hence, math.pi is invalid, m.pi is
the correct implementation.
PAGE 141
www.icit.in Python programming
Within a module, the module’s name (as a string) is available as the value of the global
variable __name__. The code in the module will be executed, just as if you imported it,
but with the __name__ set to "__main__".
Program
#!/usr/bin/python3
result = []
a, b = 0, 1
while b < n:
result.append(b)
a, b = b, a + b
return result
if __name__ == "__main__":
f = fib(100)
print(f)
Output
PAGE 142
www.icit.in Python programming
PAGE 143
www.icit.in Python programming
Program
#!/usr/bin/python3
import math
content = dir(math)
print (content)
Output
PAGE 144
www.icit.in Python programming
If locals() is called from within a function, it will return all the names that can be
accessed locally from that function.
If globals() is called from within a function, it will return all the names that can be
accessed globally from that function.
The return type of both these functions is dictionary. Therefore, names can be extracted
using the keys() function.
Therefore, if you want to reexecute the top-level code in a module, you can use
the reload() function. The reload() function imports a previously imported module again.
The syntax of the reload() function is this −
reload(module_name)
Here, module_name is the name of the module you want to reload and not the string
containing the module name. For example, to reload hello module, do the following −
reload(hello)
Packages in Python
A package is a hierarchical file directory structure that defines a single Python
application environment that consists of modules and subpackages and sub-
subpackages, and so on.
PAGE 145
www.icit.in Python programming
We can import modules from packages using the dot (.) operator.
For example, if want to import the start module in the above example, it is done as
follows.
import Game.Level.start
Now if this module contains a function named select_difficulty(), we must use the
full name to reference it.
Game.Level.start.select_difficulty(2)
If this construct seems lengthy, we can import the module without the package prefix as
follows.
start.select_difficulty(2)
Yet another way of importing just the required function (or class or variable) form a
module within a package would be as follows.
PAGE 146
www.icit.in Python programming
select_difficulty(2)
Although easier, this method is not recommended. Using the full namespace avoids
confusion and prevents two same identifier names from colliding.
While importing packages, Python looks in the list of directories defined in sys.path,
similar as for module search path.
PAGE 147
www.icit.in Python programming
What is a file?
File Handling
The key function for working with files in Python is the open() function.
"r" - Read - Default value. Opens a file for reading, error if the file does not exist
"a" - Append - Opens a file for appending, creates the file if it does not exist
"w" - Write - Opens a file for writing, creates the file if it does not exist
"x" - Create - Creates the specified file, returns an error if the file exists
In addition you can specify if the file should be handled as binary or text mode
PAGE 148
www.icit.in Python programming
There is more than one way to read a file in Python. If you need to extract a string that contains all
characters in the file then we can use file.read(). The full code would work like this:
Program
print (file.read())
Output
PAGE 149
www.icit.in Python programming
We use open () function in Python to open a file in read or write mode. As explained above,
open ( ) will return a file object.
To return a file object we use open() function along with two arguments, that accepts file name
and the mode, whether to read or write.
So, the syntax being: open(filename, mode).
There are three kinds of mode, that Python provides and how files can be opened:
“ r “, for reading.
“ w “, for writing.
“ a “, for appending.
“ r+ “, for both reading and writing
Program
print (each)
Output
PAGE 150
www.icit.in Python programming
Program
file = open('icit.txt','a')
file.close()
Output
PAGE 151
www.icit.in Python programming
If there are a large number of files to handle in your Python program, you can arrange
your code within different directories to make things more manageable.
A directory or folder is a collection of files and sub directories. Python has the os module,
which provides us with many useful methods to work with directories (and files as well).
We can get the present working directory using the getcwd() method.
This method returns the current working directory in the form of a string. We can also use
the getcwdb() method to get it as bytes object.
>>> import os
PAGE 152
www.icit.in Python programming
>>> os.getcwd()
'C:\\Program Files\\PyScripter'
>>> os.getcwdb()
b'C:\\Program Files\\PyScripter'
The extra backslash implies escape sequence. The print() function will render this
properly.
>>> print(os.getcwd())
C:\Program Files\PyScripter
Changing Directory
We can change the current working directory using the chdir() method.
The new path that we want to change to must be supplied as a string to this method. We
can use both forward slash (/) or the backward slash (\) to separate path elements.
>>> os.chdir('C:\\Python33')
>>> print(os.getcwd())
C:\Python33
This method takes in the path of the new directory. If the full path is not specified, the
new directory is created in the current working directory.
>>> os.mkdir('test')
PAGE 153
www.icit.in Python programming
>>> os.listdir()
['test']
The first argument is the old name and the new name must be supplies as the second
argument.
>>> os.listdir()
['test']
>>> os.rename('test','new_one')
>>> os.listdir()
['new_one']
>>> os.listdir()
['new_one', 'old.txt']
>>> os.remove('old.txt')
>>> os.listdir()
['new_one']
>>> os.rmdir('new_one')
>>> os.listdir()
[]
However, note that rmdir() method can only remove empty directories.
PAGE 154
www.icit.in Python programming
In order to remove a non-empty directory we can use the rmtree() method inside
the shutil module.
>>> os.listdir()
['test']
>>> os.rmdir('test')
Traceback (most recent call last):
...
OSError: [WinError 145] The directory is not empty: 'test'
>>> shutil.rmtree('test')
>>> os.listdir()
[]
PAGE 155
www.icit.in Python programming
Python has many built-in exceptions which forces your program to output an error when
something in it goes wrong.
When these exceptions occur, it causes the current process to stop and passes it to the
calling process until it is handled. If not handled, our program will crash.
For example, if function A calls function B which in turn calls function C and an exception
occurs in function C. If it is not handled in C, the exception passes to B and then to A.
If never handled, an error message is spit out and our program come to a sudden,
unexpected halt.
Syntax
try:
#block of code
except Exception1:
#block of code
except Exception2:
#block of code
#other code
PAGE 156
www.icit.in Python programming
We can also use the else statement with the try-except statement in which, we can place
the code which will be executed in the scenario if no exception occurs in the try block.
The syntax to use the else statement with the try-except statement is given below.
try:
#block of code
except Exception1:
#block of code
else:
#this code executes if no except block is executed
Program
try:
a = int(input("Enter a:"))
b = int(input("Enter b:"))
PAGE 157
www.icit.in Python programming
c = a/b;
print("a/b = %d"%c)
except Exception:
else:
Output
PAGE 158
www.icit.in Python programming
Python provides the flexibility not to specify the name of exception with the except
statement.
Program
try:
a = int(input("Enter a:"))
b = int(input("Enter b:"))
c = a/b;
print("a/b = %d"%c)
except:
PAGE 159
www.icit.in Python programming
else:
Output
Points to remember
1. Python facilitates us to not specify the exception with the except statement.
2. We can declare multiple exceptions in the except statement since the try block may
contain the statements which throw the different type of exceptions.
3. We can also specify an else block along with the try-except statement which will be
executed if no exception is raised in the try block.
4. The statements that don't throw the exception should be placed inside the else
block.
PAGE 160
www.icit.in Python programming
We can use the finally block with the try block in which, we can pace the important code
which must be executed before the try statement throws an exception.
syntax
try:
# block of code
# this may throw an exception
finally:
# block of code
# this will always be executed
PAGE 161
www.icit.in Python programming
Program
try:
fileptr = open("icit.txt","r")
try:
fileptr.write("Hi I am good")
finally:
fileptr.close()
print("file closed")
except:
print("Error")
Output
Raising exceptions
An exception can be raised by using the raise clause in python. The syntax to use the
raise statement is given below.
syntax
raise Exception_class,<value>
PAGE 162
www.icit.in Python programming
Points to remember
1. To raise an exception, raise statement is used. The exception class name follows it.
2. An exception can be provided with a value that can be given in the parenthesis.
3. To access the value "as" keyword is used. "e" is used as a reference variable which
stores the value of the exception
Program
try:
age = int(input("Enter the age?"))
if age<18:
raise ValueError;
else:
print("the age is valid")
except ValueError:
print("The age is not valid")
Output
PAGE 163
www.icit.in Python programming
User-Defined Exception
The python allows us to create our exceptions that can be raised from the program and
caught using the except clause. However, we suggest you read this section after visiting
the Python object and classes.
Program
class ErrorInCode(Exception):
self.data = data
def __str__(self):
return repr(self.data)
try:
raise ErrorInCode(2000)
Output
PAGE 164
www.icit.in Python programming
Like other general purpose languages, python is also an object-oriented language since
its beginning. Python is an object-oriented programming language. It allows us to develop
applications using an Object Oriented approach. In Python, we can easily create and use
classes and objects.
PAGE 165
www.icit.in Python programming
o Object
o Class
o Method
o Inheritance
o Polymorphism
o Data Abstraction
o Encapsulation
Object
The object is an entity that has state and behavior. It may be any real-world object like
the mouse, keyboard, chair, table, pen, etc.
Everything in Python is an object, and almost everything has attributes and methods. All
functions have a built-in attribute __doc__, which returns the doc string defined in the
function source code.
Class
The class can be defined as a collection of objects. It is a logical entity that has some
specific attributes and methods. For example: if you have an employee class then it
should contain an attribute and method, i.e. an email id, name, age, salary, etc.
Syntax
class ClassName:
<statement-1>
.
.
<statement-N>
Method
The method is a function that is associated with an object. In Python, a method is not
unique to class instances. Any object type can have methods.
Inheritance
PAGE 166
www.icit.in Python programming
By using inheritance, we can create a class which uses all the properties and behavior of
another class. The new class is known as a derived class or child class, and the one whose
properties are acquired is known as a base class or parent class.
Polymorphism
Polymorphism contains two words "poly" and "morphs". Poly means many and Morphs
means form, shape. By polymorphism, we understand that one task can be performed in
different ways. For example You have a class animal, and all animals speak. But they
speak differently. Here, the "speak" behavior is polymorphic in the sense and depends on
the animal. So, the abstract "animal" concept does not actually "speak", but specific
animals (like dogs and cats) have a concrete implementation of the action "speak".
Encapsulation
Data Abstraction
properties and behaviors of the parent object.
By using inheritance, we can create a class which uses all the properties and behavior of anot
The new class is known as a derived class or child class, and the one whose
PAGE 167
www.icit.in Python programming
1. Object-oriented Procedural
programming is the programming uses a
problem-solving list of instructions to
approach and used do computation step
where computation is by step.
done by using objects.
PAGE 168
www.icit.in Python programming
In python, a class can be created by using the keyword class followed by the class name.
The syntax to create a class is given below.
Syntax
class ClassName:
#statement_suite
Program
class Employee:
id = 10;
name = "John"
emp = Employee()
emp.display()
Output
PAGE 169
www.icit.in Python programming
A class needs to be instantiated if we want to use the class attributes in another class or
method. A class can be instantiated by calling the class using the class name.
<object-name> = <class-name>(<arguments>)
Program
class Employee:
id = 10;
name = "John"
emp = Employee()
PAGE 170
www.icit.in Python programming
emp.display()
Output
Overriding methods
The method is overwritten. This is only at class level, the parent class remains intact.
Program
class Robot:
def action(self):
print('Robot action')
class HelloRobot(Robot):
def action(self):
print('Hello world')
PAGE 171
www.icit.in Python programming
class DummyRobot(Robot):
def start(self):
print('Started.')
r = HelloRobot()
d = DummyRobot()
r.action()
d.action()
Output
Method overloading
In Python you can define a method in such a way that there are multiple ways to call it.
Given a single method or function, we can specify the number of parameters ourself.
Depending on the function definition, it can be called with zero, one, two or more parameters.
This is known as method overloading. Not all programming languages support method overloading,
but Python does.
PAGE 172
www.icit.in Python programming
Program
Output
PAGE 173
www.icit.in Python programming
Data Hiding
One of the key parts of object-oriented programming is encapsulation, which
involves the packaging of variables and related functions in one simple-to-use
object: the instance of a class.
In Python, however, the philosophy is slightly different “we are all consenting
adults” and therefore there are no particular restrictions on access.
Instead, there are methods and attributes, strongly private, that are distinguished
by the double underscore (__) as prefix in their name. Once a method is marked
with this double underscore, then the method will be really private and will no
longer be accessible from outside the class.
However, these methods can still be accessed from the outside, but using a
different name
_classname__privatemethodname
PAGE 174
www.icit.in Python programming
For example, if in a Figure class you have the private method __hidden you can
access externally to this method by calling
Program
# Driver code
myObject = MyClass()
print(myObject._MyClass__hiddenVariable)
Output
PAGE 175
www.icit.in Python programming
A regular expression in a programming language is a special text string used for describing a search pattern. It
is extremely useful for extracting information from text such as code, files, log, spreadsheets or even
documents.
In Python, a regular expression is denoted as RE (REs, regexes or regex pattern) are imported through re
module. Python supports regular expression through libraries. In Python regular expression supports various
things like Modifiers, Identifiers, and White space characters.
PAGE 176
www.icit.in Python programming
Program
#!/usr/bin/python
import re
PAGE 177
www.icit.in Python programming
if matchObj:
print ("matchObj.group() : ", matchObj.group())
Output
PAGE 178
www.icit.in Python programming
This function searches for first occurrence of RE pattern within string with optional flags.
Program
#!/usr/bin/python
import re
if searchObj:
print ("searchObj.group() : ", searchObj.group())
print ("searchObj.group(1) : ", searchObj.group(1))
print ("searchObj.group(2) : ", searchObj.group(2))
else:
print ("Nothing found!!")
Output
PAGE 179
www.icit.in Python programming
Syntax
re.sub(pattern, repl, string, max=0)
This method replaces all occurrences of the RE pattern in string with repl, substituting all
occurrences unless max provided. This method returns modified string.
Program
#!/usr/bin/python
import re
Output
1 re.I
2 re.L
PAGE 181
www.icit.in Python programming
3 re.M
4 re.S
5 re.U
6 re.X
1 ^
2 $
PAGE 182
www.icit.in Python programming
3 .
4 [...]
5 [^...]
6 re*
7 re+
8 re?
9 re{ n}
10 re{ n,}
11 re{ n, m}
12 a| b
PAGE 183
www.icit.in Python programming
Matches either a or b.
13 (re)
14 (?imx)
15 (?-imx)
16 (?: re)
17 (?imx: re)
18 (?-imx: re)
19 (?#...)
Comment.
20 (?= re)
21 (?! re)
PAGE 184
www.icit.in Python programming
22 (?> re)
23 \w
24 \W
25 \s
26 \S
Matches nonwhitespace.
27 \d
28 \D
Matches nondigits.
29 \A
30 \Z
PAGE 185
www.icit.in Python programming
before newline.
31 \z
32 \G
33 \b
34 \B
36 \1...\9
37 \10
Character classes
Sr.No Example & Description
.
1 [Pp]ython
PAGE 186
www.icit.in Python programming
2 rub[ye]
3 [aeiou]
4 [0-9]
5 [a-z]
6 [A-Z]
7 [a-zA-Z0-9]
8 [^aeiou]
9 [^0-9]
Repetition Cases
PAGE 187
www.icit.in Python programming
1 ruby?
2 ruby*
3 ruby+
4 \d{3}
5 \d{3,}
6 \d{3,5}
Match 3, 4, or 5 digits
Nongreedy repetition
This matches the smallest number of repetitions −
1 <.*>
2 <.*?>
PAGE 188
www.icit.in Python programming
1 \D\d+
No group: + repeats \d
2 (\D\d)+
3 ([Pp]ython(, )?)+
Backreferences
This matches a previously matched group again −
1 ([Pp])ython&\1ails
2 (['"])[^\1]*\1
Alternatives
1 python|perl
PAGE 189
www.icit.in Python programming
2 rub(y|le))
3 Python(!+|\?)
Anchors
This needs to specify match position.
1 ^Python
2 Python$
3 \APython
4 Python\Z
5 \bPython\b
6 \brub\B
PAGE 190
www.icit.in Python programming
7 Python(?=!)
8 Python(?!!)
1 R(?#comment)
2 R(?i)uby
3 R(?i:uby)
Same as above
4 rub(?:y|le))
PAGE 191
www.icit.in Python programming
What is CGI?
The Common Gateway Interface, or CGI, is a standard for external gateway
programs to interface with information servers such as HTTP servers.
The current version is CGI/1.1 and CGI/1.2 is under progress.
Web Browsing
To understand the concept of CGI, let us see what happens when we click a hyper link to
browse a particular web page or URL.
Your browser contacts the HTTP web server and demands for the URL, i.e.,
filename.
Web Server parses the URL and looks for the filename. If it finds that file then sends
it back to the browser, otherwise sends an error message indicating that you
requested a wrong file.
Web browser takes response from web server and displays either the received file
or error message.
PAGE 192
www.icit.in Python programming
1 CONTENT_TYPE
The data type of the content. Used when the client is sending
attached content to the server. For example, file upload.
2 CONTENT_LENGTH
PAGE 193
www.icit.in Python programming
3 HTTP_COOKIE
Returns the set cookies in the form of key & value pair.
4 HTTP_USER_AGENT
5 PATH_INFO
6 QUERY_STRING
7 REMOTE_ADDR
8 REMOTE_HOST
The fully qualified name of the host making the request. If this
information is not available, then REMOTE_ADDR can be used
to get IR address.
9 REQUEST_METHOD
10 SCRIPT_FILENAME
PAGE 194
www.icit.in Python programming
11 SCRIPT_NAME
12 SERVER_NAME
13 SERVER_SOFTWARE
http://www.test.com/cgi-bin/hello.py?key1=value1&key2=value2
The GET method is the default method to pass information from browser to web server
and it produces a long string that appears in your browser's Location:box. Never use GET
method if you have password or other sensitive information to pass to the server. The
GET method has size limitation: only 1024 characters can be sent in a request string. The
GET method sends information using QUERY_STRING header and will be accessible in
your CGI Program through QUERY_STRING environment variable.
You can pass information by simply concatenating key and value pairs along with any
URL or you can use HTML <FORM> tags to pass information using GET method.
Below is same hello_get.py script which handles GET as well as POST method.
PAGE 195
www.icit.in Python programming
#!/usr/bin/python
form = cgi.FieldStorage()
first_name = form.getvalue('first_name')
last_name = form.getvalue('last_name')
print "Content-type:text/html\r\n\r\n"
print "<html>"
print "<head>"
print "</head>"
print "<body>"
print "</body>"
print "</html>"
Let us take again same example as above which passes two values using HTML FORM
and submit button. We use same CGI script hello_get.py to handle this input.
PAGE 196
www.icit.in Python programming
</form>
Here is the actual output of the above form. You enter First and Last Name and then click
submit button to see the result.
First Name:
Submit
Last Name:
</form>
Below is checkbox.cgi script to handle input given by web browser for checkbox button.
#!/usr/bin/python
form = cgi.FieldStorage()
PAGE 197
www.icit.in Python programming
if form.getvalue('maths'):
math_flag = "ON"
else:
math_flag = "OFF"
if form.getvalue('physics'):
physics_flag = "ON"
else:
physics_flag = "OFF"
print "Content-type:text/html\r\n\r\n"
print "<html>"
print "<head>"
print "</head>"
print "<body>"
print "</body>"
Radio Buttons are used when only one option is required to be selected.
Here is example HTML code for a form with two radio buttons −
PAGE 198
www.icit.in Python programming
</form>
Below is radiobutton.py script to handle input given by web browser for radio button −
#!/usr/bin/python
form = cgi.FieldStorage()
if form.getvalue('subject'):
subject = form.getvalue('subject')
else:
print "Content-type:text/html\r\n\r\n"
print "<html>"
print "<head>"
PAGE 199
www.icit.in Python programming
print "</head>"
print "<body>"
print "</body>"
print "</html>"
</textarea>
</form>
Submit
#!/usr/bin/python
PAGE 200
www.icit.in Python programming
form = cgi.FieldStorage()
if form.getvalue('textcontent'):
text_content = form.getvalue('textcontent')
else:
print "Content-type:text/html\r\n\r\n"
print "<html>"
print "<head>";
print "</head>"
print "<body>"
print "</body>"
Here is example HTML code for a form with one drop down box −
</select>
PAGE 201
www.icit.in Python programming
</form>
#!/usr/bin/python
form = cgi.FieldStorage()
if form.getvalue('dropdown'):
subject = form.getvalue('dropdown')
else:
print "Content-type:text/html\r\n\r\n"
print "<html>"
print "<head>"
print "</head>"
print "<body>"
PAGE 202
www.icit.in Python programming
print "</body>"
print "</html>"
In many situations, using cookies is the most efficient method of remembering and
tracking preferences, purchases, commissions, and other information required for better
visitor experience or site statistics.
How It Works?
Your server sends some data to the visitor's browser in the form of a cookie. The browser
may accept the cookie. If it does, it is stored as a plain text record on the visitor's hard
drive. Now, when the visitor arrives at another page on your site, the cookie is available
for retrieval. Once retrieved, your server knows/remembers what was stored.
Expires − The date the cookie will expire. If this is blank, the cookie will expire
when the visitor quits the browser.
Domain − The domain name of your site.
Path − The path to the directory or web page that sets the cookie. This may be
blank if you want to retrieve the cookie from any directory or page.
Secure − If this field contains the word "secure", then the cookie may only be
retrieved with a secure server. If this field is blank, no such restriction exists.
Name=Value − Cookies are set and retrieved in the form of key and value pairs.
Setting up Cookies
It is very easy to send cookies to browser. These cookies are sent along with HTTP
Header before to Content-type field. Assuming you want to set UserID and Password as
cookies. Setting the cookies is done as follows −
#!/usr/bin/python
PAGE 203
www.icit.in Python programming
print "Content-type:text/html\r\n\r\n"
From this example, you must have understood how to set cookies. We use Set-
Cookie HTTP header to set cookies.
It is optional to set cookies attributes like Expires, Domain, and Path. It is notable that
cookies are set before sending magic line "Content-type:text/html\r\n\r\n.
Retrieving Cookies
It is very easy to retrieve all the set cookies. Cookies are stored in CGI environment
variable HTTP_COOKIE and they will have following form −
#!/usr/bin/python
if environ.has_key('HTTP_COOKIE'):
if key == "UserID":
user_id = value
PAGE 204
www.icit.in Python programming
if key == "Password":
password = value
This produces the following result for the cookies set by above script −
User ID = XYZ
Password = XYZ123
<html>
<body>
</form>
</body>
</html>
File:
Upload
Above example has been disabled intentionally to save people uploading file on our
server, but you can try above code with your server.
PAGE 205
www.icit.in Python programming
#!/usr/bin/python
import cgi, os
form = cgi.FieldStorage()
fileitem = form['filename']
if fileitem.filename:
fn = os.path.basename(fileitem.filename)
else:
print """\
Content-Type: text/html\n
<html>
PAGE 206
www.icit.in Python programming
<body>
<p>%s</p>
</body>
</html>
""" % (message,)
If you run the above script on Unix/Linux, then you need to take care of replacing file
separator as follows, otherwise on your windows machine above open() statement should
work fine.
fn = os.path.basename(fileitem.filename.replace("\\", "/" ))
For example, if you want make a FileName file downloadable from a given link, then its
syntax is as follows −
#!/usr/bin/python
# HTTP Header
fo = open("foo.txt", "rb")
str = fo.read();
print str
PAGE 207
www.icit.in Python programming
# Close opend
filefo.close()
Thread
A thread is an entity within a process that can be scheduled for execution. Also, it is the smallest unit
of processing that can be performed in an OS (Operating System).
In simple words, a thread is a sequence of such instructions within a program that can be executed
independently of other code. For simplicity, you can assume that a thread is simply a subset of a
process!
Stack pointer: Points to thread’s stack in the process. Stack contains the local variables under
thread’s scope.
Program counter: a register which stores the address of the instruction currently being executed
by thread.
Parent process Pointer: A pointer to the Process control block (PCB) of the process that the
thread lives on.
Consider the diagram below to understand the relation between process and its thread:
PAGE 208
www.icit.in Python programming
Multithreading
Each thread contains its own register set and local variables (stored in stack).
All thread of a process share global variables (stored in heap) and the program code.
PAGE 209
www.icit.in Python programming
Consider the diagram below to understand how multiple threads exist in memory:
In context switching, the state of a thread is saved and state of another thread is loaded whenever
any interrupt (due to I/O or manually set) takes place.
Context switching takes place so frequently that all the threads appear to be running parallely (this is
termed as multitasking).
Consider the diagram below in which a process contains two active threads:
PAGE 210
www.icit.in Python programming
Program
import threading
def print_cube(num):
"""
function to print cube of given num
"""
print("Cube: {}".format(num * num * num))
def print_square(num):
"""
function to print square of given num
"""
print("Square: {}".format(num * num))
if __name__ == "__main__":
# creating thread
t1 = threading.Thread(target=print_square, args=(10,))
PAGE 211
www.icit.in Python programming
t2 = threading.Thread(target=print_cube, args=(10,))
# starting thread 1
t1.start()
# starting thread 2
t2.start()
Output
PAGE 212
www.icit.in Python programming
Synchronizing Threads
The threading module provided with Python includes a simple-to-implement locking
mechanism that allows you to synchronize threads.
A new lock is created by calling the Lock() method, which returns the new lock.
The acquire(blocking) method of the new lock object is used to force threads to run
synchronously.
The optional blocking parameter enables you to control whether the thread waits
to acquire the lock.
If blocking is set to 0, the thread returns immediately with a 0 value if the lock
cannot be acquired and with a 1 if the lock was acquired. If blocking is set to 1, the
thread blocks and wait for the lock to be released.
The release() method of the new lock object is used to release the lock when it is
no longer required.
Program
#!/usr/bin/python
import threading
import time
threadLock = threading.Lock()
threads = []
PAGE 213
www.icit.in Python programming
Output
PAGE 214
www.icit.in Python programming
get() − The get() removes and returns an item from the queue.
put() − The put adds item to a queue.
qsize() − The qsize() returns the number of items that are currently in the queue.
empty() − The empty( ) returns True if queue is empty; otherwise, False.
full() − the full() returns True if queue is full; otherwise, False.
Chapter No 18 Database
PAGE 215
www.icit.in Python programming
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
Informix
Interbase
Oracle
Sybase
What is MySQLdb?
MySQLdb is an interface for connecting to a MySQL database server from Python. It
implements the Python Database API v2.0 and is built on top of the MySQL C API.
PAGE 216
www.icit.in Python programming
PAGE 217
www.icit.in Python programming
PAGE 218
www.icit.in Python programming
PAGE 219
www.icit.in Python programming
import pymysql
myCursor = conn.cursor()
#myCursor.execute("""CREATE TABLE names
#(
#id int primary key,
#name varchar(20)
#)""")
#myCursor.execute("INSERT INTO names(id,name)VALUES(2,'Avni');")
#print(">Data Inserted!!!")
#print(">Data Updated!!!!")
myCursor.execute("SELECT * FROM names;")
print(myCursor.fetchall(), end="\n")
conn.commit()
conn.close()
Output
PAGE 221