Python Tutorial Class-Xll PDF
Python Tutorial Class-Xll PDF
INTRODUTION TO PYTHON
1.1 Introduction:
General-purpose Object Oriented Programming language.
High-level language
Developed in late 1980 by Guido van Rossum at National Research Institute for
Mathematics and Computer Science in the Netherlands.
It is derived from programming languages such as ABC, Modula 3, small talk, Algol-
68.
It is Open Source Scripting language.
It is Case-sensitive language (Difference between uppercase and lowercase letters).
One of the official languages at Google.
Example:
>>>6+3
Output: 9
Note: >>> is a command the python interpreter uses to indicate that it is ready. The
interactive mode is better when a programmer deals with small pieces of code.
To run a python file on command line:
exec(open(“C:\Python33\python programs\program1.py”).read( ))
ii. Script Mode: In this mode source code is stored in a file with the .py extension
and use the interpreter to execute the contents of the file. To execute the script by the
interpreter, you have to tell the interpreter the name of the file.
Example:
if you have a file name Demo.py , to run the script you have to follow the following
steps:
2.2 TOKENS
Token: Smallest individual unit in a program is known as token.
There are five types of token in python:
1. Keyword
2. Identifier
3. Literal
4. Operators
5. Punctuators
as elif if or yield
All the keywords are in lowercase except 03 keywords (True, False, None).
3. Literal: Literals are the constant value. Literals can be defined as a data that is given in
a variable or constant.
Literal
String Literal
Numeric Boolean Special
Collections
Eg.
5, 6.7, 6+9j
String literals can be formed by enclosing a text in the quotes. We can use both single as
well as double quotes for a String.
Eg:
"Aman" , '12345'
C. Boolean literal: A Boolean literal can have any of the two values: True or False.
None is used to specify to that field that is not created. It is also used for end of lists in
Python.
E. Literal Collections: Collections such as tuples, lists and Dictionary are used in Python.
4. Operators: An operator performs the operation on operands. Basically there are two
types of operators in python according to number of operands:
A. Unary Operator
B. Binary Operator
5. Separator or punctuator : , ; , ( ), { }, [ ]
B. Statements
A line which has the instructions or expressions.
C. Expressions:
A legal combination of symbols and values that produce a result. Generally it produces a value.
D. Comments: Comments are not executed. Comments explain a program and make a
program understandable and readable. All characters after the # and up to the end of the
physical line are part of the comment and the Python interpreter ignores them.
i. Single line comment: This type of comments start in a line and when a line ends, it is
automatically ends. Single line comment starts with # symbol.
Example: if a>b: # Relational operator compare two values
ii. Multi-Line comment: Multiline comments can be written in more than one lines. Triple
quoted ‘ ’ ’ or “ ” ”) multi-line comments may be used in python. It is also known as
docstring.
Example:
‘’’ This program will calculate the average of 10 values.
First find the sum of 10 values
and divide the sum by number of values
‘’’
Creating a variable:
Example:
x=5
y = “hello”
Variables do not need to be declared with any particular type and can even change type after
they have been set. It is known as dynamic Typing.
x = 4 # x is of type int
x = "python" # x is now of type str
print(x)
Example: x=y=z=5
You can also assign multiple values to multiple variables. For example −
x , y , z = 4, 5, “python”
4 is assigned to x, 5 is assigned to y and string “python” assigned to variable z respectively.
x=12
y=14
x,y=y,x
print(x,y)
Now the result will be
14 12
Note: Expressions separated with commas are evaluated from left to right and assigned in same
order.
If you want to know the type of variable, you can use type( ) function :
Example:
x = int(1) # x will be 1
y = int(2.8) # y will be 2
z = int("3") # z will be 3
float( ) - constructs a float number from an integer literal, a float literal or a string literal.
Example:
str( ) - constructs a string from a wide variety of data types, including strings, integer
literals and float literals.
Example:
Data Types
Primitive Collection
Data Type Data Type
Number String
int
float
complex
Example:
w=1 # int
y = 2.8 # float
z = 1j # complex
x=1
y = 35656222554887711
z = -3255522
Boolean: It has two values: True and False. True has the value 1 and False has the
value 0.
Example:
>>>bool(0)
False
>>>bool(1)
True
>>>bool(‘ ‘)
False
>>>bool(-34)
True
>>>bool(34)
True
float : Float or "floating point number" is a number, positive or negative, containing one
or more decimals. Float can also be scientific numbers with an "e" to indicate the power
of 10.
Example:
x = 1.10
y = 1.0
z = -35.59
a = 35e3
b = 12E4
c = -87.7e100
PYTHON- Class-XI, KV ONGC VADODARA Page 16
complex : Complex numbers are written with a "j" as the imaginary part.
Example:
>>>x = 3+5j
>>>y = 2+4j
>>>z=x+y
>>>print(z)
5+9j
>>>z.real
5.0
>>>z.imag
9.0
Real and imaginary part of a number can be accessed through the attributes real and imag.
RESULT
OPERATOR NAME SYNTAX
(X=14, Y=4)
+ Addition x+y 18
_ Subtraction x–y 10
* Multiplication x*y 56
// Division (floor) x // y 3
% Modulus x%y 2
RESULT
OPERATOR NAME SYNTAX
(IF X=16, Y=42)
False
> Greater than x>y
True
< Less than x<y
False
== Equal to x == y
True
!= Not equal to x != y
False
>= Greater than or equal to x >= y
True
<= Less than or equal to x <= y
iii. Logical operators: Logical operators perform Logical AND, Logical OR and Logical
NOT operations.
X Y X and Y
False False False
False True False
True False False
True True True
X Y X or Y
False False False
False True True
True False True
True True True
X Y X or Y
false false Y
false true Y
true false X
true true X
>>>0 or 0
0
>>>0 or 6
6
>>>‘a’ or ‘n’
’a’
>>>6<9 or ‘c’+9>5 # or operator will test the second operand only if the first operand
True # is false, otherwise ignores it, even if the second operand is wrong
iv. Bitwise operators: Bitwise operators acts on bits and performs bit by bit operation.
| Bitwise OR x|y
Examples:
Let Output:
a = 10 0
b=4
14
print(a & b) -11
print(a | b) 14
2
print(~a)
40
print(a ^ b)
print(a >> 2)
print(a << 2)
v. Assignment operators: Assignment operators are used to assign values to the variables.
OPERA
TOR DESCRIPTION SYNTAX
a. Identity operators- is and is not are the identity operators both are used to check if
two values are located on the same part of the memory. Two variables that are equal
does not imply that they are identical.
is True if the operands are identical
is not True if the operands are not identical
Example:
Let
a1 = 3
b1 = 3
a2 = 'PythonProgramming'
b2 = 'PythonProgramming'
a3 = [1,2,3]
b3 = [1,2,3]
Output:
False
True
False
Example:
>>>str1= “Hello”
>>>str2=input(“Enter a String :”)
Enter a String : Hello
>>>str1==str2 # compares values of string
True
>>>str1 is str2 # checks if two address refer to the same memory address
False
b. Membership operators- in and not in are the membership operators; used to test
whether a value or variable is in a sequence.
in True if value is found in the sequence
not in True if value is not found in the sequence
Example:
Let
x = 'Digital India'
y = {3:'a',4:'b'}
print('D' in x)
print('digital' not in x)
print('Digital' not in x)
print(3 in y)
print('b' in y)
2. Looping or Iteration
3. Jumping statements
2. if-else statement: When the condition is true, then code associated with if statement will
execute, otherwise code associated with else statement will execute.
Example:
a=10
b=20
if a>b:
print(“a is greater”)
else:
print(“b is greater”)
3. elif statement: It is short form of else-if statement. If the previous conditions were not true,
then do this condition". It is also known as nested if statement.
Example:
a=input(“Enter first number”)
b=input("Enter Second Number:")
if a>b:
while
Loops in loop
Python
for loop
2. for loop : The for loop iterate over a given sequence (it may be list, tuple or string).
Note: The for loop does not require an indexing variable to set beforehand, as the for command
itself allows for this.
primes = [2, 3, 5, 7]
for x in primes:
print(x)
it generates a list of numbers, which is generally used to iterate over with for loop.
range( ) function uses three types of parameters, which are:
a. range(stop)
b. range(start, stop)
Note:
Example:
for x in range(4):
print(x)
Output:
0
1
2
3
b. range(start, stop): It starts from the start value and up to stop, but not including
stop value.
Example:
Output:
2
3
4
5
c. range(start, stop, step): Third parameter specifies to increment or decrement the value by
adding or subtracting the value.
Example:
print(x)
Output:
3
5
7
S.
No. range( ) xrange( )
1. break statement : With the break statement we can stop the loop even if it is true.
Example:
in while loop in for loop
i = 1 languages = ["java", "python", "c++"]
while i < 6: for x in languages:
print(i) if x == "python":
if i == 3: break
break print(x)
i += 1
Output: Output:
1 java
2
3
Note: If the break statement appears in a nested loop, then it will terminate the very loop it is
in i.e. if the break statement is inside the inner loop then it will terminate the inner loop only
and the outer loop will continue as it is.
PYTHON- Class-XI, KV ONGC VADODARA Page 31
2. continue statement : With the continue statement we can stop the current iteration, and
continue with the next iteration.
Example:
in while loop in for loop
i = 0 languages = ["java", "python", "c++"]
while i < 6: for x in languages:
i += 1 if x == "python":
if i == 3: continue
continue print(x)
print(i)
Output: Output:
1 java
2 c++
4
5
6
Syntax:
for loop while loop
Example:
for i in range(1,4):
for j in range(1,i):
print("*", end=" ")
print(" ")
Built in functions
Functions defined in
Types of functions modules
1. Library Functions: These functions are already built in the python library.
3. User Defined Functions: The functions those are defined by the user are called user
defined functions.
Example:
import random
n=random.randint(3,7)
Example:
def display(name):
Syntax:
function-name(parameter)
Example:
ADD(10,20)
OUTPUT:
Sum = 30.0
def functionName(parameter):
… .. …
… .. …
… .. …
… .. …
functionName(parameter)
… .. …
… .. …
OUTPUT:
(7, 7, 11)
OUTPUT:
7 7 11
b. Function not returning any value (void function) : The function that performs some
operationsbut does not return any value, called void function.
def message():
print("Hello")
m=message()
print(m)
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.
1. Local Scope
2. Global Scope
1. Local Scope: Variable used inside the function. It can not be accessed outside the function.
In this scope, The lifetime of variables inside a function is as long as the function executes.
They are destroyed once we return from the function. Hence, a function does not remember the
value of a variable from its previous calls.
2. Global Scope: Variable can be accessed outside the function. In this scope, Lifetime of a
variable is the period throughout which the variable exits in the memory.
Example:
def my_func():
x = 10
print("Value inside function:",x)
x = 20
my_func()
print("Value outside function:",x)
OUTPUT:
This is because the variable x inside the function is different (local to the function) from the
one outside. Although they have same names, they are two different variables with different
scope.
On the other hand, variables outside of the function are visible from inside. They have a global
scope.
We can read these values from inside the function but cannot change (write) them. In order to
modify the value of variables outside the function, they must be declared as global variables
using the keyword global.
5.6 RECURSION:
Definition: A function calls itself, is called recursion.
5.6.1Python program to find the factorial of a number using recursion:
Program:
def factorial(n):
if n == 1:
return n
else:
return n*factorial(n-1)
OUTPUT:
How many terms you want to display: 8
0 1 1 2 3 5 8 13
lambda keyword, is used to create anonymous function which doesn’t have any name.
While normal functions are defined using the def keyword, in Python anonymous functions are
defined using the lambda keyword.
Syntax:
Lambda functions can have any number of arguments but only one expression. The expression
is evaluated and returned. Lambda functions can be used wherever function objects are
required.
Example:
value = lambda x: x * 4
print(value(6))
Output:
24
6.1 Introduction:
Definition: Sequence of characters enclosed in single, double or triple quotation marks.
Basics of String:
Strings are immutable in python. It means it is unchangeable. At the same memory
address, the new value cannot be stored.
Each character has its index or can be accessed using its index.
String in python has two-way index for each location. (0, 1, 2, ……. In the forward
direction and -1, -2, -3, …….. in the backward direction.)
Example:
0 1 2 3 4 5 6 7
k e n d r i y a
-8 -7 -6 -5 -4 -3 -2 -1
The index of string in forward direction starts from 0 and in backward direction starts
from -1.
The size of string is total number of characters present in the string. (If there are n
characters in the string, then last index in forward direction would be n-1 and last index
in backward direction would be –n.)
i. String concatenation Operator: The + operator creates a new string by joining the two
operand strings.
Example:
>>>”Hello”+”Python”
‘HelloPython’
>>>’2’+’7’
’27’
>>>”Python”+”3.0”
‘Python3.0’
Note: You cannot concate numbers and strings as operands with + operator.
Example:
>>>7+’4’ # unsupported operand type(s) for +: 'int' and 'str'
It is invalid and generates an error.
b. Membership Operators:
in – Returns True if a character or a substring exists in the given string; otherwise False
not in - Returns True if a character or a substring does not exist in the given string; otherwise False
Example:
>>> "ken" in "Kendriya Vidyalaya"
False
>>> "Ken" in "Kendriya Vidyalaya"
True
>>>"ya V" in "Kendriya Vidyalaya"
True
>>>"8765" not in "9876543"
False
‘0’ to ‘9’ 48 to 57
‘A’ to ‘Z’ 65 to 90
Example:
>>> 'abc'>'abcD'
False
>>> 'ABC'<'abc'
True
>>> 'abcd'>'aBcD'
True
>>> 'aBcD'<='abCd'
True
Example:
>>> ord('b')
98
>>> chr(65)
'A'
Interesting Fact: Index out of bounds causes error with strings but slicing a string outside the
index does not cause an error.
Example:
>>>str[14]
IndexError: string index out of range
>>> str[14:20] # both indices are outside the bounds
' ' # returns empty string
>>> str[10:16]
'ture'
Reason: When you use an index, you are accessing a particular character of a string, thus the
index must be valid and out of bounds index causes an error as there is no character to return
from the given index.
But slicing always returns a substring or empty string, which is valid sequence.
2. Write a program that reads a string and checks whether it is a palindrome string or
not.
str=input("Enter a string : ")
n=len(str)
mid=n//2
rev=-1
3. Write a program to convert lowercase alphabet into uppercase and vice versa.
choice=int(input("Press-1 to convert in lowercase\n Press-2 to convert in uppercase\n"))
str=input("Enter a string: ")
if choice==1:
s1=str.lower()
print(s1)
elif choice==2:
s1=str.upper()
print(s1)
else:
print("Invalid choice entered")
7.1 Introduction:
List String
Mutable Immutable
Element can be assigned at specified Element/character cannot be
index assigned at specified index.
Example: Example:
To create a list enclose the elements of the list within square brackets and separate the
elements by commas.
Syntax:
Example:
>>> L
>>> List
['h', 'e', 'l', 'l', 'o', ' ', 'p', 'y', 't', 'h', 'o', 'n']
>>> L1
['6', '7', '8', '5', '4', '6'] # it treats elements as the characters though we entered digits
To overcome the above problem, we can use eval( ) method, which identifies the
data type and evaluate them automatically.
>>> L1
>>> L2
[6, 7, 8, 5, 4, 3]
Note: With eval( ) method, If you enter elements without square bracket[ ], it will be
considered as a tuple.
>>> L1
The values stored in a list can be accessed using the slice operator ([ ] and [:]) with
indexes.
List-name[start:end] will give you elements between indices start to end-1.
The first item in the list has the index zero (0).
Example:
>>> number=[12,56,87,45,23,97,56,27]
Forward Index
0 1 2 3 4 5 6 7
12 56 87 45 23 97 56 27
-8 -7 -6 -5 -4 -3 -2 -1
Backward Index
>>> number[2]
87
>>> number[-1]
27
>>> number[-8]
12
>>> number[8]
IndexError: list index out of range
>>> number[5]=55 #Assigning a value at the specified index
PYTHON- Class-XI, KV ONGC VADODARA Page 62
>>> number
[12, 56, 87, 45, 23, 55, 56, 27]
Method-1:
Output:
s
u
n
d
a
y
Method-2
>>> day=list(input("Enter elements :"))
Enter elements : wednesday
>>> for i in range(len(day)):
print(day[i])
Output:
w
e
d
n
e
s
d
a
y
Joining operator +
Repetition operator *
Slice operator [:]
Comparison Operator <, <=, >, >=, ==, !=
Example:
>>> L1=['a',56,7.8]
>>> L2=['b','&',6]
>>> L3=[67,'f','p']
>>> L1+L2+L3
Example:
>>> L1*3
>>> 3*L1
Slice Operator:
>>> number=[12,56,87,45,23,97,56,27]
>>> number[2:-2]
>>> number[4:20]
>>> number[-1:-6]
[]
>>> number[-6:-1]
List-name[start:end:step] will give you elements between indices start to end-1 with
skipping elements as per the value of step.
>>> number[1:6:2]
[27, 56, 97, 23, 45, 87, 56, 12] #reverses the list
>>> number=[12,56,87,45,23,97,56,27]
>>> number[2:4]=["hello","python"]
>>> number
>>> number[2:4]=["computer"]
>>> number
Note: The values being assigned must be a sequence (list, tuple or string)
Example:
>>> number=[12,56,87,45,23,97,56,27]
>>> number=[12,56,87,45,23,97,56,27]
Example:
Consider a list:
company=["IBM","HCL","Wipro"]
S. Function
No.
Description Example
Name
1 append( ) To add element to the list >>> company.append("Google")
at the end. >>> company
Syntax: ['IBM', 'HCL', 'Wipro', 'Google']
list-name.append (element)
Error:
>>>company.append("infosys","microsoft") # takes exactly one element
TypeError: append() takes exactly one argument (2 given)
4 index( ) Returns the index of the >>> company = ["IBM", "HCL", "Wipro",
first element with the "HCL","Wipro"]
specified value. >>> company.index("Wipro")
Syntax: 2
list-name.index(element)
Error:
>>> company.index("WIPRO") # Python is case-sensitive language
ValueError: 'WIPRO' is not in list
>>> company.insert(-16,"TCS")
>>> company
['TCS', 'IBM', 'HCL', 'Apple', 'Wipro',
'Microsoft']
[]
Error:
>>>L=[ ]
>>>L.pop( )
IndexError: pop from empty list
10 copy( ) Returns a copy of the list. >>>company=["IBM","HCL", "Wipro"]
>>> L=company.copy( )
Syntax: >>> L
list-name.copy( ) ['IBM', 'HCL', 'Wipro']
11 reverse( ) Reverses the order of the >>>company=["IBM","HCL", "Wipro"]
list. >>> company.reverse()
Syntax: >>> company
list-name.reverse( ) ['Wipro', 'HCL', 'IBM']
Takes no argument,
returns no list.
12. sort( ) Sorts the list. By default >>>company=["IBM","HCL", "Wipro"]
in ascending order. >>>company.sort( )
>>> company
Syntax: ['HCL', 'IBM', 'Wipro']
list-name.sort( )
To sort a list in descending order:
>>>company=["IBM","HCL", "Wipro"]
>>> company.sort(reverse=True)
>>> company
['Wipro', 'IBM', 'HCL']
Syntax:
Example:
>>> L=[10,20,30,40,50]
>>> L
>>> L= [10,20,30,40,50]
>>> L
>>> del L # deletes all elements and the list object too.
>>> L
S.
del remove( ) pop( ) clear( )
No.
S.
append( ) extend( ) insert( )
No.
Adds an element at the
Adds single element in the end Add a list in the end of specified position.
1
of the list. the another list
(Anywhere in the list)
Takes one list as Takes two arguments,
2 Takes one element as argument
argument position and element.
The length of the list
The length of the list will The length of the list
3 will increase by the
increase by 1. will increase by 1.
length of inserted list.
Output:
Enter the elements: 56,78,98,23,11,77,44,23,65
Enter the element that you want to search : 23
Element found at the position : 4
8.1 INTRODUCTION:
Syntax:
Example:
>>> T
>>> T=(3) #With a single element without comma, it is a value only, not a tuple
>>> T
>>> T= (3, ) # to construct a tuple, add a comma after the single element
>>> T
(3,)
>>> T1
(3,)
>>> T2=tuple('hello') # for single round-bracket, the argument must be of sequence type
>>> T2
('h', 'e', 'l', 'l', 'o')
>>> T3=('hello','python')
>>> T3
('hello', 'python')
>>> T=(5,10,(4,8))
>>> T
>>> T
>>> T1
('4', '5', '6', '7', '8') # it treats elements as the characters though we entered digits
To overcome the above problem, we can use eval( ) method, which identifies the
data type and evaluate them automatically.
>>> T1
>>> type(T1)
<class 'int'>
>>> T2
(1, 2, 3, 4, 5)
>>> T3
Tuples are very much similar to lists. Like lists, tuple elements are also indexed.
Forward indexing as 0,1,2,3,4……… and backward indexing as -1,-2,-3,-4,………
The values stored in a tuple can be accessed using the slice operator ([ ] and [:]) with
indexes.
tuple-name[start:end] will give you elements between indices start to end-1.
The first item in the tuple has the index zero (0).
Example:
>>> alpha=('q','w','e','r','t','y')
Forward Index
0 1 2 3 4 5
q w e r t y
-6 -5 -4 -3 -2 -1
Backward Index
>>> alpha[5]
'y'
>>> alpha[-4]
'e'
>>> alpha[46]
IndexError: tuple index out of range
>>> alpha[2]='b' #can’t change value in tuple, the value will remain unchanged
TypeError: 'tuple' object does not support item assignment
Syntax:
statement
Example:
Method-1
>>> alpha=('q','w','e','r','t','y')
>>> for i in alpha:
print(i)
Output:
q
w
e
r
t
y
Method-2
>>> for i in range(0, len(alpha)):
print(alpha[i])
Output:
q
w
e
r
t
y
Joining operator +
Repetition operator *
Slice operator [:]
Comparison Operator <, <=, >, >=, ==, !=
Example:
>>> T1 = (25,50,75)
>>> T2 = (5,10,15)
>>> T1+T2
(25, 50, 75, 5, 10, 15)
>>> T1 + (34)
TypeError: can only concatenate tuple (not "int") to tuple
>>> T1 + (34, )
Example:
>>> T1*2
>>> T2=(10,20,30,40)
>>> T2[2:4]*3
Slice Operator:
>>>alpha=('q','w','e','r','t','y')
>>> alpha[1:-3]
('w', 'e')
>>> alpha[3:65]
>>> alpha[-1:-5]
>>> alpha[-5:-1]
List-name[start:end:step] will give you elements between indices start to end-1 with
skipping elements as per the value of step.
>>> alpha[1:5:2]
('w', 'r')
Comparison Operators:
Example:
Consider a tuple:
subject=("Hindi","English","Maths","Physics")
S. Function
No.
Description Example
Name
1 len( ) Find the length of a tuple. >>>subject=("Hindi","English","Maths","Physics”)
Syntax: >>> len(subject)
len (tuple-name) 4
2 max( ) Returns the largest value >>> max(subject)
from a tuple. 'Physics'
Syntax:
max(tuple-name)
Error: If the tuple contains values of different data types, then it will give an error
because mixed data type comparison is not possible.
Example:
>>> T=(45,78,22)
>>> T
(45, 78, 22)
Example:
>>> a, b, c=T
>>> a
45
>>> b
78
>>> c
22
Note: Tuple unpacking requires that the number of variable on the left side must be equal
to the length of the tuple.
The del statement is used to delete elements and objects but as you know that tuples are
immutable, which also means that individual element of a tuple cannot be deleted.
>> T=(2,4,6,8,10,12,14)
But you can delete a complete tuple with del statement as:
Example:
>>> T=(2,4,6,8,10,12,14)
>>> del T
>>> T
9.1 INTRODUCTION:
Syntax:
Example:
>>> marks
>>> D
{ }
{'Maths': 81, 'Chemistry': 78, 'Physics': 75, 'CS': 78} # there is no guarantee that
Example:
>>> D1={[2,3]:"hello"}
>>> marks=dict(Physics=75,Chemistry=78,Maths=81,CS=78)
>>> marks
In the above case the keys are not enclosed in quotes and equal sign is used
for assignment rather than colon.
>>> marks
>>> marks=dict(zip(("Physics","Chemistry","Maths","CS"),(75,78,81,78)))
>>> marks
Example-a
>>> marks=dict([['Physics',75],['Chemistry',78],['Maths',81],['CS',78]])
# list as argument passed to dict( ) constructor contains list type elements.
>>> marks
Example-b
>>> marks=dict((['Physics',75],['Chemistry',78],['Maths',81],['CS',78]))
>>> marks
Example-c
>>> marks=dict((('Physics',75),('Chemistry',78),('Maths',81),('CS',78)))
>>> marks
Syntax:
dictionary-name[key]
Example:
>>> marks["Maths"]
81
KeyError: 'English'
Lookup : A dictionary operation that takes a key and finds the corresponding value, is
called lookup.
Syntax:
statement
OUTPUT:
physics : 75
Chemistry : 78
Maths : 81
CS : 78
Syntax:
dictionary-name[key]=value
Example:
>>> marks
>>> marks
>>> marks
{'physics': 75, 'Chemistry': 78, 'Maths': 81, 'CS': 84, 'English': 89}
Syntax:
del dictionary-name[key]
Example:
>>> marks
{'physics': 75, 'Chemistry': 78, 'Maths': 81, 'CS': 84, 'English': 89}
>>> marks
(ii) Using pop( ) method: It deletes the key-value pair and returns the value of deleted
element.
Syntax:
dictionary-name.pop( )
Example:
>>> marks
>>> marks.pop('Maths')
81
(i) in : it returns True if the given key is present in the dictionary, otherwise False.
(ii) not in : it returns True if the given key is not present in the dictionary, otherwise
False.
Example:
True
False
>>> 78 in marks # in and not in only checks the existence of keys not values
False
However, if you need to search for a value in dictionary, then you can use in operator
with the following syntax:
Syntax:
Example:
>>> 78 in marks.values( )
True
For pretty printing a dictionary you need to import json module and then you can use
Example:
OUTPUT:
"physics": 75,
"Chemistry": 78,
"Maths": 81,
"CS": 78
dumps( ) function prints key:value pair in separate lines with the number of spaces
Steps:
import json
L = sentence.split()
d={ }
for word in L:
key=word
if key not in d:
count=L.count(key)
d[key]=count
print(json.dumps(d,indent=2))
S. Function
No.
Description Example
Name
1 len( ) Find the length of a >>> len(marks)
dictionary.
Syntax: 4
len (dictionary-name)
2 clear( ) removes all elements >>> marks.clear( )
from the dictionary
Syntax: >>> marks
dictionary-name.clear( )
{}
Note: When key does not exist it returns no value without any error.
>>> marks.get('Hindi')
>>>
4 items( ) returns all elements as a >>> marks.items()
sequence of (key,value)
tuples in any order. dict_items([('physics', 75), ('Chemistry',
Syntax: 78), ('Maths', 81), ('CS', 78)])
dictionary-name.items( )
Note: You can write a loop having two variables to access key: value pairs.
>>> seq=marks.items()
>>> for i, j in seq:
print(j, i)
OUTPUT:
75 physics
78 Chemistry
81 Maths
78 CS
5 keys( ) Returns all keys in the >>> marks.keys()
form of a list.
Syntax: dict_keys (['physics', 'Chemistry',
dictionary-name.keys( ) 'Maths', 'CS'])
6 values( ) Returns all values in the >>> marks.values()
form of a list.
Syntax: dict_values([75, 78, 81, 78])
dictionary-name.values( )
7 update( ) Merges two dictionaries.
Already present elements
are override.
Syntax:
dictionary1.update(dictionary2)
Example:
>>> marks1 = { "physics" : 75, "Chemistry" : 78, "Maths" : 81, "CS":78 }
>>> marks2 = { "Hindi" : 80, "Chemistry" : 88, "English" : 92 }
>>> marks1.update(marks2)
>>> marks1
{'physics': 75, 'Chemistry': 88, 'Maths': 81, 'CS': 78, 'Hindi': 80, 'English': 92}
PYTHON- Class-XI, KV ONGC VADODARA Page 93
CHAPTER-10
SORTING
10.1 DEFINITION:
To arrange the elements in ascending or descending order.
n=len(L)
for p in range(0,n-1):
for i in range(0,n-1):
if L[i]>L[i+1]:
OUTPUT:
The sorted list is : [8, 12, 24, 45, 60, 77, 87, 90]
PROGRAM:
n=len(L)
for j in range(1,n):
temp=L[j]
prev=j-1
prev=prev-1
Enter the elements: [45, 11, 78, 2, 56, 34, 90, 19]
The sorted list is : [2, 11, 19, 34, 45, 56, 78, 90]
6 while prev>=0 and L[prev]>temp: first time 1 comparison, second time 2, and so on. In
this case 1+2+3+4+5+6=21 operations
L[prev+1]=L[prev] first time 1 element shifted, second time 2 and so on.
In this case 1+2+3+4+5+6= 21 operations
prev=prev-1 21 operations
L[prev+1]=temp element insertion at right place, 6 operations
7 print("The sorted list is : ", L) 1
TOTAL: 1+1+6+6+6+21+21+21+6+1 = 90 operations
TYPES OF ERRORS
a. Syntax Error
b. Semantics Error
3. Logical Error
1. Compile Time Error: Compile time errors are those errors that occur at the time of
compilation of the program.
for example:
b=20
b. Semantics Error: Semantic errors occur when the statements written in the program are
not meaningful.
Example:
a+b = c # expression cannot come on the left side of the assignment operator.
2. Run Time Error: Errors that occur during the execution or running the program are
known as run time errors. When a program “crashed” or “abnormally terminated” during
the execution, then this type errors are run time errors.
a=1
while a<5: # value of a is always less than 5, infinite loop
print(a)
a=a-1
3. Logical Error: These types of errors occur due to wrong logic. When a program
successfully executes but giving wrong output, then it is known as logical error.
Example:
a=10
b=20
c=30
average=a+b+c/3 #wrong logic to find the average
print(average)
OUTPUT:
40.0
PYTHON- Class-XI, KV ONGC VADODARA Page 99
11.3 Exception handling in python:
Exception: The unusual and unexpected condition other than syntax or logical errors,
encountered by a program at the time of execution, is called exception.
The purpose of exception handling mechanism is to provide means to detect and report
an exceptional circumstance, so that appropriate action can be taken.
Exception handling in python can be done using try and except blocks.
Syntax:
try:
# Code that may generate an exception
except:
# Code for handling the exception
Example:
num1=int(input("Enter first number :"))
num2=int(input("Enter second number: "))
try:
r=num1/num2
print("Result is :", r)
except:
print("Divided by zero")
OUTPUT:
Enter first number :30
Enter second number: 0
Divided by zero
d. Use intermediate print statements to know the value and type of a variable
b. None
None is a special constant in Python that represents the absence of a value or a null value.
None does mean False, 0 or any empty list.
Example:
>>> None = = 0
PYTHON- Class-XI, KV ONGC VADODARA Page 102
False
>>> None = = False
False
>>> None = = [ ]
False
>>> x = None
>>> y = None
>>> x = = y
True
void functions that do not return anything will return a None object automatically. None is also
returned by functions in which the program flow does not encounter a return statement. For
example:
def My_Function( ) :
x=5
y=7
z=x+y
sum = My_Function( )
print(sum)
OUTPUT :
None
Another Example:
def ODD_EVEN(x) :
if(x % 2 ) = = 0:
return True
r = ODD_EVEN(7)
print(r)
OUTPUT :
None
c. as
as is used to create an alias while importing a module.
Example:
>>> import math as mymath
>>> mymath.sqrt(4)
2.0
d. assert
If the condition is true, nothing happens. But if the condition is false, AssertionError is
raised.
Syntax:
example:
>>> x = 7
>>> assert x > 9, “The value is smaller”
Traceback ( most recent call last ):
File “<string>”, line 201, in runcode
File “<interactive input>”, line 1, in <module>
AssertionError: The value is smaller
e. def
def is used to define a user-defined function.
f. del
>>> a = b = 9
>>>del a
>>> a
>>>b
>>> x
Exceptions are basically errors that suggests something went wrong while executing our
program
Syntax:
try:
Try-block
except exception1:
Exception1-block
except exception2:
Exception2-block
else:
Else-block
finally:
Finally-block
example:
def reciprocal(num):
try:
r = 1/num
except:
print('Exception caught')
return
return r
print(reciprocal(10))
print(reciprocal(0))
Output
0.1
h. finally
finally is used with try…except block to close up resources or file streams.
i. from, import
import keyword is used to import modules into the current namespace. from…import is
used to import specific attributes or functions into the current namespace.
For example:
import math
Example :
from math import sqrt
now we can use the function simply as sqrt( ), no need to write math.sqrt( ).
j. global
global is used to declare that a variable inside the function is global (outside the function).
If we need to read the value of a global variable, it is not necessary to define it as global. This
is understood.
If we need to modify the value of a global variable inside a function, then we must declare it
with global. Otherwise a local variable with that name is created.
Example:
globvar = 10
def read1( ):
print(globvar)
def write1( ):
global globvar
globvar = 5
def write2( ):
globvar = 15
read1( )
PYTHON- Class-XI, KV ONGC VADODARA Page 107
write1( )
read1( )
write2( )
read1( )
Output
10
5
5
k. in
in is used to test if a sequence (list, tuple, string etc.) contains a value. It returns True if the
value is present, else it returns False. For example:
>>> a = [1, 2, 3, 4, 5]
>>> 5 in a
True
>>> 10 in a
False
Output
h
e
l
l
o
l. is
is keyword is used in Python for testing object identity.
While the = = operator is used to test if two variables are equal or not, is is used to test if the
two variables refer to the same object.
It returns True if the objects are identical and False if not.
We know that there is only one instance of True, False and None in Python, so they are
identical.
>>> [ ] == [ ]
True
>>> [ ] is [ ]
False
>>> { } == { }
True
>>> { } is { }
False
An empty list or dictionary is equal to another empty one. But they are not identical objects as
they are located separately in memory. This is because list and dictionary are mutable (value
can be changed).
m. lambda
lambda is used to create an anonymous function (function with no name). It is an
inline function that does not contain a return statement. It consists of an
expression that is evaluated and returned.
example:
a = lambda x: x*2
for i in range(1,6):
print(a(i))
n. nonlocal
The use of nonlocal keyword is very much similar to the global keyword. nonlocal is used to
declare a variable inside a nested function (function inside a function) is not local to it.
If we need to modify the value of a non-local variable inside a nested function, then we must
declare it with nonlocal. Otherwise a local variable with that name is created inside the nested
function.
Example:
def outer_function( ):
a=5
def inner_function( ):
nonlocal a
a = 10
print("Inner function: ",a)
inner_function ( )
print("Outer function: ",a)
outer_function( )
Output
Inner function: 10
Outer function: 10
outer_function( )
Output
Inner function: 10
Outer function: 5
Here, we do not declare that the variable a inside the nested function is nonlocal. Hence, a new
local variable with the same name is created, but the non-local a is not modified as seen in our
output.
o. pass
pass is a null statement in Python. Nothing happens when it is executed. It is used
as a placeholder.
Suppose we have a function that is not implemented yet, but we want to implement it in the
future. Simply writing,
def function(args):
in the middle of a program will give us IndentationError. Instead of this, we construct a blank
body with the pass statement.
def function(args):
pass
p. while
while is used for looping.
i=5
while(i):
print(i)
i=i–1
Output
5
4
3
PYTHON- Class-XI, KV ONGC VADODARA Page 111
2
1
q. with
with statement is used to wrap the execution of a block of code within methods
defined by the context manager.
Context manager is a class that implements enter and exit methods. Use of with statement
ensures that the exit method is called at the end of the nested block.
Example
This example writes the text Computer Science to the file Book.txt. File objects
have enter and exit method defined within them, so they act as their own context manager.
First the enter method is called, then the code within with statement is executed and finally
the exit method is called. exit method is called even if there is an error. It basically closes the
file stream.
r. yield
yield is used inside a function like a return statement. But yield returns a generator.
Generator is an iterator that generates one item at a time. A large list of value will take up a
lot of memory. Generators are useful in this situation as it generates only one value at a time
instead of storing all the values in memory.
Example:
will create a generator g which generates the values 20 to 299. We can generate the numbers
using the next( ) function as shown below:
>>> next(g)
1
>>> next(g)
2
>>> next(g)
4
>>> next(g)
8