python-notes-CS XI 2023
python-notes-CS XI 2023
CHAPTER PAGE
CHAPTER NAME
NO. NO.
1 INTRODUCTION TO PYTHON 2
2 PYTHON FUNDAMENTALS 5
3 DATA HANDLING 16
4 FLOW OF CONTROL 27
5 FUNCTIONS IN PYTHON 38
6 STRING IN PYTHON 50
7 LIST IN PYTHON 61
8 TUPLE IN PYTHON 75
9 DICTIONARY IN PYTHON 85
10 SORTING 95
11 DEBUGGING PROGRAMS 99
Page 1
CHAPTER-1
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.
Page 2
i. Interactive Mode: Without passing python script file to the interpreter, directly
execute code to Python (Command line).
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:
Page 4
CHAPTER-2
PYTHON FUNDAMENTALS
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).
Page 5
2. Identifier: The name given by the user to the entities like variable name, class-name,
function-name etc.
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
Page 6
B. String literals:
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 : , ; , ( ), { }, [ ]
Page 8
2.4 Basic terms of a Python Programs:
A. Blocks and Indentation
B. Statements
C. Expressions
D. Comments
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.
Page 9
There are two types of comments in python:
i. Single line comment
ii. Multi-line comment
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
‘’’
Page 10
Multiple Statements on a Single Line:
The semicolon ( ; ) allows multiple statements on the single line given that neither statement
starts a new code block.
Example:-
x=5; print(“Value =” x)
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 :
Page 12
Syntax:
type (variable-name)
Example:
x=6
type(x)
The result will be:
<class ‘int’>
If you want to know the memory address or location of the object, you can use id( )
function.
Example:
>>>id(5)
1561184448
>>>b=5
>>>id(b)
1561184448
You can delete single or multiple variables by using del statement. Example:
del x
del y, z
Page 13
int( ) - constructs an integer number from an integer literal, a float literal or a string
literal.
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:
Page 14
object : It can be one or multiple objects separated by comma.
sep : sep argument specifies the separator character or string. It separate the objects/items. By
default sep argument adds space in between the items when printing.
end : It determines the end character that will be printed at the end of print line. By default it
has newline character( ‘\n’ ).
Example:
x=10
y=20
z=30
print(x,y,z, sep=’@’, end= ‘ ‘)
Output:
10@20@30
Page 15
CHAPTER-3
DATA HANDLING
3.1 Data Types in Python:
Python has Two data types –
1. Primitive Data Type (Numbers, String)
2. Collection Data Type (List, Tuple, Set, Dictionary)
Data Types
Primitive Collection
Data Type Data Type
Number String
int
float
complex
Example:
w=1 # int
y = 2.8 # float
z = 1j # complex
Page 16
integer : There are two types of integers in python:
int
Boolean
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
Page 17
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.
Page 18
3.2 MUTABLE & IMMUTABLE Data Type:
Mutable Data Type:
These are changeable. In the same memory address, new value can be stored.
Example: List, Set, Dictionary
Immutable Data Type:
These are unchangeable. In the same memory address new value cannot be stored.
Example: integer, float, Boolean, string and tuple.
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
Page 19
Example:
>>>x= -5
>>>x**2
>>> -25
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.
Page 20
a. Relational expressions as operands:
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
Page 21
b. numbers or strings or lists as operands:
In an expression X or Y, if first operand has true value, then return first operand X as a
result, otherwise returns Y.
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
Page 22
~ Bitwise NOT ~x
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]
Page 24
print(a2 is b2) # Output is False, since lists are mutable.
print(a3 is b3)
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)
Page 25
Output:
True
True
False
True
False
Page 26
CHAPTER-4
FLOW OF CONTROL
2. Looping or Iteration
3. Jumping statements
Page 27
There are three types of conditions in python:
1. if statement
2. if-else statement
3. elif statement
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:
Page 28
print("a is greater")
elif a==b:
print("both numbers are equal")
else:
print("b is greater")
while
Loops in loop
Python
for loop
Page 29
1. while loop: With the while loop we can execute a set of statements as long as a condition is
true. It requires to define an indexing variable.
Example: To print table of number 2
i=2
while i<=20:
print(i)
i+=2
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:
Page 30
a. range(stop): By default, It starts from 0 and increments by 1 and ends up to stop,
but not including stop value.
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
Page 31
Explanation of output: 3 is starting value, 8 is stop value and 2 is step value. First print 3 and
increase it by 2, that is 5, again increase is by 2, that is 7. The output can’t exceed stop-1 value
that is 8 here. So, the output is 3, 5, 8.
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.
Page 32
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
Page 33
Syntax:
for <variable-name> in <sequence>:
for <variable-name> in <sequence>:
statement(s)
statement(s)
Example:
for i in range(1,4):
for j in range(1,i):
print("*", end=" ")
print(" ")
Page 34
3. Write a program to check a year whether it is leap year or not.
year=int(input("Enter the year: "))
if year%100==0 and year%400==0:
print("It is a leap year")
elif year%4==0:
print("It is a leap year")
else:
print("It is not leap year")
Page 35
res=rem+res*10
num=num//10
if res==n:
print("Number is Palindrome")
else:
print("Number is not Palindrome")
Page 36
if num==sum:
print(num, "is perfect number")
else:
print(num, "is not perfect number")
Page 37
CHAPTER-5
FUNCTIONS IN PYTHON
5.1 Definition: Functions are the subprograms that perform specific task. Functions are the
small modules.
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.
Page 38
2. Functions defined in modules:
a. Functions of math module:
To work with the functions of math module, we must import math module in program.
import math
S. No. Function Description Example
1 sqrt( ) Returns the square root of a number >>>math.sqrt(49)
7.0
2 ceil( ) Returns the upper integer >>>math.ceil(81.3)
82
3 floor( ) Returns the lower integer >>>math.floor(81.3)
81
4 pow( ) Calculate the power of a number >>>math.pow(2,3)
8.0
5 fabs( ) Returns the absolute value of a number >>>math.fabs(-5.6)
5.6
6 exp( ) Returns the e raised to the power i.e. e3 >>>math.exp(3)
20.085536923187668
Example:
import random
n=random.randint(3,7)
Page 39
Where:
Example:
def display(name):
Page 40
5.4 Calling the function:
Once we have defined a function, we can call it from another function, program or even the
Python prompt. To call a function we simply type the function name with appropriate
parameters.
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)
Page 42
OUTPUT:
Hello
None
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.1 Python 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)
Page 44
OUTPUT:
enter the number: 5
The factorial of 5 is 120
OUTPUT:
How many terms you want to display: 8
0 1 1 2 3 5 8 13
Page 45
Program:
def Binary_Search(sequence, item, LB, UB):
if LB>UB:
return -5 # return any negative value
mid=int((LB+UB)/2)
if item==sequence[mid]:
return mid
elif item<sequence[mid]:
UB=mid-1
return Binary_Search(sequence, item, LB, UB)
else:
LB=mid+1
Page 46
return Binary_Search(sequence, item, LB, UB)
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
Page 47
In the above program, lambda x: x * 4 is the lambda function. Here x is the argument and x *
4 is the expression that gets evaluated and returned.
Page 48
def lcm(x, y):
lcm = (x*y)//gcd(x,y)
return lcm
Page 49
CHAPTER-6
STRING IN PYTHON
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.)
Page 50
Output:
kendriya
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.
Page 51
ii. String repetition Operator: It is also known as String replication operator. It requires
two types of operands- a string and an integer number.
Example:
>>>”you” * 3
‘youyouyou’
>>>3*”you”
‘youyouyou’
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
Page 52
Characters ASCII (Ordinal) Value
‘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'
Page 53
Program: Write a program to display ASCII code of a character and vice versa.
var=True
while var:
choice=int(input("Press-1 to find the ordinal value \n Press-2 to find a character of a value\n"))
if choice==1:
ch=input("Enter a character : ")
print(ord(ch))
elif choice==2:
val=int(input("Enter an integer value: "))
print(chr(val))
else:
print("You entered wrong choice")
Page 54
Example:
>>> str="data structure"
>>> str[0:14]
'data structure'
>>> str[0:6]
'data s'
>>> str[2:7]
'ta st'
>>> str[-13:-6]
'ata str'
>>> str[-5:-11]
'' #returns empty string
>>> str[:14] # Missing index before colon is considered as 0.
'data structure'
>>> str[0:] # Missing index after colon is considered as 14. (length of string)
'data structure'
>>> str[7:]
'ructure'
>>> str[4:]+str[:4]
' structuredata'
>>> str[:4]+str[4:] #for any index str[:n]+str[n:] returns original string
'data structure'
>>> str[8:]+str[:8]
'ucturedata str'
>>> str[8:], str[:8]
('ucture', 'data str')
Slice operator with step index:
Slice operator with strings may have third index. Which is known as step. It is optional.
Page 55
Syntax:
string-name[start:end:step]
Example:
>>> str="data structure"
>>> str[2:9:2]
't tu'
>>> str[-11:-3:3]
'atc'
>>> str[: : -1] # reverses a string
'erutcurts atad'
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.
Page 56
s1= “hello365”
s2= “python”
s3 = ‘4567’
s4 = ‘ ‘
s5= ‘comp34%@’
S. No. Function Description Example
1 len( ) Returns the length of a string >>>print(len(str))
14
2 capitalize( ) Returns a string with its first character >>> str.capitalize()
capitalized. 'Data structure'
3 find(sub,start,end) Returns the lowest index in the string where the >>> str.find("ruct",5,13)
substring sub is found within the slice range. 7
Returns -1 if sub is not found. >>> str.find("ruct",8,13)
-1
4 isalnum( ) Returns True if the characters in the string are >>>s1.isalnum( )
alphabets or numbers. False otherwise True
>>>s2.isalnum( )
True
>>>s3.isalnum( )
True
>>>s4.isalnum( )
False
>>>s5.isalnum( )
False
5 isalpha( ) Returns True if all characters in the string are >>>s1.isalpha( )
alphabetic. False otherwise. False
>>>s2.isalpha( )
True
>>>s3.isalpha( )
False
>>>s4.isalpha( )
False
>>>s5.isalpha( )
False
6 isdigit( ) Returns True if all the characters in the string are >>>s1.isdigit( )
digits. False otherwise. False
>>>s2.isdigit( )
False
>>>s3.isdigit( )
True
>>>s4.isdigit( )
False
>>>s5.isdigit( )
False
7 islower( ) Returns True if all the characters in the string are >>> s1.islower()
lowercase. False otherwise. True
>>> s2.islower()
Page 57
True
>>> s3.islower()
False
>>> s4.islower()
False
>>> s5.islower()
True
8 isupper( ) Returns True if all the characters in the string are >>> s1.isupper()
uppercase. False otherwise. False
>>> s2.isupper()
False
>>> s3.isupper()
False
>>> s4.isupper()
False
>>> s5.isupper()
False
9 isspace( ) Returns True if there are only whitespace >>> " ".isspace()
characters in the string. False otherwise. True
>>> "".isspace()
False
10 lower( ) Converts a string in lowercase characters. >>> "HeLlo".lower()
'hello'
11 upper( ) Converts a string in uppercase characters. >>> "hello".upper()
'HELLO'
12 lstrip( ) Returns a string after removing the leading >>> str="data structure"
characters. (Left side). >>> str.lstrip('dat')
if used without any argument, it removes the ' structure'
leading whitespaces. >>> str.lstrip('data')
' structure'
>>> str.lstrip('at')
'data structure'
>>> str.lstrip('adt')
' structure'
>>> str.lstrip('tad')
' structure'
13 rstrip( ) Returns a string after removing the trailing >>> str.rstrip('eur')
characters. (Right side). 'data struct'
if used without any argument, it removes the >>> str.rstrip('rut')
trailing whitespaces. 'data structure'
>>> str.rstrip('tucers')
'data '
14 split( ) breaks a string into words and creates a list out of it >>> str="Data Structure"
>>> str.split( )
['Data', 'Structure']
Page 58
Programs related to Strings:
1. Write a program that takes a string with multiple words and then capitalize the first
letter of each word and forms a new string out of it.
Solution:
s1=input("Enter a string : ")
length=len(s1)
a=0
end=length
s2="" #empty string
while a<length:
if a==0:
s2=s2+s1[0].upper()
a+=1
elif (s1[a]==' 'and s1[a+1]!=''):
s2=s2+s1[a]
s2=s2+s1[a+1].upper()
a+=2
else:
s2=s2+s1[a]
a+=1
print("Original string : ", s1)
print("Capitalized wrds string: ", s2)
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
Page 59
for i in range(mid):
if str[i]==str[rev]:
i=i+1
rev=rev-1
else:
print("String is not palindrome")
break
else:
print("String is palindrome")
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")
Page 60
CHAPTER-7
LIST IN PYTHON
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:
Page 61
mylist = list(("apple", "banana", "cherry")) #note the double round-brackets
print(mylist)
>>> 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
Page 62
enter the elements: [6,7,8,5,4,3] # for list, you must enter the [ ] bracket
>>> 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
Page 63
>>> 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 <, <=, >, >=, ==, !=
Page 64
Joining Operator: It joins two or more lists.
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]
Page 65
>>> number[0:len(number)]
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]
Page 66
Comparison Operators:
Example:
Page 67
List Methods:
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
Page 68
>>> company.index(2) # Write the element, not index
ValueError: 2 is not in list
5 insert( ) Adds an element at the >>>company=["IBM","HCL","Wipro"]
specified position. >>> company.insert(2,"Apple")
>>> company
Syntax: ['IBM', 'HCL', 'Apple', 'Wipro']
list.insert(index, element)
>>> company.insert(16,"Microsoft")
>>> company
['IBM', 'HCL', 'Apple', 'Wipro',
'Microsoft']
>>> company.insert(-16,"TCS")
>>> company
['TCS', 'IBM', 'HCL', 'Apple', 'Wipro',
'Microsoft']
[]
Page 69
9 pop( ) Removes the element at >>>company=["IBM","HCL", "Wipro"]
the specified position and >>> company.pop(1)
returns the deleted 'HCL'
element. >>> company
Syntax: ['IBM', 'Wipro']
list-name.pop(index)
>>> company.pop( )
The index argument is
'Wipro'
optional. If no index is
specified, pop( ) removes and
returns the last item in the list.
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']
Page 70
Deleting the elements from the list using del statement:
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
Page 71
Difference between del, remove( ), pop( ), clear( ):
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.
Page 72
>>> L[3:4][0]
['modern', 'programming']
>>> L[3:4][0][1]
'programming'
>>> L[3:4][0][1][3]
'g'
>>> L[0:9][0]
'Python'
>>> L[0:9][0][3]
'h'
>>> L[3:4][1]
IndexError: list index out of range
Page 73
Program-2 Find the second largest number in a list.
L=eval(input("Enter the elements: "))
n=len(L)
max=second=L[0]
for i in range(n):
if max<L[i]>second:
max=L[i]
seond=max
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
Page 74
CHAPTER-8
TUPLE IN PYTHON
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,)
Page 75
>>> T1=3, # It also creates a tuple with single element
>>> 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
Page 76
('h', 'e', 'l', 'l', 'o', ' ', 'p', 'y', 't', 'h', 'o', 'n')
>>> 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
Page 77
8.3 Accessing Tuples:
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
Page 78
8.4 Traversing a Tuple:
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 <, <=, >, >=, ==, !=
Page 79
Joining Operator: It joins two or more tuples.
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]
Page 80
()
>>> 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.
https://pythonschoolkvs.wordpress.com/ Page 82
tuple- >>> subject.index("Maths")
name.index(element)
2
5 count( ) Return the number of >>> subject.count("English")
times the value appears.
Syntax: 1
tuple-
name.count(element)
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.
https://pythonschoolkvs.wordpress.com/ Page 83
Example:
>> 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
https://pythonschoolkvs.wordpress.com/ Page 84
CHAPTER-9
DICTIONARY IN PYTHON
9.1 INTRODUCTION:
Syntax:
Example:
>>> marks
>>> D
{ }
{'Maths': 81, 'Chemistry': 78, 'Physics': 75, 'CS': 78} # there is no guarantee that
https://pythonschoolkvs.wordpress.com/ Page 85
Note: Keys of a dictionary must be of immutable types, such as string, number, tuple.
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
https://pythonschoolkvs.wordpress.com/ Page 86
In this case the keys and values are enclosed separately in parentheses and are given as
argument to the zip( ) function. zip( ) function clubs first key with first value and so on.
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
https://pythonschoolkvs.wordpress.com/ Page 87
9.3 ACCESSING ELEMENTS OF A DICTIONARY:
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
https://pythonschoolkvs.wordpress.com/ Page 88
Example:
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}
https://pythonschoolkvs.wordpress.com/ Page 89
9.6 DELETE ELEMENTS FROM A DICTIONARY:
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
https://pythonschoolkvs.wordpress.com/ Page 90
9.7 CHECK THE EXISTANCE OF A KEY IN A DICTIONARY:
(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
https://pythonschoolkvs.wordpress.com/ Page 91
To print a dictionary in more readable and presentable form.
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:
https://pythonschoolkvs.wordpress.com/ Page 92
Program:
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( )
{}
https://pythonschoolkvs.wordpress.com/ Page 93
3. get( ) Returns value of a key. >>> marks.get("physics")
Syntax:
dictionary-name.get(key) 75
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}
https://pythonschoolkvs.wordpress.com/ Page 94
CHAPTER-10
SORTING
10.1 DEFINITION:
To arrange the elements in ascending or descending order.
https://pythonschoolkvs.wordpress.com/ Page 95
PROGRAM:
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]
https://pythonschoolkvs.wordpress.com/ Page 96
2. INSERTION SORT: Sorts the elements by shifting them one by one and inserting the
element at right position.
PROGRAM:
n=len(L)
for j in range(1,n):
temp=L[j]
prev=j-1
prev=prev-1
https://pythonschoolkvs.wordpress.com/ Page 97
OUTPUT:
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
https://pythonschoolkvs.wordpress.com/ Page 98
CHAPTER-11
DEBUGGING PROGRAMS
11.1 INTRODUCTION:
Errors in a program are known as ‘bugs’.
To remove the errors from a program, known as debugging.
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:
https://pythonschoolkvs.wordpress.com/ Page 99
a=10
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
https://pythonschoolkvs.wordpress.com/ Page 100
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
https://pythonschoolkvs.wordpress.com/ Page 103
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( )
https://pythonschoolkvs.wordpress.com/ Page 108
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
https://pythonschoolkvs.wordpress.com/ Page 112
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