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

Python Final Book

The document provides an introduction to Python programming, detailing its features such as high-level readability, object-oriented design, and versatility in applications from web development to data analysis. It includes instructions for setting up the Python environment, basic syntax, variable creation, and data types, as well as an overview of conditional statements and decision-making structures. Additionally, it covers Python operators and offers example programs for arithmetic operations and decision-making logic.

Uploaded by

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

Python Final Book

The document provides an introduction to Python programming, detailing its features such as high-level readability, object-oriented design, and versatility in applications from web development to data analysis. It includes instructions for setting up the Python environment, basic syntax, variable creation, and data types, as well as an overview of conditional statements and decision-making structures. Additionally, it covers Python operators and offers example programs for arithmetic operations and decision-making logic.

Uploaded by

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

www.icit.

in Python programming

Chapter No 1. Introduction to python

Overview

Python is a popular programming language. It was created by Guido van Rossum, and
released in 1991.

It is used for:

• web development (server-side),


• software development,
• mathematics, • system scripting.

• Python is a high-level, interpreted, interactive and object-oriented scripting


language. Python is designed to be highly readable.
• It uses English keywords frequently where as other languages use punctuation,
and it has fewer syntactical constructions than other languages.
• Python is Interpreted
Python is processed at runtime by the interpreter. You do not need to compile your
program before executing it. This is similar to PERL and PHP.
• Python is Interactive
You can actually sit at a Python prompt and interact with the interpreter directly to
write your programs
• Python is Object-Oriented
Python supports Object-Oriented style or technique of programming that
encapsulates code within objects
• Python is a Beginner's Language
Python is a great language for the beginner-level programmers and supports the
development of a wide range of applications from simple text processing to WWW
browsers to games.

• It can be used as a scripting language or can be compiled to byte-code for building


large applications.

• It provides very high-level dynamic data types and supports dynamic type
checking.

• It supports automatic garbage collection.

• It can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java.

PAGE 1
www.icit.in Python programming

What can Python do?


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

Why Python?
• Python works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc).
• Python has a simple syntax similar to the English language.
• Python has syntax that allows developers to write programs with fewer lines than
some other programming languages.
• Python runs on an interpreter system, meaning that code can be executed as soon
as it is written. This means that prototyping can be very quick.
• Python can be treated in a procedural way, an object-orientated way or a
functional way.

Local Environment Setup


Open a terminal window and type "python" to find out if it is already installed and which
version is installed.

• Unix (Solaris, Linux, FreeBSD, AIX, HP/UX, SunOS, IRIX, etc.)


• Win 9x/NT/2000
• Macintosh (Intel, PPC, 68K)
• OS/2
• DOS (multiple versions)
• PalmOS
• Nokia mobile phones
• Windows CE
• Acorn/RISC OS
• BeOS
• Amiga
• VMS/OpenVMS
• QNX
PAGE 2
www.icit.in Python programming

• VxWorks
• Psion
• Python has also been ported to the Java and .NET virtual machines
Installation & Setup Guide

How to Install Python on Windows [PyCharm IDE]

Step 1). To download PyCharm visit the website https://www.jetbrains.com/pycharm/download/ and


Click the "DOWNLOAD" link under the Community Section.

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 6) Wait for the installation to finish.

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:

>>> print("Hello, World!")


Hello, World!

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:

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


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

Remember that variables are case-sensitive


A variable is created the moment you first assign a value to it.

1 Program for creating variable in python

x =5
y = "John"
print(x)
print(y)

Output

PAGE 8
www.icit.in Python programming

2 Program for creating variable in python

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.

To combine both text and a variable, Python uses the + character:


3 Program for to combine both text and variable

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.

Python divides the operators in the following groups:

• Arithmetic operators
• Assignment operators
• Comparison operators
• Logical operators
• Identity operators
• Membership operators
• Bitwise operators
Python Arithmetic Operators

Operator Description Example

PAGE 14
www.icit.in Python programming

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


30

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


operand. 10

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


Multiplicatio 200
n

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


operand

% Modulus Divides left hand operand by right hand b%a=


operand and returns remainder 0

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


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

PAGE 15
www.icit.in Python programming

Program for performing arithmetic operations

num1 = int(input('Enter First number: '))

num2 = int(input('Enter Second number '))

add = num1 + num2

dif = num1 - num2

mul = num1 * num2

div = num1 / num2

floor_div = num1 // num2

power = num1 ** num2

modulus = num1 % num2

print('Sum of ',num1 ,'and' ,num2 ,'is :',add)

print('Difference of ',num1 ,'and' ,num2 ,'is :',dif)

print('Product of' ,num1 ,'and' ,num2 ,'is :',mul)

print('Division of ',num1 ,'a nd' ,num2 ,'is :',div)

print('Floor Division of ',num1 ,'and' ,num2 ,'is :',floor_div)

print('Exponent of ',num1 ,'and' ,num2 ,'is :',power)

print('Modulus of ',num1 ,'and' ,num2 ,'is :',modulus)

PAGE 16
www.icit.in Python programming

Output

Program to find the area of triangle

Program

a=5
b=6
c=7

# Uncomment below to take inputs from the user


# a = float(input('Enter first side: '))
# b = float(input('Enter second side: '))
# c = float(input('Enter third side: '))

# calculate the semi-perimeter

PAGE 17
www.icit.in Python programming

s = (a + b + c) / 2

# calculate the area


area = (s*(s-a)*(s-b)*(s-c)) ** 0.5
print('The area of the triangle is %0.2f' %area)

Output

PAGE 18
www.icit.in Python programming

Chapter No 2. Conditional Statement (Decision Making Statement)

• Decision making is anticipation of conditions occurring while execution of the


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

o Python programming language assumes any non-zero and non-null values as


TRUE, and if it is either zero or null, then it is assumed as FALSE value.

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

Program On positive and negative number using If statement

# If the number is positive, we print an appropriate message


num = 3
if num > 0:
print(num, "is a positive number.")
print("This is always printed.")

num = -1
if num >
0:
print(num, "is a positive number.")

PAGE 20
www.icit.in Python programming

print("This is also always printed.")

Output

2) If -Else statement

o An else statement can be combined with an if statement. An else statement


contains the block of code that executes if the conditional expression in the
if statement resolves to 0 or a FALSE value.

• 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

Program on display even and odd numbers


num = 22 if num %
2 == 0:
print("Even
Number") else:
print("Odd
Number")

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

# To get year (integer input) from the user


# year = int(input("Enter a year: "))

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

# uncomment to take input from the user


#nterms = int(input("How many terms? "))

# first two terms


n1 = 0 n2 = 1
count = 0

# check if the number of terms is valid if


nterms <= 0:
PAGE 26
www.icit.in Python programming

print("Please enter a positive integer") elif


nterms == 1: print("Fibonacci sequence
upto",nterms,":")
print(n1) else:
print("Fibonacci sequence upto",nterms,":")
while count < nterms: print(n1,end=' , ')
nth = n1 + n2 # update values
n1 = n2
n2 = nth
count += 1

Output

PAGE 27
www.icit.in Python programming

Python program to display calendar of given month of the year


Program

# import module

import calendar

yy = 2014
mm = 11

# To ask month and year from the user


# yy = int(input("Enter year: "))
# mm = int(input("Enter month: "))

# display the calendar

print(calendar.month(yy, mm))

PAGE 28
www.icit.in Python programming

Output

Single Statement Suites


If the suite of an if clause consists only of a single line, it may go on the same line as the
header statement.
Program
#! /usr/bin/python
var =
100
if (var == 100): print ("Value of expression is 100") print
("Good bye!")

Output

PAGE 29
www.icit.in Python programming

Chapter no 3. Looping Statements For Loop


• A loop is a used for iterating over a set of statements repeatedly.
Syntax of For loop in Python

PAGE 30
www.icit.in Python programming

for <variable> in <sequence>:


# body_of_loop that has set of statements
# which requires repeated execution

• Here <variable> is a variable that is used for iterating over a <sequence>.


• On every iteration it takes the next value from <sequence> until the end of

sequence is reached. Python – For loop example

Program to print squares of all numbers present in a list

# List of integer numbers


numbers = [1, 2, 4, 6,
11, 20]

# variable to store the square of each


num temporary sq = 0

# iterating over the given


list for val in numbers:
# calculating square of
each number sq = val * val
# displaying the squares
print(sq)

PAGE 31
www.icit.in Python programming

Output

Program to display the multiplication table of 12 using the for loop num = 12

# To take input from the user


# num = int(input("Display multiplication table of? "))

# use for loop to iterate 10 times for i in


range(1, 11):
print(num,'x',i,'=',num*i)

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(n): generates a set of whole numbers starting from 0 to (n-1).


For example:
range(8) is equivalent to [0, 1, 2, 3, 4, 5, 6, 7]
• range(start, stop): generates a set of whole numbers starting from star to stop- .
t 1
For example:
range(5, 9) is equivalent to [5, 6, 7, 8]

• 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

For example: range(1, 10, 2) is equivalent to


[1, 3, 5, 7, 9]

Lets use the range() function in for loop:

for loop example using range() function


Here we are using range() function to calculate and display the sum of first 5 natural numbers.
Program to print the sum of first 5 natural numbers

# variable to store the


sum sum = 0

# iterating over natural numbers


using range() for val in range(1,
6): # calculating sum sum =
sum + val

# displaying sum of first 5 natural


numbers print(sum)

Output

PAGE 34
www.icit.in Python programming

Nested For loop in Python


When a for loop is present inside another for loop then it is called a nested for loop. Let’s take an
example of nested for loop.

Program
for num1 in range(3): for num2 in
range(10, 14): print(num1,
",", num2)

Output

Python While Loop

• While loop is used to iterate over a block of code repeatedly until a given condition returns false.

Syntax of while loop


PAGE 35
www.icit.in Python programming

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.

Flow of while loop

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.

Flowchart of while Loop

Example: Python while Loop


Program
Program to add natural numbers upto sum = 1+2+3+...+n
# To take input from the user,
# n = int(input("Enter n: "))
PAGE 36
www.icit.in Python programming

n = 10

# initialize sum and counter sum


=0
i=1

while i <= n: sum = sum +


i i = i+1 # update
counter

# print the sum print("The


sum is", sum)

Output

PAGE 37
www.icit.in Python programming

Program

Python program to check if the number provided by the user is an Armstrong


number or not
# take input from the user num
= int(input("Enter a number:
"))

# initialize sum
sum = 0

# find the sum of the cube of each


digit temp = num while temp > 0:

PAGE 38
www.icit.in Python programming

digit = temp % 10
sum += digit ** 3
temp //= 10

# display the result


if num == sum:
print(num,"is an Armstrong number")
else:
print(num,"is not an Armstrong number")
Output

PAGE 39
www.icit.in Python programming

Nested while loop in Python

• 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

print ("Good bye!")

Output

Python – while loop with else block

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

Chapter No 4. Control Statements

Python break Statement

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

Syntax of break statement in Python


break

PAGE 42
www.icit.in Python programming

Flow diagram of break

Example of break statement


In this example, we are searching a number ’88’ in the given list of numbers. The requirement is to display all
the numbers till the number ’88’ is found and when it is found, terminate the loop and do not display the rest of
the numbers.

Program
program to display all the elements before number 88

for num in [11, 9, 88, 10,


90, 3, 19]: print(num)
if(num==88):
print("The number 88 is found")
print("Terminating the loop")
break

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.

Python Continue Statement

• 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

Flow diagram of continue

Example of continue statement


• Lets say we have a list of numbers and we want to print only the odd numbers out of that list.

• We can do this by using continue statement.


We are skipping the print statement inside loop by using continue statement when the number
is even, this way all the even numbers are skipped and the print statement executed for all the
odd numbers.

Program to display only odd numbers


for num in [20, 11, 9, 66, 4, 89, 44]:
# Skipping the iteration when number is even
if num%2 == 0:
continue
# This statement will be skipped for all even numbers
print(num)

PAGE 45
www.icit.in Python programming

Output

Python pass Statement


• The pass statement acts as a placeholder and usually used when there is no need of code
but a statement is still required to make a code syntactically correct

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

Python pass statement example

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

Chapter No.5 String

• A string is usually a bit of text (sequence of characters).

PAGE 48
www.icit.in Python programming

• In Python we use” (double quotes) or ‘(single quotes) to represent a string

1. How to create a String in Python


There are several ways to create strings in Python.
1. We can use ‘(single quotes), see the string str in the following code.
2. We can use” (double quotes), see the string str2 in the source code below.
3. Triple double quotes “”” and triple single quotes”’ are used for creating multi-line strings in Python. See the
strings str3 and str4 in the following example.

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

2. How to access strings in Python


• A string is nothing but an array of characters so we can use the indexes to access the
characters of a it. Just like arrays, the indexes start from 0 to the length-1
• You will get IndexError if you try to access the character which is not in the range. For
example, if a string is of length 6 and you try to access the 8th char of it then you will get this
error.

Program
str = "Kevin"

# displaying whole string


print(str)

# displaying first character of string


print(str[0])

PAGE 50
www.icit.in Python programming

# displaying third character of string


print(str[2])

# displaying the last character of the string print(str[-


1])

# displaying the second last char of string print(str[-2])


Output

Python Program to Check Whether a String is Palindrome or Not


# change this value for a different output

my_str = 'icit'

# make it suitable for caseless comparison

my_str = my_str.casefold()

PAGE 51
www.icit.in Python programming

# reverse the string


rev_str = reversed(my_str)

# check if the string is equal to its

reverse if list(my_str) == list(rev_str):

print("It is palindrome")

else:

print("It is not palindrome")

Output

Python String Operations


Concatenation of Two or More Strings
PAGE 52
www.icit.in Python programming

• Joining of two or more strings into a single one is called concatenation.

• 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!'

# using + print('str1 + str2 = ', str1 +


str2)

# using * print('str1 * 3 =',


str1 * 3)

Output

PAGE 53
www.icit.in Python programming

Iterating Through String

Using for loop we can iterate through a string. Here is an example to count the number of 'l' in a
string.

Program count = 0 for letter


in 'Hello World': if(letter
== 'l'): count += 1
print(count,'letters found')
Output

PAGE 54
www.icit.in Python programming

Deleting/Updating from a String

• In Python, Updation or deletion of characters from a String is not allowed.


• This will cause an error because item assignment or item deletion from a String is not
supported.
• Although deletion of entire String is possible with the use of a built-in del keyword.
• This is because Strings are immutable, hence elements of a String cannot be changed once it
has been assigned. Only new strings can be reassigned to the same name.
Program for Updation string in python
Program
String1 = "Hello, I'm a student"
print("Initial String: ")
print(String1)

# Updating a String

PAGE 55
www.icit.in Python programming

String1 = "Welcome to the icit


institute" print("\nUpdated String: ")
print(String1)
Output

Escape Sequencing in Python

• 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

Python Program for Escape Sequencing of String


# Initial String
String1 = '''I'm a "student"''' print("Initial String with use
of Triple Quotes: ") print(String1)

# Escaping Single Quote String1 =


'I\'m a "student"' print("\nEscaping
Single Quote: ") print(String1)

# Escaping Doule Quotes String1 = "I'm a


\"student\"" print("\nEscaping Double
Quotes: ") print(String1)

# Printing Paths with the


# use of Escape Sequences String1 =
"C:\\Python\\student\\" print("\
nEscaping Backslashes: ")
print(String1)

# Printing student in HEX


String1 = "This is \x47\x65\x65\x6b\x73 in \x48\x45\x58" print("\nPrinting in HEX
with the use of Escape Sequences: ") print(String1)

# Using raw String to


# ignore Escape Sequences
String1 = r"This is \x47\x65\x65\x6b\x73 in \x48\x45\x58" print("\nPrinting Raw String in HEX Format: ")
print(String1)

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

String1 = "{} {} {}".format('Geeks', 'For',


'Life') print("Print String in default order:
") print(String1)

# 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 Integers String1 =


"{0:b}".format(16) print("\nBinary
representation of 16 is ")
print(String1)

# Formatting of Floats
String1 = "{0:e}".format(165.6458)
print("\nExponent representation of 165.6458
is ") print(String1)

# Rounding off Integers


String1 =
"{0:.2f}".format(1/6)
print("\none-sixth 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

string.ascii_letters Concatenation of the ascii_lowercase and ascii_uppercase constants.

string.ascii_lowercas Concatenation of lowercase letters


e

string.ascii_uppercas Concatenation of uppercase letters


e

string.digits Digit in strings

PAGE 60
www.icit.in Python programming

string.hexdigits Hexadigit in strings

string.letters concatenation of the strings lowercase and uppercase

string.lowercase A string must contain lowercase letters.

string.octdigits Octadigit in a string

string.punctuation ASCII characters having punctuation characters.

string.printable String of characters which are printable

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

Returns “True” if all characters in the string are alphabets, Otherwise, It


String.isalpha() returns “False”.

PAGE 61
www.icit.in Python programming

string.isdecimal() Returns true if all characters in a string are decimal.

one of the string formatting methods in Python3, which allows multiple


str.format() substitutions and value formatting.

String.index Returns the position of the first occurrence of substring in a string

string.uppercase A string must contain uppercase letters.

string.whitespace A string containing all characters that are considered whitespace.

Method converts all uppercase characters to lowercase and vice versa of


string.swapcase() the given string, and returns it

returns a copy of the string where all occurrences of a substring is replaced


replace() with another substring.

Deprecated string functions

BUILT-IN DESCRIPTION
FUNCTION

string.Isdecimal Returns true if all characters in a string are decimal

String.Isalnum Returns true if all the characters in a given string are alphanumeric.

string.Istitle Returns True if the string is a titlecased string

PAGE 62
www.icit.in Python programming

String.partition splits the string at the first occurrence of the separator and returns a tuple.

String.Isidentifier Check whether a string is a valid identifier or not.

String.len Returns the length of the string.

String.rindex Returns the highest index of the substring inside the string if substring is found.

String.Max Returns the highest alphabetical character in a string.

String.min Returns the minimum alphabetical character in a string.

String.splitlines Returns a list of lines in the string.

string.capitalize Return a word with its first character capitalized.

string.expandtab Expand tabs in a string replacing them by one or more spaces


s

string.find Return the lowest indexin a sub string.

string.rfind find the highest index.

string.rindex Raise ValueError when the substring is not found.

string.count Return the number of (non-overlapping) occurrences of substring sub in string

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.

rpartition() Method splits the given string into three parts

string.splitfields Return a list of the words of the string when only used with two arguments.

string.join Concatenate a list or tuple of words with intervening occurrences of sep.

string.strip() It return a copy of the string with both leading and trailing characters removed

string.lstrip Return a copy of the string with leading characters removed.

string.rstrip Return a copy of the string with trailing characters removed.

string.swapcase Converts lower case letters to upper case and vice versa.

string.translate translate the characters using table

string.upper lower case letters converted to upper case.

string.ljust left-justify in a field of given width.

string.rjust Right-justify in a field of given width.

PAGE 64
www.icit.in Python programming

string.center() Center-justify in a field of given width.

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

• Lists are just like the arrays, declared in other languages.


• Lists need not be homogeneous always which makes it a most powerful tool in Python.
• A single list may contain DataTypes like Integers, Strings, as well as Objects.
• Lists are also very useful for implementing stacks and queues
• Lists are mutable, and hence, they can be altered even after their creation.
• In Python, list is a type of container in Data Structures, which is used to store multiple data at
the same time.
• Unlike Sets, the list in Python are ordered and have a definite count
• Note- Lists are a useful tool for preserving a sequence of data and further iterating over it.

List creation in python


• In Python programming, a list is created by placing all the items (elements) inside a square
bracket [ ], separated by commas.
• It can have any number of items and they may be of different types (integer, float, string etc.).

PAGE 65
www.icit.in Python programming

# empty list
my_list = []

# list of integers
my_list = [1, 2, 3]

# list with mixed datatypes


my_list = [1, "Hello", 3.4]
Also, a list can even have another list as an item. This is called nested list.

# nested list

my_list = ["mouse", [8, 4, 6], ['a']]

Program to demonstrate creation of List


# Creating a List List = []
print("Intial blank List: ")
print(List)

# Creating a List with


# the use of a String List =
['IcitInstituteccc'] print("\nList with the use
of String: ") print(List)

# Creating a List with


# the use of multiple values List = ["Icit",
"Institute", "ccc"] print("\nList containing
multiple values: ") print(List[0]) print(List[2])

# Creating a Multi-Dimensional List

PAGE 66
www.icit.in Python programming

# (By Nesting a list inside a List) List =


[['Icit', 'Institute'] , ['ccc']] print("\nMulti-
Dimensional List: ") print(List)

# Creating a List with


# the use of Numbers
# (Having duplicate values) List = [1, 2, 4, 4,
3, 3, 3, 6, 5] print("\nList with the use of
Numbers: ") print(List)

# Creating a List with


# mixed type of values
# (Having numbers and strings)
List = [1, 2, 'Icit', 4, 'Institute', 6, 'ccc'] print("\nList with
the use of Mixed Values: ") print(List)

PAGE 67
www.icit.in Python programming

Output

Accessing elements in list


There are various ways in which we can access the elements of a list.

Way 1. List Index

Way 2. Negative indexing

Way 3. slicing operator (colon)

Way 1. List Index

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

Program for Nested list are accessed using nested indexing.


Program

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

# Error! Only integer can be used for indexing


# my_list[4.0]

# Nested List n_list = ["Happy",


[2,0,1,5]] # Nested indexing

# Output: a print(n_list[0][1])

# Output: 5 print(n_list[1][3])

Output

PAGE 69
www.icit.in Python programming

Way 2. Negative indexing


Python allows negative indexing for its sequences. The index of -1 refers to the last item, -2 to the
second last item and so on.

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

Way 3. slicing operator (colon)


How to slice lists in Python?
• In Python List, there are multiple ways to print the whole List with all the elements, but to print a
specific range of elements from the list, we use Slice operation.
• Slice operation is performed on Lists with the use of colon(:). To print elements from beginning
to a range use [:Index], to print elements from end use [:-Index], to print elements from specific
Index till the end use [Index:], to print elements within a range, use [Start Index:End Index] and
to print whole List with the use of slicing operation, use [:]. Further, to print whole List in reverse
order, use [::-1].
Note – To print elements of List from rear end, use Negative Indexes.

PAGE 71
www.icit.in Python programming

Python program to demonstrate Removal of elements in a List

# 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

print("\nPrinting all elements using slice


operation: ") print(Sliced_List)
# Printing elements in reverse
# using Slice operation
Sliced_List = List[::-1]
print("\nPrinting List in reverse: ")
print(Sliced_List)

Output

Updating Lists in python


• update () function in set adds elements from a set (passed as an argument) to the set.

Syntax:
set1.update(set2)

PAGE 73
www.icit.in Python programming

Here set1 is the set in which set2 will be added.

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

Python Dictionary | update () method

• 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])

Python program to show working of update () method in Dictionary

Example #1: Update with another Dictionary.

PAGE 75
www.icit.in Python programming

# Dictionary with three


items
Dictionary1 = { 'A': 'Icit', 'B': 'Institute',
}
Dictionary2 = { 'B': 'Icit' }

# 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

Example #2: Update with an iterable.

# Dictionary with single item


Dictionary1 = { 'A':
'Icit'}
# Dictionary before
Updation
print("Original
Dictionary:")
print(Dictionary1)
# update the Dictionary with iterable
Dictionary1.update(B = 'Institute', C =
'Icit') print("Dictionary after updation:")
print(Dictionary1)

PAGE 77
www.icit.in Python programming

Output

Delete List Elements in python


To remove a list element, you can use either the del statement if you know exactly which element(s) you are
deleting or the remove () method

Program
Example 1: Remove Element from The List

# animal list
animal = ['cat', 'dog', 'rabbit', 'guinea pig']

# 'rabbit' element is removed


animal.remove('rabbit')

PAGE 78
www.icit.in Python programming

#Updated Animal List


print('Updated animal list: ', animal)

Output

Example 2: remove () Method on a List having Duplicate Elements


Program
# If a list contains duplicate elements
# the remove () method removes only the first instance

# animal list
animal = ['cat', 'dog', 'dog', 'guinea pig', 'dog']

PAGE 79
www.icit.in Python programming

# 'dog' element is removed animal.remove('dog')

#Updated Animal List


print('Updated animal list: ', animal)

Output

Built-in List Functions & Methods


Python includes the following list functions −

Sr.No Function with Description


.

1 cmp(list1, list2)

Compares elements of both lists.

PAGE 80
www.icit.in Python programming

2 len(list)

Gives the total length of the list.

3 max(list)

Returns item from the list with max value.

4 min(list)

Returns item from the list with min value.

5 list(seq)

Converts a tuple into list.


Python includes following list methods

Sr.No Methods with Description


.

1 list.append(obj)

Appends object obj to list

2 list.count(obj)

Returns count of how many times obj occurs in list

3 list.extend(seq)

Appends the contents of seq to list

4 list.index(obj)

Returns the lowest index in list that obj appears

5 list.insert(index, obj)

Inserts object obj into list at offset index

PAGE 81
www.icit.in Python programming

6 list.pop(obj=list[-1])

Removes and returns last object or obj from list

7 list.remove(obj)

Removes object obj from list

8 list.reverse()

Reverses objects of list in place

9 list.sort([func])

Sorts objects of list, use compare func if given

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.

Advantages of Tuple over List

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

• The parentheses are optional but is a good practice to write it.

• A tuple can have any number of items and they may be of different types (integer, float, list,
string etc.).

Program for creating tuple in python Program


# empty tuple #
Output: ()
my_tuple = ()
print(my_tuple)

# tuple having integers #


Output: (1, 2, 3)
my_tuple = (1, 2, 3)
print(my_tuple)
PAGE 83
www.icit.in Python programming

# tuple with mixed datatypes


# Output: (1, "Hello", 3.4)
my_tuple = (1, "Hello", 3.4)
print(my_tuple)

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

my_tuple = 3, 4.6, "dog"


print(my_tuple)

# tuple unpacking is also possible #


Output:
#3
# 4.6 # dog a, b, c
= my_tuple
print(a) print(b)
print(c)

Output

PAGE 84
www.icit.in Python programming

Accessing Elements in a Tuple

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

# Output: 't' print(my_tuple[5])

# index must be in range


# If you uncomment line 14, #
you will get an error.
# IndexError: list index out of range

#print(my_tuple[6])

# index must be an integer #


If you uncomment line 21, #
you will get an error.
# TypeError: list indices must be integers, not float

#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

Python allows negative indexing for its sequences.

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

# Output: 't' print(my_tuple[-1])

PAGE 87
www.icit.in Python programming

# Output: 'p' print(my_tuple [-


6])

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

# elements 2nd to 4th #


Output: ('r', 'o', 'g')
print(my_tuple[1:4])

# elements beginning to 2nd


# Output: ('p', 'r')
print(my_tuple [:-7])

# elements 8th to end #


Output: ('i', 'z')
print(my_tuple[7:])

# elements beginning to end


# Output: ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')
print(my_tuple[:])

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.

But deleting a tuple entirely is possible using the keyword del.

Program
my_tuple = ('p','r','o','g','r','a','m','i','z')

# can't delete items # if


you uncomment line 8, #
you will get an error:
# TypeError: 'tuple' object doesn't support item deletion

#del my_tuple[3]

PAGE 90
www.icit.in Python programming

# can delete entire tuple


# NameError: name 'my_tuple' is not defined
del my_tuple my_tuple

Output

Python Tuple Methods


Methods that add items or remove items are not available with tuple. Only the following two methods
are available.

Python Tuple Method

PAGE 91
www.icit.in Python programming

Method Description

count(x) Return the number of items that is equal to x

index(x) Return index of first item that is equal to x

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

3. Built-in Functions with Tuple

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.

max() Return the largest item in the tuple.

min() Return the smallest item in the tuple

sorted() Take elements in the tuple and return a new sorted list (does not sort the tuple itself).

sum() Retrun the sum of all elements in the tuple.

tuple() Convert an iterable (list, string, set, dictionary) to a tuple.

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.

How to create a dictionary?

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:

thisdict = { "brand": "Ford",


"model": "Mustang",
"year": 1964
} print(thisdict)

PAGE 95
www.icit.in Python programming

Output

How to Accessing directories Items?


You can access the items of a dictionary by referring to its key name, inside square
brackets:
Program

my_dict = {'name':'Anjana', 'age': 29}# Output: Jack print(my_dict['name'])

# Output: 26
print(my_dict.get('age'))

# Trying to access keys which doesn't exist throws error


# my_dict.get('address')
# my_dict['address']

PAGE 96
www.icit.in Python programming

Output

Python Dictionary update ()

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

The syntax of update () is:

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

• If update() is called without passing parameters, the dictionary remains unchanged.

Return Value from update()

They update() method updates the dictionary with elements from a dictionary object or an iterable
object of key/value pairs.

It doesn't return any value (returns None).

Example 1: How update () works in Python?


d = {1: "one", 2: "three"}

d1 = {2: "two"}

# updates the value of key 2

d.update(d1)

print(d)

d1 = {3: "three"}

# adds element with key 3

d.update(d1)

print(d)

Output

PAGE 98
www.icit.in Python programming

Example 2: How update () Works with an Iterable?

Program

d = {'x': 2}

d.update(y = 3, z = 0) print(d)

PAGE 99
www.icit.in Python programming

Output

How to delete or remove elements from a dictionary?

• 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

squares = {1:1, 2:4, 3:9, 4:16, 5:25}

# remove a particular item

# Output: 16

print(squares.pop(4))

# Output: {1: 1, 2: 4, 3: 9, 5: 25} print(squares)

# remove an arbitrary item

# Output: (1, 1)

print(squares.popitem()) #

Output: {2: 4, 3: 9, 5: 25}

print(squares)

# delete a particular item del


squares[5]

# Output: {2: 4, 3: 9}

PAGE 101
www.icit.in Python programming

print(squares)

# remove all items


squares.clear()

# Output: {}
print(squares)

# delete the dictionary itself

del squares

# Throws Error

# print(squares)

PAGE 102
www.icit.in Python programming

Output

Properties of Dictionary Keys

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

There are two important points to remember about dictionary keys:

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

#!/usr/bin/python dict = {‘Name’: ‘Zara’, ‘Age’:

7, ‘Name’: ‘Manni’};

print “dict[‘Name’]: “, dict[‘Name’];


PAGE 103
www.icit.in Python programming

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


dict[‘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

dict = {[‘Name’]: ‘Zara’, ‘Age’: 7};

print “dict[‘Name’]: “, dict[‘Name’];

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


Traceback (most recent call last):

File “test.py”, line 3, in<module>

dict = {[‘Name’]: ‘Zara’, ‘Age’: 7};

TypeError: list objects are unhashable

Built-in Dictionary Functions & Methods


Python includes the following dictionary functions −

Sr.No Function with Description


.

1 cmp(dict1, dict2)

Compares elements of both dict.

PAGE 104
www.icit.in Python programming

2
len(dict)

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


the number of items in the dictionary.

3 str(dict)

Produces a printable string representation of a dictionary

4
type(variable)

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


dictionary, then it would return a dictionary type.
Python includes following dictionary methods −
Sr.No Methods with Description
.
1
dict.clear()

Removes all elements of dictionary dict

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

PAGE 105
www.icit.in Python programming

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

Chapter no 9. Date and Time

• 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

The datetime classes in Python are categorized into main 5 classes.

• date – Manipulate just date ( Month, day, year)


• time – Time independent of the day (Hour, minute, second, microsecond)
• datetime – Combination of time and date (Month, day, year, hour, second, microsecond)
• timedelta— A duration of time used for manipulating dates
• tzinfo— An abstract class for dealing with time zones

How to Use Date & DateTime Class


Step 1) Before you run the code for datetime, it is important that you import the date time modules as shown
in the screenshot below.

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

from datetime import date

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

Step 3) Next, we print the date and run the code.

The output is as expected.

Print Date using date.today()


date.today function has several properties associated with it. We can print individual
day/month/year and many other things

Day WeekDay Number

PAGE 108
www.icit.in Python programming

Monday 0

Tuesday 1

Let's see an example

Today's Weekday Number


The date.today() function also gives you the weekday number. Here is the Weekday Table which start with
Monday as 0 and Sunday as 6

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.

Python Current Date and Time: now() today()


Step 1) Like Date Objects, we can also use "DATETIME OBJECTS" in Python. It gives date along with time in
hours, minutes, seconds and milliseconds.

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

to print just the current time without the date.

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

Program to get current date and time using datetime now

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

Python code to demonstrate the working of calendar () and firstweeksday ()

Program

PAGE 114
www.icit.in Python programming

# importing calendar module for calendar


operations import calendar

# using calender to print calendar of year


# prints calendar of 2019
print ("The calender of year 2019
is : ") print
(calendar.calendar(2019,2,1,6))
#using firstweekday() to print starting day
number print ("The starting day number in
calendar is : ",end="") print
(calendar.firstweekday())

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

Python code to demonstrate the working of isleap() and leapdays ()

# importing calendar module for calendar


operations import calendar
# using isleap() to check if year is leap
or not if (calendar.isleap(2008)):
print ("The year is
leap") else : print ("The year
is not leap")
#using leapdays() to print leap days between
years print ("The leap days between 1950 and
2000 are : ",end="") print
(calendar.leapdays(1950, 2000))

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

# importing calendar module for calendar


operations import calendar
# using month() to display month of
specific year print ("The month 5th of
2019 is :") print
(calendar.month(2019,5,2,1))

Output

PAGE 117
www.icit.in Python programming

Python calendar module | isleap() method

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

Returns: Returns True if the year is a leap year, otherwise False.


Code #1:

# Python program to explain working of isleap() method

# importing calendar module


import calendar

# checking whether given year is leap or not


print(calendar.isleap(2016))
print(calendar.isleap(2001))

PAGE 118
www.icit.in Python programming

Output

Code #2: Explaining working of isleap() method.


Python code to demonstrate the working of isleap()
Program

# importing calendar module for calendar


operations import calendar

year = 2017

# calling isleap() method to


verify val =
calendar.isleap(year)
# checking the condition is True or
not if val == True:

PAGE 119
www.icit.in Python programming

# print 4th month of given leap year


calendar.prmonth(year, 4, 2, 1)

# Returned False, year is not a


leap else: print("% s is not
a leap year" % year)

Output

PAGE 120
www.icit.in Python programming

Chapter No 10. Functions

Defining Function

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

You can pass data, known as parameters, into a function.

A function can return data as a result.

Syntax of Function

def function_name(parameters):

"""docstring"""

statement(s)

Above shown is a function definition which consists of following components.

1. Keyword def marks the start of function header.


2. A function name to uniquely identify it. Function naming follows the same rules of
writing identifiers in Python.
3. Parameters (arguments) through which we pass values to a function. They are
optional.
4. A colon (:) to mark the end of function header.
5. Optional documentation string (docstring) to describe what the function does.
6. One or more valid python statements that make up the function body. Statements
must have same indentation level (usually 4 spaces).
7. An optional return statement to return a value from the function.

PAGE 121
www.icit.in Python programming

How Function works in Python?

Scope and Lifetime of variables

1.Scope of a variable is the portion of a program where the variable is recognized.


Parameters and

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

variables inside a function is as long as the function executes.

3.They are destroyed once we return from the function. Hence, a function does not
remember the

value of a variable from its previous calls.

Here is an example to illustrate the scope of a variable inside a function.

Program

def my_func():

x = 10

print("Value inside function:",x)

PAGE 122
www.icit.in Python programming

x = 20

my_func()

print("Value outside function:",x)

Output

Calling a Function

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

Program

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

my_function()

Output

PAGE 123
www.icit.in Python programming

Pass by Reference or pass by value

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

# Here x is a new reference to same list lst


def myFun(x):
x[0] = 20

# Driver Code (Note that lst is modified


# after function call.
lst = [10, 11, 12, 13, 14, 15]
myFun(lst);
print(lst)

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

# After below line link of x with previous


# object gets broken. A new object is assigned
# to x.
x = [20, 30, 40]

# Driver Code (Note that lst is not modified


# after function call.
lst = [10, 11, 12, 13, 14, 15]
myFun(lst);
print(lst)

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.

def student(firstname, lastname ='Mark', standard ='Fifth'):

print(firstname, lastname, 'studies in', standard, 'Standard')

We need to keep the following points in mind while calling functions:


1. In case of passing keyword argument, order of arguments is not important.
2. There should be only one value for one parameter.
3. The passed keyword name should match with the actual keyword name.
4. In case of calling function containing non-keyword arguments, order is important.

Example #1: Calling functions without keyword arguments

Program

def student(firstname, lastname ='Mark', standard ='Fifth'):


print(firstname, lastname, 'studies in', standard, 'Standard')

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

Example #2: Calling functions with keyword arguments

Program

def student(firstname, lastname ='Mark', standard ='Fifth'):


print(firstname, lastname, 'studies in', standard, 'Standard')

# 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

# Python program to demonstrate Keyword Arguments


def student(firstname, lastname):
print(firstname, lastname)

# Keyword arguments
student(firstname ='Geeks', lastname ='Practice')
student(lastname ='Practice', firstname ='Geeks')

Output

3. Variable length arguments:

We can have both normal and keyword variable number of arguments.

PAGE 130
www.icit.in Python programming

Program

# Python program to illustrate


# *args for variable number of arguments
def myFun(*argv):
for arg in argv:
print (arg)

myFun('Hello', 'Welcome', 'to', 'GeeksforGeeks')

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

Python code to illustrate cube of a number using lambda function

PAGE 132
www.icit.in Python programming

cube = lambda x: x*x*x


print(cube(7))

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 is a small anonymous function.

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

Why Use Lambda Functions?

The power of lambda is better shown when you use them as an anonymous function
inside another function.

Say you have a function definition that takes one argument, and that argument will be
multiplied with an unknown number:

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

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

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

Chapter No 11. Modules


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

How to import modules in Python?

We can import the definitions inside a module to another module or the interactive
interpreter in Python.

We use the import keyword to do this. To import our previously defined


module example we type the following in the Python prompt.

>>> import example

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

# import statement example

# to import standard module math

PAGE 139
www.icit.in Python programming

import math

print("The value of pi is", math.pi)

Output

Import with renaming

We can import a module by renaming

Program

PAGE 140
www.icit.in Python programming

# import module by renaming it

import math as m

print("The value of pi is", m.pi)

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.

Executing Modules as Scripts

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

Add this code at the end of your module −

Program

#!/usr/bin/python3

# Fibonacci numbers module

def fib(n): # return Fibonacci series up to n

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

The PYTHONPATH Variable

The PYTHONPATH is an environment variable, consisting of a list of directories. The


syntax of PYTHONPATH is the same as that of the shell variable PATH.

Here is a typical PYTHONPATH from a Windows system −

set PYTHONPATH = c:\python34\lib;

And here is a typical PYTHONPATH from a UNIX system −

set PYTHONPATH = /usr/local/lib/python

PAGE 143
www.icit.in Python programming

The dir( ) Function


The dir() built-in function returns a sorted list of strings containing the names defined by
a module.

Program

#!/usr/bin/python3

# Import built-in module math

import math

content = dir(math)

print (content)

Output

PAGE 144
www.icit.in Python programming

The globals() and locals() Functions


The globals() and locals() functions can be used to return the names in the global and
local namespaces depending on the location from where they are called.

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

The reload() Function


When a module is imported into a script, the code in the top-level portion of a module is
executed only once.

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

Importing module from a package

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.

from Game.Level import start

We can now call the function simply 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

from Game.Level.start import select_difficulty

Now we can directly call this function.

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.

Chapter No 12. Input-Output

PAGE 147
www.icit.in Python programming

What is a file?

File is a named location on disk to store related information. It is used to permanently


store data in a non-volatile memory (e.g. hard disk).

 File handling is an important part of any web application.


 Python has several functions for creating, reading, updating, and deleting files

File Handling

The key function for working with files in Python is the open() function.

The open() function takes two parameters; filename, and mode.

There are four different methods (modes) for opening a file:

"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

"t" - Text - Default value. Text mode

"b" - Binary - Binary mode (e.g. images)

Reading keyboard Input

Working of read() 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

Python code to illustrate read() mode

# Python code to illustrate read() mode

file = open("icit.txt", "r")

print (file.read())

Output

Opening and Closing Files

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

# a file named "geek", will be opened with the reading mode.

file = open('icit.txt', 'r')

# This will print every line one by one in the file

for each in file:

print (each)

Output

PAGE 150
www.icit.in Python programming

Working of append() close mode

Program

file = open('icit.txt','a')

file.write("This will add this line")

file.close()

Output

PAGE 151
www.icit.in Python programming

Files and Directory in python

What is Directory in Python?

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

Get Current Directory

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.

It is safer to use escape sequence when using the backward slash.

>>> os.chdir('C:\\Python33')

>>> print(os.getcwd())
C:\Python33

Making a New Directory

We can make a new directory using the mkdir() method.

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']

Renaming a Directory or a File

The rename() method can rename a directory or a file.

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']

Removing Directory or File

A file can be removed (deleted) using the remove() method.

Similarly, the rmdir() method removes an empty directory.

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

>>> import shutil

>>> shutil.rmtree('test')
>>> os.listdir()
[]

PAGE 155
www.icit.in Python programming

Chapter No.13 Exception Handling

What are exceptions in Python?

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:

print("can't divide by zero")

else:

print("Hi I am else block")

Output

PAGE 158
www.icit.in Python programming

The except statement with no exception

Python provides the flexibility not to specify the name of exception with the except
statement.

Consider the following example.

Program

try:
a = int(input("Enter a:"))

b = int(input("Enter b:"))

c = a/b;

print("a/b = %d"%c)

except:

print("can't divide by zero")

PAGE 159
www.icit.in Python programming

else:

print("Hi I am else block")

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

The finally block

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.

The syntax to use the finally block is given below.

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

def __init__(self, data):

self.data = data

def __str__(self):

return repr(self.data)

try:
raise ErrorInCode(2000)

except ErrorInCode as ae:

print("Received error:", ae.data)

Output

PAGE 164
www.icit.in Python programming

Chapter No 14. Oops concept

Python OOPs Concepts

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.

Major principles of object-oriented programming system are given below.

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

Inheritance is the most important aspect of object-oriented programming which simulates


the real world concept of inheritance. It specifies that the child object acquires all the
properties and behaviors of the parent object.

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.

It provides re-usability of the code.

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

Encapsulation is also an important aspect of object-oriented programming. It is used to


restrict access to methods and variables. In encapsulation, code and data are wrapped
together within a single unit from being modified by accident.

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

properties are acquired is known as a base class or parent class.

It provides re-usability of the code.

wrapped together within a single unit from being modified by accident.

Object-oriented vs Procedure-oriented Programming languages

PAGE 167
www.icit.in Python programming

Inde Object-oriented Programming Procedural Programming


x

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.

2. It makes the In procedural


development and programming, It is not
maintenance easier. easy to maintain the
codes when the project
becomes lengthy.

3. It simulates the real It doesn't simulate the


world entity. So real- real world. It works on
world problems can be step by step
easily solved through instructions divided
oops. into small parts called
functions.

4. It provides data hiding. Procedural language


So it is more secure doesn't provide any
than procedural proper way for data
languages. You cannot binding, so it is less
access private data secure.
from anywhere.

5. Example of object- Example of procedural


oriented programming languages are: C,
languages is C++, Fortran, Pascal, VB etc.
Java, .Net, Python, C#,
etc.

PAGE 168
www.icit.in Python programming

Creating classes in python

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"

def display (self):

print("ID: %d \nName: %s"%(self.id,self.name))

emp = Employee()

emp.display()

Output

PAGE 169
www.icit.in Python programming

Creating an instance of the class

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.

The syntax to create the instance of the class is given below.

<object-name> = <class-name>(<arguments>)
Program

class Employee:

id = 10;

name = "John"

def display (self):

print("ID: %d \nName: %s"%(self.id,self.name))

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

# First product method.


# Takes two argument and print their
# product
def product(a, b):
p = a * b
print(p)

# Second product method


# Takes three argument and print their
# product
def product(a, b, c):
p = a * b*c
print(p)

# Uncommenting the below line shows an error


# product(4, 5)

# This line will call the second product method


product(4, 5, 5)

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.

 A concept related to this is data hiding, which consists in hiding the


implementation details of a class. In this way the user interface of this class is clean
and more intuitive.

 In other programming languages, data hiding is done by creating private methods


and attributes, to which their external access to the function is blocked.

 In Python, however, the philosophy is slightly different “we are all consenting
adults” and therefore there are no particular restrictions on access.

 So there is nothing that can deprive an attribute or method in such a way as to


make it inaccessible to the outside of the classroom.

 n Python, the so-called weakly-private methods have a single underscore (_)


prefixed in their name. This prefix indicates the presence of a private method,
which should not be used outside the class. But this is just a convention and nothing
avoids the opposite. The only real effect it has is to avoid importing the method
when using the wording

 from modulename import *

 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

# A Python program to demonstrate that hidden


# members can be accessed outside a class
class MyClass:

# Hidden member of MyClass


__hiddenVariable = 10

# Driver code
myObject = MyClass()
print(myObject._MyClass__hiddenVariable)

Output

PAGE 175
www.icit.in Python programming

Chapter No.15 Regular Expression

What is Regular Expression?

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.

Identifiers Modifiers White space Escape


characters required

\d= any number (a digit) \d represents a \n = new line . + * ? [] $ ^


digit.Ex: \d{1,5} it will () {} | \
declare digit between
1,5 like 424,444,545 etc.

PAGE 176
www.icit.in Python programming

\D= anything but a number (a + = matches 1 or more \s= space


non-digit)

\s = space (tab,space,newline ? = matches 0 or 1 \t =tab


etc.)

\S= anything but a space * = 0 or more \e = escape

\w = letters ( Match $ match end of a string \r = carriage


alphanumeric character, return
including "_")

\W =anything but letters ^ match start of a string \f= form feed


( Matches a non-
alphanumeric character
excluding "_")

. = anything but letters | matches either or x/y -----------------


(periods)

\b = any character except for [] = range or "variance" ----------------


new line

\. {x} = this amount of -----------------


preceding code

Match and Replace

This function attempts to match RE pattern to string with optional flags.

Program

#!/usr/bin/python

import re

PAGE 177
www.icit.in Python programming

line = "Cats are smarter than dogs"

matchObj = re.match( r'(.*) are (.*?) .*', line, re.M|re.I)

if matchObj:
print ("matchObj.group() : ", matchObj.group())

print ("matchObj.group(1) : ", matchObj.group(1))

print ("matchObj.group(2) : ", matchObj.group(2))


else:

print ("No match!!")

Output

The search Function

PAGE 178
www.icit.in Python programming

This function searches for first occurrence of RE pattern within string with optional flags.

Here is the syntax for this function −

re.search(pattern, string, flags=0)

Program

#!/usr/bin/python
import re

line = "Cats are smarter than dogs";

searchObj = re.search( r'(.*) are (.*?) .*', line, re.M|re.I)

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

Search and Replace


One of the most important re methods that use regular expressions is sub.

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

phone = "2004-959-559 # This is Phone Number"

# Delete Python-style comments


num = re.sub(r'#.*$', "", phone)
print ("Phone Num : ", num)

# Remove anything other than digits


num = re.sub(r'\D', "", phone)
print ("Phone Num : ", num)
PAGE 180
www.icit.in Python programming

Output

Regular Expression Modifiers: Option Flags


Regular expression literals may include an optional modifier to control various aspects of
matching. The modifiers are specified as an optional flag. You can provide multiple
modifiers using exclusive OR (|),

Sr.No Modifier & Description


.

1 re.I

Performs case-insensitive matching.

2 re.L

Interprets words according to the current locale. This


interpretation affects the alphabetic group (\w and \
W), as well as word boundary behavior(\b and \B).

PAGE 181
www.icit.in Python programming

3 re.M

Makes $ match the end of a line (not just the end of


the string) and makes ^ match the start of any line
(not just the start of the string).

4 re.S

Makes a period (dot) match any character, including


a newline.

5 re.U

Interprets letters according to the Unicode character


set. This flag affects the behavior of \w, \W, \b, \B.

6 re.X

Permits "cuter" regular expression syntax. It ignores


whitespace (except inside a set [] or when escaped
by a backslash) and treats unescaped # as a
comment marker.

Regular Expression Patterns


Except for control characters, (+ ? . * ^ $ ( ) [ ] { } | \), all characters match
themselves. You can escape a control character by preceding it with a backslash.

Sr.No Pattern & Description


.

1 ^

Matches beginning of line.

2 $

Matches end of line.

PAGE 182
www.icit.in Python programming

3 .

Matches any single character except newline. Using m option


allows it to match newline as well.

4 [...]

Matches any single character in brackets.

5 [^...]

Matches any single character not in brackets

6 re*

Matches 0 or more occurrences of preceding expression.

7 re+

Matches 1 or more occurrence of preceding expression.

8 re?

Matches 0 or 1 occurrence of preceding expression.

9 re{ n}

Matches exactly n number of occurrences of preceding


expression.

10 re{ n,}

Matches n or more occurrences of preceding expression.

11 re{ n, m}

Matches at least n and at most m occurrences of preceding


expression.

12 a| b

PAGE 183
www.icit.in Python programming

Matches either a or b.

13 (re)

Groups regular expressions and remembers matched text.

14 (?imx)

Temporarily toggles on i, m, or x options within a regular


expression. If in parentheses, only that area is affected.

15 (?-imx)

Temporarily toggles off i, m, or x options within a regular


expression. If in parentheses, only that area is affected.

16 (?: re)

Groups regular expressions without remembering matched


text.

17 (?imx: re)

Temporarily toggles on i, m, or x options within parentheses.

18 (?-imx: re)

Temporarily toggles off i, m, or x options within parentheses.

19 (?#...)

Comment.

20 (?= re)

Specifies position using a pattern. Doesn't have a range.

21 (?! re)

PAGE 184
www.icit.in Python programming

Specifies position using pattern negation. Doesn't have a


range.

22 (?> re)

Matches independent pattern without backtracking.

23 \w

Matches word characters.

24 \W

Matches nonword characters.

25 \s

Matches whitespace. Equivalent to [\t\n\r\f].

26 \S

Matches nonwhitespace.

27 \d

Matches digits. Equivalent to [0-9].

28 \D

Matches nondigits.

29 \A

Matches beginning of string.

30 \Z

Matches end of string. If a newline exists, it matches just

PAGE 185
www.icit.in Python programming

before newline.

31 \z

Matches end of string.

32 \G

Matches point where last match finished.

33 \b

Matches word boundaries when outside brackets. Matches


backspace (0x08) when inside brackets.

34 \B

Matches nonword boundaries.

35 \n, \t, etc.

Matches newlines, carriage returns, tabs, etc.

36 \1...\9

Matches nth grouped subexpression.

37 \10

Matches nth grouped subexpression if it matched already.


Otherwise refers to the octal representation of a character cod

Character classes
Sr.No Example & Description
.

1 [Pp]ython

PAGE 186
www.icit.in Python programming

Match "Python" or "python"

2 rub[ye]

Match "ruby" or "rube"

3 [aeiou]

Match any one lowercase vowel

4 [0-9]

Match any digit; same as [0123456789]

5 [a-z]

Match any lowercase ASCII letter

6 [A-Z]

Match any uppercase ASCII letter

7 [a-zA-Z0-9]

Match any of the above

8 [^aeiou]

Match anything other than a lowercase vowel

9 [^0-9]

Match anything other than a digit

Repetition Cases

Sr.No Example & Description


.

PAGE 187
www.icit.in Python programming

1 ruby?

Match "rub" or "ruby": the y is optional

2 ruby*

Match "rub" plus 0 or more ys

3 ruby+

Match "rub" plus 1 or more ys

4 \d{3}

Match exactly 3 digits

5 \d{3,}

Match 3 or more digits

6 \d{3,5}

Match 3, 4, or 5 digits

Nongreedy repetition
This matches the smallest number of repetitions −

Sr.No. Example & Description

1 <.*>

Greedy repetition: matches "<python>perl>"

2 <.*?>

Nongreedy: matches "<python>" in "<python>perl>"

Grouping with Parentheses

PAGE 188
www.icit.in Python programming

Sr.No Example & Description


.

1 \D\d+

No group: + repeats \d

2 (\D\d)+

Grouped: + repeats \D\d pair

3 ([Pp]ython(, )?)+

Match "Python", "Python, python, python", etc.

Backreferences
This matches a previously matched group again −

Sr.No Example & Description


.

1 ([Pp])ython&\1ails

Match python&pails or Python&Pails

2 (['"])[^\1]*\1

Single or double-quoted string. \1 matches whatever the 1st


group matched. \2 matches whatever the 2nd group matched,
etc.

Alternatives

Sr.No Example & Description


.

1 python|perl

PAGE 189
www.icit.in Python programming

Match "python" or "perl"

2 rub(y|le))

Match "ruby" or "ruble"

3 Python(!+|\?)

"Python" followed by one or more ! or one ?

Anchors
This needs to specify match position.

Sr.No Example & Description


.

1 ^Python

Match "Python" at the start of a string or internal line

2 Python$

Match "Python" at the end of a string or line

3 \APython

Match "Python" at the start of a string

4 Python\Z

Match "Python" at the end of a string

5 \bPython\b

Match "Python" at a word boundary

6 \brub\B

PAGE 190
www.icit.in Python programming

\B is nonword boundary: match "rub" in "rube" and "ruby" but


not alone

7 Python(?=!)

Match "Python", if followed by an exclamation point.

8 Python(?!!)

Match "Python", if not followed by an exclamation point

Special Syntax with Parentheses

Sr.No Example & Description


.

1 R(?#comment)

Matches "R". All the rest is a comment

2 R(?i)uby

Case-insensitive while matching "uby"

3 R(?i:uby)

Same as above

4 rub(?:y|le))

Group only without creating \1 backreference

PAGE 191
www.icit.in Python programming

Chapter No 16. CGI (Common Gateway Interface)

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

CGI Architecture Diagram

CGI Environment Variables


All the CGI programs have access to the following environment variables. These variables
play an important role while writing any CGI program.

Sr.No Variable Name & Description


.

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

The length of the query information. It is available only for


POST requests.

3 HTTP_COOKIE

Returns the set cookies in the form of key & value pair.

4 HTTP_USER_AGENT

The User-Agent request-header field contains information


about the user agent originating the request. It is name of the
web browser.

5 PATH_INFO

The path for the CGI script.

6 QUERY_STRING

The URL-encoded information that is sent with GET method


request.

7 REMOTE_ADDR

The IP address of the remote host making the request. This is


useful logging or for authentication.

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

The method used to make the request. The most common


methods are GET and POST.

10 SCRIPT_FILENAME

PAGE 194
www.icit.in Python programming

The full path to the CGI script.

11 SCRIPT_NAME

The name of the CGI script.

12 SERVER_NAME

The server's hostname or IP Address

13 SERVER_SOFTWARE

The name and version of the software the server is running.

GET and POST Methods


Passing Information using GET method
The GET method sends the encoded user information appended to the page request. The
page and the encoded information are separated by the ? character as follows −

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.

Passing Information Using POST Method


A generally more reliable method of passing information to a CGI program is the POST
method. This packages the information in exactly the same way as GET methods, but
instead of sending it as a text string after a ? in the URL it sends it as a separate
message. This message comes into the CGI script in the form of the standard input.

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

# Import modules for CGI handling

import cgi, cgitb

# Create instance of FieldStorage

form = cgi.FieldStorage()

# Get data from fields

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 "<title>Hello - Second CGI Program</title>"

print "</head>"

print "<body>"

print "<h2>Hello %s %s</h2>" % (first_name, last_name)

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.

<form action = "/cgi-bin/hello_get.py" method = "post">

First Name: <input type = "text" name = "first_name"><br />

Last Name: <input type = "text" name = "last_name" />

PAGE 196
www.icit.in Python programming

<input type = "submit" value = "Submit" />

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

Passing Checkbox Data to CGI Program


Checkboxes are used when more than one option is required to be selected.

Here is example HTML code for a form with two checkboxes −

<form action = "/cgi-bin/checkbox.cgi" method = "POST" target = "_blank">

<input type = "checkbox" name = "maths" value = "on" /> Maths

<input type = "checkbox" name = "physics" value = "on" /> Physics

<input type = "submit" value = "Select Subject" />

</form>

The result of this code is the following form −


Select Subject
Maths Physics

Below is checkbox.cgi script to handle input given by web browser for checkbox button.

#!/usr/bin/python

# Import modules for CGI handling

import cgi, cgitb

# Create instance of FieldStorage

form = cgi.FieldStorage()

PAGE 197
www.icit.in Python programming

# Get data from fields

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 "<title>Checkbox - Third CGI Program</title>"

print "</head>"

print "<body>"

print "<h2> CheckBox Maths is : %s</h2>" % math_flag

print "<h2> CheckBox Physics is : %s</h2>" % physics_flag

print "</body>"

print "</html>"Passing Radio Button Data to CGI Program

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 −

<form action = "/cgi-bin/radiobutton.py" method = "post" target = "_blank">

PAGE 198
www.icit.in Python programming

<input type = "radio" name = "subject" value = "maths" /> Maths

<input type = "radio" name = "subject" value = "physics" /> Physics

<input type = "submit" value = "Select Subject" />

</form>

The result of this code is the following form −


Select Subject
Maths Physics

Below is radiobutton.py script to handle input given by web browser for radio button −

#!/usr/bin/python

# Import modules for CGI handling

import cgi, cgitb

# Create instance of FieldStorage

form = cgi.FieldStorage()

# Get data from fields

if form.getvalue('subject'):

subject = form.getvalue('subject')

else:

subject = "Not set"

print "Content-type:text/html\r\n\r\n"

print "<html>"

print "<head>"

print "<title>Radio - Fourth CGI Program</title>"

PAGE 199
www.icit.in Python programming

print "</head>"

print "<body>"

print "<h2> Selected Subject is %s</h2>" % subject

print "</body>"

print "</html>"

Passing Text Area Data to CGI Program


TEXTAREA element is used when multiline text has to be passed to the CGI Program.

Here is example HTML code for a form with a TEXTAREA box −

<form action = "/cgi-bin/textarea.py" method = "post" target = "_blank">

<textarea name = "textcontent" cols = "40" rows = "4">

Type your text here...

</textarea>

<input type = "submit" value = "Submit" />

</form>

The result of this code is the following form −

Submit

Below is textarea.cgi script to handle input given by web browser −

#!/usr/bin/python

# Import modules for CGI handling

import cgi, cgitb

# Create instance of FieldStorage

PAGE 200
www.icit.in Python programming

form = cgi.FieldStorage()

# Get data from fields

if form.getvalue('textcontent'):

text_content = form.getvalue('textcontent')

else:

text_content = "Not entered"

print "Content-type:text/html\r\n\r\n"

print "<html>"

print "<head>";

print "<title>Text Area - Fifth CGI Program</title>"

print "</head>"

print "<body>"

print "<h2> Entered Text Content is %s</h2>" % text_content

print "</body>"

Passing Drop Down Box Data to CGI Program


Drop Down Box is used when we have many options available but only one or two will be
selected.

Here is example HTML code for a form with one drop down box −

<form action = "/cgi-bin/dropdown.py" method = "post" target = "_blank">

<select name = "dropdown">

<option value = "Maths" selected>Maths</option>

<option value = "Physics">Physics</option>

</select>

<input type = "submit" value = "Submit"/>

PAGE 201
www.icit.in Python programming

</form>

The result of this code is the following form −


Maths Submit

Below is dropdown.py script to handle input given by web browser.

#!/usr/bin/python

# Import modules for CGI handling

import cgi, cgitb

# Create instance of FieldStorage

form = cgi.FieldStorage()

# Get data from fields

if form.getvalue('dropdown'):

subject = form.getvalue('dropdown')

else:

subject = "Not entered"

print "Content-type:text/html\r\n\r\n"

print "<html>"

print "<head>"

print "<title>Dropdown Box - Sixth CGI Program</title>"

print "</head>"

print "<body>"

print "<h2> Selected Subject is %s</h2>" % subject

PAGE 202
www.icit.in Python programming

print "</body>"

print "</html>"

Using Cookies in CGI


HTTP protocol is a stateless protocol. For a commercial website, it is required to maintain
session information among different pages. For example, one user registration ends after
completing many pages. How to maintain user's session information across all the web
pages?

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.

Cookies are a plain text data record of 5 variable-length fields −

 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

print "Set-Cookie:UserID = XYZ;\r\n"

PAGE 203
www.icit.in Python programming

print "Set-Cookie:Password = XYZ123;\r\n"

print "Set-Cookie:Expires = Tuesday, 31-Dec-2007 23:12:40 GMT";\r\n"

print "Set-Cookie:Domain = www.tutorialspoint.com;\r\n"

print "Set-Cookie:Path = /perl;\n"

print "Content-type:text/html\r\n\r\n"

...........Rest of the HTML Content....

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 −

key1 = value1;key2 = value2;key3 = value3....


Here is an example of how to retrieve cookies.

#!/usr/bin/python

# Import modules for CGI handling

from os import environ

import cgi, cgitb

if environ.has_key('HTTP_COOKIE'):

for cookie in map(strip, split(environ['HTTP_COOKIE'], ';')):

(key, value ) = split(cookie, '=');

if key == "UserID":

user_id = value

PAGE 204
www.icit.in Python programming

if key == "Password":

password = value

print "User ID = %s" % user_id

print "Password = %s" % password

This produces the following result for the cookies set by above script −

User ID = XYZ
Password = XYZ123

File Upload Example


To upload a file, the HTML form must have the enctype attribute set to multipart/form-
data. The input tag with the file type creates a "Browse" button.

<html>

<body>

<form enctype = "multipart/form-data"

action = "save_file.py" method = "post">

<p>File: <input type = "file" name = "filename" /></p>

<p><input type = "submit" value = "Upload" /></p>

</form>

</body>

</html>

The result of this code is the following form −

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

Here is the script save_file.py to handle file upload −

#!/usr/bin/python

import cgi, os

import cgitb; cgitb.enable()

form = cgi.FieldStorage()

# Get filename here.

fileitem = form['filename']

# Test if the file was uploaded

if fileitem.filename:

# strip leading path from file name to avoid

# directory traversal attacks

fn = os.path.basename(fileitem.filename)

open('/tmp/' + fn, 'wb').write(fileitem.file.read())

message = 'The file "' + fn + '" was uploaded successfully'

else:

message = 'No file was uploaded'

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("\\", "/" ))

How To Raise a "File Download" Dialog Box?


Sometimes, it is desired that you want to give option where a user can click a link and it
will pop up a "File Download" dialogue box to the user instead of displaying actual
content. This is very easy and can be achieved through HTTP header. This HTTP header is
be different from the header mentioned in previous section.

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

print "Content-Type:application/octet-stream; name = \"FileName\"\r\n";

print "Content-Disposition: attachment; filename = \"FileName\"\r\n\n";

# Actual File Content will go here.

fo = open("foo.txt", "rb")

str = fo.read();

print str

PAGE 207
www.icit.in Python programming

# Close opend

filefo.close()

Chapter No 17. Multithreading

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!

A thread contains all this information in a Thread Control Block (TCB):

 Thread Identifier: Unique id (TID) is assigned to every new thread

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

 Thread state: can be running, ready, waiting, start or done.

 Thread’s register set: registers assigned to thread for computations.

 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

Multiple threads can exist within one process where:

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

Multithreading is defined as the ability of a processor to execute multiple threads concurrently.

In a simple, single-core CPU, it is achieved using frequent switching between threads.

This is termed as context switching.

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

Python program to illustrate the concept of threading

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

# wait until thread 1 is completely executed


t1.join()
# wait until thread 2 is completely executed
t2.join()

# both threads completely executed


print("Done!")

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

class myThread (threading.Thread):


def __init__(self, threadID, name, counter):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.counter = counter
def run(self):
print ("Starting " + self.name)
# Get lock to synchronize threads
threadLock.acquire()
print_time(self.name, self.counter, 3)
# Free lock to release next thread
threadLock.release()

def print_time(threadName, delay, counter):


while counter:
time.sleep(delay)
print ("%s: %s" % (threadName, time.ctime(time.time())))
counter -= 1

threadLock = threading.Lock()
threads = []

PAGE 213
www.icit.in Python programming

# Create new threads


thread1 = myThread(1, "Thread-1", 1)
thread2 = myThread(2, "Thread-2", 2)

# Start new Threads


thread1.start()
thread2.start()

# Add threads to thread list


threads.append(thread1)
threads.append(thread2)

# Wait for all threads to complete


for t in threads:
t.join()
print ("Exiting Main Thread")

Output

PAGE 214
www.icit.in Python programming

Multithreaded Priority Queue


The Queue module allows you to create a new queue object that can hold a specific
number of items. There are following methods to control the Queue −

 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

 Microsoft SQL Server 2000

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

CRUD Operation in python

Step 1: Install Xampp Server

Step 2: After installation open Xampp server

PAGE 216
www.icit.in Python programming

Step 3: After Start Apache , mysql and tomcat server.

PAGE 217
www.icit.in Python programming

Step 4: Click on admin for MySQL server

Step 5: it shows http://localhost/phpmyadmin/

PAGE 218
www.icit.in Python programming

Step 6: Create new database

PAGE 219
www.icit.in Python programming

Step 7: Go pycharm window and write following code

import pymysql

conn = pymysql.connect(host="localhost", user="root",


password="", db="my_python")

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

#myCursor.execute("DELETE FROM names where id=2;")


#print(">Data Deleted!!!")

#myCursor.execute("UPDATE names SET name='nope' where id=1;")


PAGE 220
www.icit.in Python programming

#print(">Data Updated!!!!")
myCursor.execute("SELECT * FROM names;")
print(myCursor.fetchall(), end="\n")
conn.commit()
conn.close()

Output

((1, 'nope'), (2, 'sagar'))

Process finished with exit code 0

PAGE 221

You might also like