Introduction
Python is a high level, interpreted general purpose programming language. Python can be used on
almost every operating system. It is a free and open source software.
Features
1. The code written in Python is automatically compiled to byte code and executed.
2. Python can be used as a scripting language
3. It has built in data types like string, lists, tuples etc
Python command line
We can execute python commands in command line. The “>>>” indicates python prompt.
Identifiers
Identifier is the name given to variable, function, class etc. An identifier can begin with an
alphabet(A-Z or a-z) or an underscore and can include any number of letters, digits or underscore.
Special characters are not allowed. Identifiers are case-sensitive.
Variables
A variable holds a value that may change. In python, variables do not need to be declared
before its use. When we initialize the variable , Python interpreter automatically does the
declaration process.
Variable initialization
Syntax
Variable=expression
eg: Year=2020
Data Types
Python has seven basic data types. They are
1. Numeric
2. String
3. List
4. Tuple
5. Dictionary
6. Boolean
7. Set
Numeric
Python numbers include integers, floating point numbers and complex numbers. They are
defined as int, float and complex class in python
int or integer is a whole number with or without sign.
Float or floating point number is a number with decimal point.
Complex numbers are written with j as the imaginary part
eg:
a=5
b=2.5
c=1+2j
Strings
A string is a group of characters enclosed with in single quotes or double quotes. In string,
first character has an index 0. Following operators can be applied to a string.
1. slice operator - [] and [:]
2. Concatenation operator +
3. Repetition operator *
Slice operator is used to extract substrings from the string.
Eg:
s=”Hello”
print (s[1]) # output e
print(s[0:2]) # output He
Concatenation operator is used to combine two strings
print(s+” World”) # Hello World
Repetition operator is used to repeat a string
print(s*3) # HelloHelloHello
List
A list is a collection which is ordered and changeable. A list contains items separated by commas
and enclosed within square brackets. Following operators can be applied to a list.
1. slice operator - [] and [:]
2. Concatenation operator +
3. Repetition operator *
first=[1,”one”,2,”two”]
second=[3,”three”,4, “four”]
print first # [1,”one”,2,”two”]
print first+second # [1,”one”,2,”two”,3,”three”,4, “four”]
print second *3 #[3,”three”,4, “four”, 3,”three”,4, “four”, 3,”three”,4, “four” ]
print first[0:2] # [1,”one”]
Tuple
A tuple is a collection which is ordered and unchangeable. A tuple contains items separated
by commas and enclosed with in parenthesis
Following operators can be applied to a tuple.
1. slice operator - [] and [:]
2. Concatenation operator +
3. Repetition operator *
first=(1,”one”,2,”two”)
second=(3,”three”,4, “four”)
print first # (1,”one”,2,”two”)
print first+second # (1,”one”,2,”two”,3,”three”,4, “four”)
print second *3 #(3,”three”,4, “four”, 3,”three”,4, “four”, 3,”three”,4, “four” )
print first[0:2] # (1,”one”)
Difference between tuple and list
List Tuple
Items are enclosed within square brackets Items are enclosed with in parenthesis
Mutable Immutable
Change and read Read only
first=[1,”one”,2,”two”] first=(1,”one”,2,”two”)
Dictionary
A dictionary is a collection which is unordered, changeable and indexed. Dictionary items
are written in keys and values format. Items are enclosed in the curly-braces and separated by the
commas. A colon is used to separate key from value. A key inside the square brackets is used for
accessing the dictionary items
eg:
d={1:”first”,2:”second”}
d[3]=”third”
print d # {1:”first”,2:”second”,3:”third”}
print [Link]() #{1,2,3}
print [Link]() #{“first”,”second”,”third”}
Set
A set is a collection which is unordered and unindexed. Items are enclosed in the curly
braces and separated by commas.
s={“one”,”two”,”three”}
We cannot access items in a set by referring to an index, since sets are unordered.
Boolean
True and False are known as boolean data. Boolean variables can store boolean data
Operators
Python operators are categorised into the following 7 types.
1. Arithmetic operators
2. Relational operators
3. Assignment operators
4. Logical operators
5. Bitwise operators
6. Membership operators
7. Identity operators
Arithmetic operators
These operators are used to perform arithmetic operations such as addition, subtraction etc
+ Addition
- Subtraction
* Multiplication
/ Division
** Exponential operator to calculate power(5**2=25)
% Modulus operator to find remainder (5%2=1)
// Floor division operator to find the quotient and remove the fractional part (5//2=2)
Relational Operators
These operators are used to compare values. The result of these operators is always a
Boolean value.
== Equal to
!= or <> not equal to
> greater than
< less than
>= greater than or equal to
<= less than or equal to
Assignment Operators
Assignment operators are used to assign values to variables
Bitwise Operators
These operators perform bit level operation on operands
& - Bitwise AND
| - Bitwise OR
Logical Operators
Logical operators are used to combine conditional statements.
Membership Operators
Membership Operators are used to check whether an item is present in string, list or tuple.
in – Return true, if item is in list, string or tuple. Otherwise returns false
not in - Return true, if item is not in list, string or tuple. Otherwise returns false
eg:
x=10
y=12
list=[21,13,10,17]
x in list // returns true
y in list // returns false
Identity Operators
These operators are used to check whether both operands are same or not.
is – Returns true, if the operands are same, otherwise returns false
not is - Returns true, if the operands are not same, otherwise returns false
Precedence of operators
**
* / % //
+-
< <= > >=
<> !=
= %= /= //= -= += *= **=
is not is
in not in
not or and
Most of the operators in Python have left to right associativity. ** operator is right to left
associative.
input()
input() function is used to read a string from the keyboard.
General form
variable=input(message)
eg:
name=input(“Enter the name”)
print()
print() function prints the specified message to the screen.
General form
print(object(s), sep=separator, end=end)
where
object- any object we want to print
sep=separator Optional. Specify how to separate the objects, if there is more than one. Default is
space
end=end Optional. Specify what to print at the end. Default is '\n' (line feed)
Branching statements
if, if else and if –elif are branching statements in Python.
if statement.
If is a simple branching statement in Python. Its general form
if condition :
statements
where colon separates if statement from the body. The line after the column must be
indented. All lines indented the same amount after the colon will be executed whenever the boolean
expression is true.
Eg:
if n<0 :
print “negative”
print “end”
if else statement
It is a two way branching statement.
General form
if condition:
statement block1
else:
statement block2
First evaluates the condition. If it is true statement block1 will be executed, otherwise statement
block2 will be executed.
Eg:
if n<0:
print ‘Given no. is negative’
else:
print ‘Given no. is not negative’
if – elif statement
It is a multiway decision statement. Its general form
if condition1:
statement block1
elif condition2:
statement block2
elif condition3:
statement block3
--- ----
else:
default block
In this conditions are evaluated from the top downward. As soon as a true condition is found , the
statement block associated with it is executed and rest of the statement blocks are skipped. If all
conditions are false, then default block will be executed.
Eg:
if a<0:
print ‘Given number is negative’
elif a>0:
print ‘Given number is positive’
else:
print ‘Given number is zero’
Looping statements
Looping is a mechanism in which group of statements are repeatedly executed based on a condition.
while and for are two important looping statements in Python.
While statement
while is looping statement in python. Its general form
while condition:
statement block1
else:
statement
First evaluates the condition. If it is true, then statement block1 will be executed. This will continue
until the condition becomes false. Else part is optional. The else part is executed when the condition
becomes false.
i=1
while i<=3:
print (i)
i=i+1
else:
print 'end'
o/p
1
2
3
end
for loop
The python for loop is an iterator based for loop. It is used with list, tuple, dictionary, set or string
Syntax
for loop_variable in sequence:
body of loop
else:
statement
Loop_ variable takes the value of the item inside the sequence on each iteration. Loop continues
until we reach the last item in the sequence. Else part is optional . The else part is executed when
the loop is finished.
Eg:
numbers=[1,2,3,4,5]
for i in numbers:
print i
else:
print ‘end’
Type casting
In some situations, we want to specify a type to value of a variable. This can be done with casting.
Python type casting functions are
int()- Convert value to an integer
float()- Convert value to floating point
str() - Convert a value to string
Built in functions and Modules
The python interpreter has a number of built-in functions. They are loaded automatically as the
interpreter starts and are always available.
Eg: print(), input(), int() etc
In addition to these functions a large number of pre-defined functions are available as a part of
library. These functions are defined in modules.
A module is a file containing definitions of functions, classes, variables, constants or any
other python objects. Import statement is used to include modules in our programming
eg:
import math
print([Link](2,4))
print([Link](25))
User defined functions
In python, user defined functions are defined using the def keyword
general form
def function_name(arguments):
Function body
return
The function body always start with a colon. After writing the statement , the function body is
ended with a return statement. Return statement is used to return a value to a calling function.
Its general form
return expression;
return is an optional statement.
Eg:
def sum(a,b):
s=a+b
return s
range()
The range() function is a built-in function. It returns a sequence of numbers , starting from 0
by default, and increments by 1 and ends at a specified number.
Eg:
for x in range(6):
print(x)
This will print values from 0 to 5.
o/p
0
1
2
3
4
5
We can specify begin and end in range() functions
eg:
for x in range(2,6):
print(x)
o/p
2
3
4
5
We can also specify step value as third argument in range function
for x in range (2,15,3)
print(x)
o/p
2
5
8
11
14
Strings
Strings are group of characters enclosed with in asingle quotation marks or double quotation marks.
Square brackets can be used to access elements of the string
a= “Hello World”
print(a[1])
o/p
e
Slice operator {:} is used to extract substring from a string
print(a[2:5]) o/p llo
strip() - It removes any white space from the beginning or the end of the string
a=” Hello “
print([Link]())
o/p
“Hello”
len() - It is used to find the length of a string
a=”hello”
print(len(a))
lower() - It converts all the uppercase letters into lowercase in a string
a=”HEllo”
print([Link]())
upper() - It converts all the lowercase letters into uppercase in a string
a =”Hello”
print([Link]())
split() - It splits string into substrings according to the separator.
a=”Hello, world”
print([Link](“,”))
[‘Hello’,’World’]
join()- It returns a string which is the concatenation of the strings in the sequence with a separator
[Link](sequence)
s1=”1234”
s2=”+”
s3=[Link](s1)
print (s3)
o/p
1+2+3+4
isalpha()- It returns true if all the characters in the string are alphabets. If not , it returns false
[Link]()
name=”Hello”
print ([Link]())
isdigit() - It returns true if all the characters in a string are digits. If not , it returns false
[Link]()
n=”123”
print([Link]())
islower()- It returns true if all alphabets in a string are lower case letters, otherwise false
[Link]()
eg:
isupper()- It returns true if all alphabets in a string are uppercase, otherwise false
[Link]()
count()- It returns the number of occurrences of a substring in the given string
syntax
[Link](substring, start, end)
s=”Ptyhon is . It is”
c=[Link](“is”)
Tuples
A tuple contains items separated by commas and enclosed with in parenthesis. We can take
items in a tuple by using for loop.
fr=(“apple”,”orange”,”banana”)
for x in fr:
print(x)
We can compare two tuples with relational operators.
a=(5,6)
b=(1,4)
if a>b :
print ‘a is bigger’
else:
print “ b is bigger”
in keyword is used to check whether given item is present in the tuple
fr=(“apple”,”orange”,”banana”)
if “apple” in fr:
print “Yes”
else:
print “No”
cmp() - It is used to compare items of two tuples. Cmp() function returns following values
0 - both tuples are equal
1- first tuple is greater than second tuple
-1 – first tuple is less than second tuple
max()- It returns the elements from the tuple with maximum value
a=(1,2,3)
print(max(a))
min()- It returns the elements from the tuple with minimum value
a=(1,2,3)
print(min(a))
len()- It returns the number of elements in the tuple
a=(1,2,3)
print(len(a))
tuple() - It converts a list of items into tuples
a=[1,2,3]
print(tuple(a))
o/p
(1,2,3)
count() - It returns the number of occurrences of a given element in the tuple
a=(1,2,3,2)
print([Link](2))
List
It contains items separated by commas and enclosed within square brackets.
len()- It returns the number of elements in the list
a=[1,2,3]
print (len(a))
max()- It returns the elements from the list with maximum value
a=[1,2,3]
print (max(a))
min() - It returns the elements from the list with minimum value
a=[1,2,3]
print (min(a))
insert() - It inserts an object into list at the specified index.
A=[1,2,3]
[Link](1,100)
print a
o/p
[1,100,2,3]
append()- It appends an element into the list
a=[1,2,3]
[Link](100)
print a
o/p
[1,2,3,100]
sort()- It sorts elements in the list
a=[2,8,5]
a,sort()
print a
remove() - It removes an item from the list
a=[2,8,5]
[Link](8)
print(a)
pop() - It removes and returns the last element from the list
a=[2,8,5]
print([Link]())
Dictionary
A dictionary is a collection which is unordered , changeable and indexed.
d={1:”first”, 2:”second” }
get() - It returns the values of the item with the specified keyname
[Link](1)
update()- It inserts the specified items into the dictionary
d. update({3:”third”})
pop()- It removes item with the specified key name
[Link](2)
popitem() - It removes the item with the specified key name
[Link]()
del keyword removes the item with the specified key name
del d[1]
The del keyword can also delete the dictionary completely
del d
clear()- It empties the dictionary
[Link]()
len()- It returns the number of items in the dictionary
len(d)
cmp()- It compares the items of two dictionaries
cmp(d1,d2)
sorted()- It returns the sorted list of keys
sorted(d)
print all key names in the dictionary by using following statement
for x in d:
print(x)
print all values in the dictionary by using following statements
for x in d:
print(d[x])
CGI programming
It stands for common Gateway interface. GUI programs run on the web server. We can transfer
values to a CGI scripts through GET or POST methods
In GET method values are appended to the URL in name/value pairs
In POST method values are appended to the body of the HTTP request. It is not shown in
URL
Unit 9
Programming in Python
Features of Python
Python provides lots of features that are listed below.
1) Easy to Learn and Use
Python is easy to learn and use. It is developer-friendly and high level
programming language.
2) Expressive Language
Python language is more expressive means that it is more
understandable and readable.
3) Interpreted Language
Python is an interpreted language i.e. interpreter executes the code line
by line at a time. This makes debugging easy and thus suitable for beginners.
4) Cross-platform Language
Python can run equally on different platforms such as Windows, Linux,
Unix and Macintosh etc. So, we can say that Python is a portable language.
5) Free and Open Source
Python language is freely available at official web address. The source-
code is also available. Therefore it is open source.
6) Object-Oriented Language
Python supports object oriented language and concepts of classes and
objects come into existence.
7) Extensible
It implies that other languages such as C/C++ can be used to compile
the code and thus it can be used further in our python code.
8) Large Standard Library
Python has a large and broad library and provides rich set of module
and functions for rapid application development.
9) GUI Programming Support
Graphical user interfaces can be developed using Python.
10) Integrated
It can be easily integrated with languages like C, C++, JAVA etc.
Standard data types
A variable can hold different types of values. For example, a person's
name must be stored as a string whereas its id must be stored as an integer.
Python provides various standard data types that define the storage
method on each of them. The data types defined in Python are given below.
1. Numbers
2. String
3. List
4. Tuple
5. Dictionary
6. Set
7. Boolean
1. Numbers
Number stores numeric values. Python creates Number objects when a
number is assigned to a variable. For example;
1. a=3, b=5 #a and b are number objects
Python supports 4 types of numeric data.
1. int (signed integers like 10, 2, 29, etc.)
2. long (long integers used for a higher range of values like 908090800L, -
0x1929292L, etc.)
3. float (float is used to store floating point numbers like 1.9, 9.902, 15.2,
etc.)
4. complex (complex numbers like 2.14j, 2.0 + 2.3j, etc.)
Python allows us to use a lower-case L to be used with long integers.
However, we must always use an upper-case L to avoid confusion.
A complex number contains an ordered pair, i.e., x + iy where x and y denote
the real and imaginary parts respectively).
2. String
The string can be defined as the sequence of characters represented in
the quotation marks. In python, we can use single, double, or triple quotes to
define a string.
String handling in python is a straightforward task since there are
various inbuilt functions and operators provided.
In the case of string handling, the operator + is used to concatenate two
strings as the operation "hello"+" python" returns "hello python".
The operator * is known as repetition operator as the operation "Python " *2
returns "Python Python ".
The following example illustrates the string handling in python.
1. str1='hello python’ #string str1
2. str2= ' how are you' #string str2
3. print(str1[0:2]) #printing first two character using slice operator
4. print (str1[4]) #printing 4th character of the string
5. print (str1*2) #printing the string twice
6. print(str1 + str2) #printing the concatenation of str1 and str2
Output:
he
o
hello python hello python
hello python how are you
List
Lists are similar to arrays in C. However; the list can contain data of different
types. The items stored in the list are separated with a comma (,) and
enclosed within square brackets [].
We can use slice [:] operators to access the data of the list. The
concatenation operator (+) and repetition operator (*) works with the list in the
same way as they were working with the strings.
Consider the following example.
1. l = [1 , "hi" , "python", 2]
2. print (l[3:]);
3. print (l[0:2]);
4. print (l);
5. print(l+l);
6. print (l*3);
Output:
[2]
[1, 'hi']
[1, 'hi', 'python', 2]
[1, 'hi', 'python', 2, 1, 'hi', 'python', 2]
[1, 'hi', 'python', 2, 1, 'hi', 'python', 2, 1, 'hi', 'python', 2]
Tuple
A tuple is similar to the list in many ways. Like lists, tuples also contain
the collection of the items of different data types. The items of the tuple are
separated with a comma (,) and enclosed in parentheses ().
A tuple is a read-only data structure as we can't modify the size and
value of the items of a tuple.
Let's see a simple example of the tuple.
1. t = ("hi" , "python", 2)
2. print (t[1:]);
3. print (t[0:1]);
4. print (t);
5. print (t + t);
6. print ( t * 3);
7. print (type(t))
8. t[2] = "hi";
Output:
('python', 2)
('hi',)
('hi', 'python', 2)
('hi', 'python', 2, 'hi', 'python', 2)
('hi', 'python', 2, 'hi', 'python', 2, 'hi', 'python', 2)
<type 'tuple'>
Traceback (most recent call last):
File "[Link]", line 8, in <module>
t[2] = "hi";
TypeError: 'tuple' object does not support item assignment
Dictionary
Dictionary is an ordered set of a key-value pair of items. It is like an
associative array or a hash table where each key stores a specific value. Key
can hold any primitive data type whereas value is an arbitrary Python object.
The items in the dictionary are separated with the comma and enclosed
in the curly braces {}.
Consider the following example.
1. d = {1:'Jimmy', 2:'Alex', 3:'john', 4:'mike'};
2. print("1st name is "+d[1]);
3. print("2nd name is "+ d[4]);
4. print (d);
5. print ([Link]());
6. print ([Link]());
Output:
1st name is Jimmy
2nd name is mike
{1: 'Jimmy', 2: 'Alex', 3: 'john', 4: 'mike'}
[1, 2, 3, 4]
['Jimmy', 'Alex', 'john', 'mike']
Input Statement
The input() function allows user input.
input(prompt)
Use the prompt parameter to write a message before the input:
x = input('Enter your name:')
Output Statement
The Python print statement is often used to output variables.
To combine both text and a variable, Python uses the + character:
Example 1:
x=5
print(x)
Example2 :
x = "awesome"
print("Python is " + x)
We n also use the + character to add a variable to another variable:
x=5
y = 10
print(x + y) --- will print 15
x = "Python is "
y = "awesome"
z= x+y
print(z) --will print Python is awesome
String Functions
Function Description
len(string) returns the length(number of characters) in the string
isalpha(string) Returns True if at least one character is alphabetic
otherwise False
isdigit(string) Returns True if the string contains only digits
otherwise False
isnumeric(string) Returns True if the string contains only numeric
characters otherwise False
islower(string) Returns True if the string contains only lower case
characters otherwise False
isupper(string) Returns True if the string contains only upper case
characters otherwise False
lower(string) Converts a string to all lower case letters
upper(string) Converts a string to all uppercase letters
string slicing
stringname[a:b] – display string from a to b(excluding b)
Control statements
if..elif..else statements
Simple if statement
Syntax
if expression :
statement
Eg:
if a >b :
print a, “is largest”
if ... else statement
Syntax
if expression :
statement 1
else :
statement 2
Eg.
if a>b :
print a,”is largest”
else :
print b,”is largest”
Qn. Write a python program to read a number and check whether it is odd or
even.
a=input("enter a number")
if a%2 == 0 :
print a,"is even"
else :
print a,"is odd"
Qn. Write a python program to read two numbers and find its largest.
a=input("Enter first number")
a=input("Enter second number")
if a>b :
print a,"is largest"
else :
print b,"is largest"
while loop
Syntax
while expression :
statements
else :
statements
Eg. Write a python program to print fist 10 natural numbers
i=1
while i<=10 :
print i
i=i+1
for loop
syntax
for variable in set_of_values :
block1
else :
block2
Qn. Write a python program to display first 10 natural numbers using for loop
for i in range(1,11) :
print i
Note:
range() function is a built in function that help us to iterate a sequence of
numbers.
Eg.1.
range (10)
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
Eg.2.
range(3,9)
[ 3, 4, 5, 6, 7, 8 ]
Eg.3.
range (3, 40, 5)
[ 3, 8, 13, 18, 23, 28, 33, 38 ]
LQ. 29. Write a python program to print the fibonacci series upto n terms
a=1
b=1
n=input("Enter the number of terms")
print a,'\n',b
for i in range (2,n) :
c=a+b
print c
a=b
b=c
30. Write a python program to read a number and check whether it is prime or
not.
n=input('Enter a number')
prime=True
for i in range(2,n/2) :
if n%i == 0 :
prime=False
if prime :
print n,'is prime'
else :
print n,'is not prime'
List methods
Method Description
len() Returns the length of a list
max(list) Returns the value of the item which has maximum
value in the list
min(list) Returns the value of the item which has minimum
value in the list
[Link](item) Adds the item at the end of the list
[Link](item) Returns the number of times the item occurs in the
list
[Link](item) Returns the index of the item in the list
[Link](index,item) Inserts the given item on to the given index number
while the elements in the list take one right shift
[Link](item) Removes the given item from the list
Tuple functions
len(tuple) Returns the length of tuple
max(tuple) Returns the largest value among the elements in the
tuple
min(tuple) Returns the smallest value among the elements in the
tuple
[Link](item) Returns index of the item in tuple
Dictionary functions
Function Description
len(dict) Returns the number of items in the list
[Link]() Returns the list of entire keys in the dictionary
[Link]() Returns the entire key value pair in the dictionary
[Link]() Returns all the values in the dictionary
31. Write a Python program to implement list operations (length, insert,
append etc.)
# program using list
print " create a list with fruits"
list1 = ["apple", "banana", "cherry"]
print list1
print "change the item in second position to grapes"
list1[2] = "grapes"
print(list1)
print("the number of items in the list",len(list1))
print "add orange to the list"
[Link]("orange")
print(list1)
print "insert mango at position 1"
[Link](1, "mango")
print(list1)
print "remove banana from the list"
[Link]("banana")
print "remove the item 0 from the list"
del list1[0]
print(list1)
32. Write a Python program to implement tuple operations (length, count,
index )
# program using tuple.
print "create a tuple with three items one, two and three"
tuple1 = ("one", "two", "three")
print tuple1
print(tuple1[1])
print "You can loop through the tuple items by using a for loop."
for x in tuple1:
print(x)
print " to check two in the list"
if "two" in tuple1:
print("Yes, 'two' is in the tuple")
print "the number of items in the list",[Link]("two")
print "the index of three is ", [Link]("three")
33. Write a Python program to implement dictionary operations (length,
modify, delete)
#program using dictionary
dict1 = { 1: "one", "two": 2, 3.0: "three", 4:"four"}
print(dict1)
print "Get the value of the 3.0 key"
print dict1[3.0]
print "change the value of a specific item by referring to its key name"
dict1[1] = 1
print "Loop Through a Dictionary"
for x in dict1:
print(x)
print "Loop through both keys and values, by using the items() function:"
for x, y in [Link]():
print(x, y)
if 4 in dict1:
print("Yes, 4 is one of the keys in the dict1 dictionary")
print "the number of items in the dictionary:",len(dict1)
dict1["five"] = 5
print(dict1)