Class Xi Python
Class Xi Python
Class Xi Python
• Log on to www.python.org
• The home page looks as .....
Click on Download Python Now Hyperlink or
Download option from the side menu..
The Download Python Page appears. Click on the version of
Python that you want to install (Python 2.7 or Python 3.3)
Examples :-
>>>6+10
16
>>> (10+5)/3
5
Interactive Mode : Sequence of commands
Example 1 Example 2
• ^D (Ctrl+D) or
• Type quit ()
Script Mode
File New
Type Python program in a file
Save it . Default extension is .py
then use interpreter to execute the
contents from the file by
Can use Run option or press F5
type the function name at command
prompt
Variables / Objects in Python
Example
>>> flag=True
>>> type(flag)
<type 'bool'>
>>> flag=False
>>> type(flag)
<type 'bool'>
2. None
used to signify the absence of value / false in a situation
3.Sequence
5.Mapping
• an unordered data type for eg: dictonaries
Example :
>>>x=1256
Mutable and Immutable
Variables
Mutable Variable :
Immutable Variable :
x 5
>>>y=x
will make y refer to 5 of x
x
5
y
>>>x=x+y
RHS results to 10
value assigned to LHS (x)
x rebuilds to 10
x 10
y 5
Example
x = something # immutable type
y=x
print x
// some statement that operates on y
print x # prints the original value of x
x = something # mutable type
y=x
print x
// some statement that operates on y
print x # might print something different
Example
Immutable variable - x
x = 'foo'
y=x
print x # foo
y += 'bar'
print x # foo
Mutable Variable - x
x = [1, 2, 3]
y=x
print x # [1, 2, 3]
y += [3, 2, 1]
print x # [1, 2, 3, 3, 2, 1]
Points to remember about variables……
• Refer to an object
Arithmetic Assignment
Relational Logical
>>>17/5
3 >>>28/3
/ Division*
>>>17/5.0 9
3.4
Remainder/ >>>17%5 >>> 23%2
% 1
Modulo 2
>>>2**8
>>>2**3 256
** Exponentiation
8
>>>7.0//2 >>>3/ / 2
// Integer Division 1.0
3.0
Relational Operators
Symbol Description Example 1 Example 2
>>>7<10
True >>>‘Hello’< ’Goodbye’
>>> 7<5 False
< Less than False >>>'Goodbye'< 'Hello'
>>> 7<10<15 True
True
>>>7>5 >>>‘Hello’> ‘Goodbye’
True True
> Greater than >>>10<10 >>>'Goodbye'> 'Hello'
False False
>>> 2<=5 >>>‘Hello’<= ‘Goodbye’
True False
<= less than equal to >>> 7<=4 >>>'Goodbye' <= 'Hello'
False True
>>>10>=10 >>>’Hello’>= ‘Goodbye’
True True
>= greater than equal to >>>10>=12 >>>'Goodbye' >= 'Hello'
False False
>>>10!=11 >>>’Hello’!= ‘HELLO’
True True
! =, <> not equal to >>>10!=10 >>> ‘Hello’ != ‘Hello’
False False
>>>10==10 >>>“Hello’ == ’Hello’
True True
== equal to >>>10==11 >>>’Hello’ == ‘Good Bye’
False False
Logical Operators
Symbol Description
Added and assign back the result to left Will change the value of x to
+= >>>x+=2
operand 14
raw_input()
input ( )
raw_input()
• Syntax
raw_input ([prompt])
>>>Input1+Input2
>>>’DPS Gurgaon’
Addition of two numbers using raw_input( )
method
>>>Input1+Input2 d esired
t th e
is i s no
>>>’78100’ o ps! T h
O
ut.
outp
Addition of two numbers using
raw_input( ) method
>>>Input1+Input2
>>>178
raw_input() –Numeric data
• typecast the string data accepted from user to appropriate
Numeric type.
• e.g.
>>>y=int(raw_input(“enter your roll no”))
• E.g.
• >>>z = float(raw_input(“ enter the float value”)
input()
• Syntax
input ([prompt])
• Eg:
x= input (‘enter data:’)
Enter data: 2+ 1/2.0
Will supply 2.5 to x
Output
• For output in Python we use ‘print ’.
• Syntax:
print expression/constant/variable
• Example:
>>> print “Hello”
Hello
>>> print 5.5
5.5
>>> print 4+6
10
Functions
A function is named sequence of statement(s) that
performs a computation.
Eg:
>>> import math
• Syntax
>>> from modulename import functionname
[, functionname…..]
e.g
>>> from math import sqrt
Value = sqrt (25)
Some Functions from Math module
Name of the Description Example
function
Eg. Suppose we have two functions fn1 & fn2, such that
a= fn2 (x)
b= fn1 (a)
then call to the two functions can be combined as
b= fn1 (fn2 (x))
Eg:
degrees=270
math.sin (degrees/360.0 ° *2*math.pi)
Built in Function
• Built into Python and can be accessed by Programmer.
Examples
(i) >>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> range(1, 11)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
• Example
def area (radius):
a = 3.14*radius**2
return a
Function call
>>> print area (5)
Scope of variables
The part of the program where a variable can be used is
known as Scope of variable
Global Scope
Local Scope
Global Scope
With global scope, variable can be used
anywhere in the program
eg:
x=50
def test ( ):
print “inside test x is “, x
print “value of x is “, x
Output:
inside test x is 50
value of x is 50
Local Scope
With local scope, variable can be used only within the
function / block that it is created .
Eg:
X=50
def test ( ):
y = 20
print ‘value of x is ’, X, ‘ y is ’ , y
print ‘value of x is ’, X, ‘ y is ‘ , y
The next print statement will produce an error, because the variable y is
not accessible outside the def()
More on Scope of Variables
To access global variable inside the function prefix
keyword global with the variable
Eg:
x=50
def test ( ):
global x =5
y =2
print ‘value of x & y inside the function are ‘ , x , y
print ‘value of x outside function is ‘ ‘,
Eg.
def greet (message, times=1):
print message * times
Output:
Welcome
HelloHello
Fruitful and Void Functions
Fruitful functions return some value
Example:
>>>x=math.sqrt(25)
>>>print x
Void Functions returns no value
Example:
def greet (message, times=1):
print message * times
Docstrings
Enclosed in triple quotes.
What function does (without How it does) i.e. summary of its purpose
Type of parameters it take
Effect of parameter on behaviour of functions, etc
Eg:
def area (radius):
“””Calculates area of a circle.
area = radius**2
return area
DocString Conventions
The first line of docstring starts with capital
letter and ends with a period (.)
Second line is left blank (it visually
separates summary from other
description).
Other details of docstring start from 3rd line.
Control Flow Structure:
• Sequence
• Selection
- if
- if …else
- if…elif….else
• Looping
- for
- while
If Statement
• if x > 0:
print ‘x is positive’
• if x > y:
print ‘x is big’
else:
print ‘y is big’
• if x > 0:
print ‘x is positive’
elif x<0:
print ‘x is negative’
else:
print ‘x is zero’
Examples on if using logical operators
def largest():
a=input("Enter the first value")
b=input("Enter the second value")
c=input("Enter the third value")
while condition:
STATEMENT BLOCK 1
[else:
STATEMENT BLOCK 2]
while statement
• Eg:-
i=1
while (i <=10):
print i,
i +=1
else:
# to bring print control to next line
print “coming out of loop”
E.g.:
for letter in ‘Python’:
if letter == ‘h’:
break
print letter
Example - Break
"""A program to check whether a number is prime
or not"""
def prime():
number=input("Enter the value")
for i in range(2,number/2,1):
if(number % i == 0):
print " not prime"
break
else:
print " prime"
Continue
• Used to skip the rest of the statements of the
current loop block and to move to next
iteration, of the loop.
• Continue will return back the control to the
beginning of the loop.
• Can be used with both while & for.
Eg:
for letter in ‘Python’:
if letter == ‘h’:
continue
print letter,
Output
Pyton
Strings
• A set of characters enclosed in single /
double / triple quotes
Example:
>>> str='honesty'
>>> str[2]='p'
TypeError: 'str' object does not support item
assignment
Initializing Strings
Examples
>>>print ‘ A friend in need a friend indeed’
A friend in need a friend indeed
for loop
while loop.
Traversing a string
Using for loop Using while loop
A=’Welcome’ A=’Welcome’
>>>for i in A: >>>i=0
print i >>>while i<len(A):
W print A[i]
e i=i+1
l W
c e
o l
m c
e o
m
e
Strings operations
Operator Description Example
+ (Concatenation) The + operator joins the >>> ‘Save’+’Earth’
text on both sides of the ‘Save Earth’
operator
Slice[n : m]
Description
The Slice[n : m] operator extracts sub parts from the
strings.
Example
String A S a v e E a r t h
Positive Index 0 1 2 3 4 5 6 7 8 9
Negative Index -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
Examples
>>>print A[3:]
‘e Earth’
>>>print A[:3]
Sav
>>>print A[:]
‘Save Earth’
>>>print A[-2:]
‘th’
String Functions
Function Description Example
capitalize Returns the exact copy of the >>> str=’welcome’
string with the first letter in >>>print str.capitalize()
upper case
Welcome
lstrip() Returns the string after removing the >>> print str
space(s) on the left of the string. Save Earth
If a string is passed as argument to >>> str.lstrip()
the lstrip() function, it removes those 'Save Earth'
characters from the left of the string. >>> str='Teach India
Movement'
>>> print str.lstrip("Te")
ach India Movement
rstrip() Returns the string after removing the >>> str='Teach India
space(s) on the right of the string Movement’
>>> print str.rstrip()
Teach India Movement
A Sample Program
Program to count no of ‘p’ in the given string .
def lettercount():
word = 'python practice'
count = 0
for letter in word:
if letter == 'p':
count = count + 1
print count
Output
2
Lists
Lists
Like a String, List also is, sequence data type.
In a string we have only characters but a list
consists of data of multiple data types
It is an ordered set of values enclosed in
square brackets [].
We can use index in square brackets []
Values in the list are called elements or items.
A list can be modified, i.e. it is mutable.
Lists (contd.)
List index works the same way as String index :
>>>L=[1,2,3,4]
>>>L5=L # L5 is created as a copy of L
>>>L= list[(1,2,3,4)]
>>>print L
[1,2,3,4]
List Slices
New_list= L[start:stop:step]
L1=[1,2,3,4]
Print(L1[1:4:2])
Ans: [2,4]
• >>> L=[10,20,30,40,50]
Output
1234
Traversing a List (contd)
L=[1,2,3,4,5] L1=[1,2,3,4,5]
for i in L:for i in range (5):
print i, print L1 [i],
Output: Output:
1 2 3 4 51 2 3 4 5
append method
to add one element at the end of the list
Example:
>>> l=[1,2,3,4]
>>> print l
[1, 2, 3, 4]
>>> l.append(5)
>>> print l
[1, 2, 3, 4, 5]
extend Method
To add a list at the end of another list
Example
>>> l1=[10,20,30]
>>> l2=[100,200,300]
>>> l1.extend(l2)
>>> print l1
[10, 20, 30, 100, 200, 300]
>>> print l2
[100, 200, 300]
Updating list elements
Can update single or multiple elements
Example
>>>l1[1:2]=[90,100]
>>>print l1
[10,90,100,40,50] #2nd and 3rd element is updated
Use of + and * operators
+ operator – concatenates two lists
Example
>>> L1=[10,20,30]
>>>L2=[40,50]
>>>L3=L1+L2
>>>print L3
[10,20,30,40,50]
Use of + and * operators
* operator – repetition of lists
Example
>>> L1=[10,20,30]
>>>L2= L1*3
>>>print L2
[10,20,30,10,20,30,10,20,30]
>>>[‘Hi’]*4
[‘Hi’,’Hi’,’Hi’,’Hi’]
Deleting Elements from list
• Examples
>>> l=[10,20,30,40,50]
>>> l.pop() #pop without index deletes the last
element i.e. 50
50
>>> l.pop(1)
20 #deletes 2nd element i.e. 20
>>> l.remove(10) #deleted 10 i.e. 1st element
>>> print l
[30, 40]
Deleting Elements from list
• Example
>>> l=[1,2,3,4,5,6,7,8]
>>> del l[2:5] #deletes from 3rd to 6th element
>>> print l
[1, 2, 6, 7, 8]
insert method
used to add element(s) in between the list
Syntax
list.insert(index,item)
Example
>>> l=[10,20,30,40,50]
>>> l.insert(2,25)
>>> print l
[10, 20, 25, 30, 40, 50]
sort() and sorted() methods
sort(): Used to arrange the list in ascending order in place
Example:
>>> l=[10,8,4,7,3]
>>> l.sort()
>>> print l
[3, 4, 7, 8, 10]
Example
def test(L1):
for I in range(len(L1)):
L1[i]+=10
>>>x=[1,2,3,4,5]
>>>test(x)
>>>print x
[11,12,13,14,15]
An Example
n=input("Enter total number of elements")
l=range(n)
for i in range(n):
l[i]=input("enter element")
print "All elements in the list on the output screen"
for i in range(n):
print l[i]
Output
Enter total number of elements5
enter element10
enter element20
enter element30
enter element40
enter element50
All elements in the list on the output screen
10
20
30
40
50
DICTIONARIES
Dictionaries
• General form of a list that is created by using curly
brackets { }
• Index values can be any other data type and are called
keys.
Syntax:
Example
>>> D={}
>>> print D
{}
Adding elements in a Dictionary:
• By using ‘for-loop’.
Example
H={'Four': 'scanner', 'three': 'printer', 'two': 'Mouse', 'one':
'keyboard'}
for i in H:
print(I,”:”, H[i])
Output:
Four: scanner three: printer two: Mouse
one:keyboard
Appending values to the
dictionary
• To add only one element to the dictionary
Syntax:
Dictionaryname[key]=value
Example:
>>> a={"mon":"monday","tue":"tuesday","wed":"wednesday"}
>>> a["thu"]="thursday"
>>> print a
{'thu': 'thursday', 'wed': 'wednesday', 'mon': 'monday', 'tue':
'tuesday'}
>>>
Update()
( Merging Dictionaries)
update ( ) method merges the keys and values of one
dictionary into another and overwrites values of the same key.
Syntax:
Dic_name1.update(dic_name2)
Using this dic_name2 is added with Dic_name1.
Example:
>>> d1={1:10,2:20,3:30}
>>> d2={4:40,5:50}
>>> d1.update(d2)
>>> print d1
{1: 10, 2: 20, 3: 30, 4: 40, 5: 50}
del()
Syntax:
del dicname[key]
Example:
>>>A={"mon":"monday","tue":"tuesday","wed":"wednesda
y","thu":"thursday"}
>>> del A["tue"]
>>> print A
{'thu': 'thursday', 'wed': 'wednesday', 'mon': 'monday'}
>>>
Dictionary Functions
(i) cmp()
• used to check whether the given dictionaries are same or not.
(ii) len()
It returns number of key-value pairs in the given dictionary.
Syntax:
len(d) #d dictionary
Example:
(iii) clear()
It removes all items from the particular dictionary.
Syntax:
d.clear( ) #d dictionary
Example
>>> D={'mon':'Monday','tue':'Tuesday','wed':'Wednesday'}
>>> print D
{'wed': 'Wednesday', 'mon': 'Monday', 'tue': 'Tuesday'}
>>> D.clear( )
>>> print D
{}
Dictionary Functions(contd.)
(iV) has_key( )
(iV) items( )
It returns the content of dictionary as a list of key and value in
the form of a tuple.(not in any particular order)
Syntax:
D.items() # D dictionary
Example
>>>D={'sun':'Sunday','mon':'Monday','tue':'Tuesday','wed':'
Wednesday','thu':'Thursday','fri':'Friday','sat':'Saturday'}
>>> D.items()
[('wed', 'Wednesday'), ('sun', 'Sunday'), ('thu', 'Thursday'),
('tue', 'Tuesday'), ('mon', 'Monday'), ('fri', 'Friday'), ('sat',
'Saturday')]
Dictionary Functions(contd.)
(iV) values()
It returns the values from key-value pairs(not in any particular
order)
Syntax:
D.items() # D dictionary
Example
>>>D={'sun':'Sunday','mon':'Monday','tue':'Tuesday','wed':'
Wednesday','thu':'Thursday','fri':'Friday','sat':'Saturday'}
>>> D.values()
['Wednesday'), 'Sunday', 'Thursday’, 'Tuesday','Monday',
'Friday’, 'Saturday’]