Notes Updated
Notes Updated
x by R K PAL
Steps for problem solving
1. Analyzing the problem: It is important to clearly understand a problem before we begin to find the solution for
it. If we are not clear as to what is to be solved, we may end up developing a program which may not solve our
purpose. By analyzing a problem, we would be able to figure out what are the inputs that our program should
accept and the outputs that it should produce.
2. Developing an algorithm: It is essential to device a solution before writing a program code for a given problem.
The solution is represented in natural language and is called an algorithm. We can imagine an algorithm like a very
well-written recipe for a dish, with clearly defined steps that, if followed, one will end up preparing the dish.
3. Coding: After finalizing the algorithm, we need to convert the algorithm into the format which can be
understood by the computer to generate the desired solution. Different high level programming languages can be
used for writing a program.
4. Testing and debugging: The program created should be tested on various parameters. The program should meet
the requirements of the user. It must respond within the expected time. It should generate correct output for all
possible inputs. In the presence of syntactical errors, no output will be obtained.
A programmer writes a program to instruct the computer to do certain tasks as desired. The computer then follows
the steps written in the program code. Therefore, the programmer first prepares a roadmap of the program to be
written, before actually writing the code. And this is called algorithm in computer terms.
• it showcases the logic of the problem solution, excluding any implementation details
Example:
Let’s have an example preparing the early morning tea and write an algorithm for the same.
STEP 1 : START
STEP 2 : Pour water in a pan.
STEP 3 : Put the pan on gas burner.
STEP 4 : Light the gas burner.
STEP 5 : Put sugar in the pan.
STEP 6 : Put tea leaves in the pan.
STEP 7 : Pour milk in the pan.
STEP 8 : Filter the prepared tea in the cup.
STEP 9 : Serve it to others and enjoy yourself.
STEp 10 : STOP
There are two common methods of representing an algorithm —flowchart and pseudocode. Either of the methods
can be used to represent an algorithm while keeping in mind the following:
Page 1 of 66
Example:
Before developing the algorithm, let us first identify the input, process and output:
ALGORITHM
FLOWCHART
Following are some of the frequently used keywords while writing pseudocode: INPUT, COMPUTE, PRINT,
INCREMENT, DECREMENT, IF THEN/ELSE, WHILE, TRUE/FALSE
Page 2 of 66
Example
Write an algorithm to display the sum of two numbers entered by user, using both pseudocode and flowchart.
PSEUDOCODE FLOWCHART
input num1
input num2
COMPUTE Result = num1 + num2
PRINT Result
Decomposition
Sometimes a problem may be complex, that is, its solution is not directly derivable. In such cases, we need to
decompose it into simpler parts. The basic idea of solving a complex problem by decomposition is to 'decompose'
or break down a complex problem into smaller sub problems .These sub problems are relatively easier to solve
than the original problem. Finally, the subproblems are combined in a logical way to obtain the solution for the
bigger, main problem. In simple terms creating modules/functions is called decomposition.
Python Programming
Python is an open source, object oriented and interpreted high level language developed by Guido van Rossum in
1991. It is case sensitive language.
Characteristics of Python
Following are important characteristics of Python Programming −
>>> sys.version
Page 3 of 66
Python character set - A character set is a set of valid characters acceptable by a programming language in
scripting. Python supports all ASCII / Unicode characters that include:
Alphabets: All capital (A-Z) and small (a-z) alphabets.
Digits: All digits 0-9.
Special Symbols: Python supports all kind of special symbols like, ” ‘ l ; : ! ~ @ # $ % ^ ` & * ( ) _ + – = { } [ ] \ .
White Spaces: White spaces like tab space, blank space, newline, and carriage return.
Other: All ASCII and UNICODE characters are supported by Python that constitutes the Python character set.
Tokens - smallest individual unit of a python program.
Keyword - Reserved word that are case sensitive and has a special meaning. They can’t be used as an identifier.
There are 36 keywords.
>>> keyword.kwlist
['False', 'None', 'True', '__peg_parser__', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del',
'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise',
'return', 'try', 'while', 'with', 'yield']
Note: memorize all the keywords and learn the use of keywords highlighted
Identifiers - Meaningful names given to any variable/reference/object, constant, function or module etc.
Python is a case-sensitive language and it has some rules and regulations to name an identifier. Here are some rules
to name an identifier:-
As stated above, Python is case-sensitive. So case matters in naming identifiers. And hence geeks and Geeks are
two different identifiers.
Identifier starts with a capital letter (A-Z) , a small letter (a-z) or an underscore( _ ). It can’t start with any other
character.
Except for letters and underscore, digits can also be a part of identifier but can’t be the first character of it.
Any other special characters or whitespaces are strictly prohibited in an identifier.
An identifier can’t be a keyword.
Rvalue: It can be an already declared variable identifier or an expression or a literal. It appears in the right side of
the expression.
Example
Example:
Roll=12
Roll 12
String- The text enclosed in quotes (single/double/triple).
Comment- Comments are non-executable statement beginning with # sign. A multiline comment can be
represented either of 2 ways:
This creates a condition which results either True or False. Generally used with if and while statements.
Sample code
3. Assignment: =
This directly assigns a value or indirectly assigns a value or a literal of another variable.
Sample code
Page 5 of 66
x+=5 means x=x+5
i.e. first 5 is added to x and then the result is assigned to x.
Sample code
>>> x=10
>>> x+=5
>>> print(x)
>>> 15
5. Logical: and , or , not
and, or actually combines multiple conditions while not gives the complement
like x>5 and y<10 means
i.e. if value of x is 7 and y is 20 then x>5 will give True and y<10 will give False. And the True and False will give
False. Generally used with if and while statements.
>>> x=10
>>> y=10
>>> x is y
>>> True
Note: is actually checks the memory id.
7. Membership: in , not in
in operator actually checks the presence of a part in a string/list/tuple/dictionary. Generally used with for and if
statements
Sample code
Precedence of operators
The following table lists all operators from highest precedence to lowest.
Operator Description
( ) [ ] { }
, : . ` = ;
The following printing ASCII characters have special meaning as part of other tokens or are otherwise significant to
the lexical analyzer:
' " # \
At a very high level, it’s a way of translating characters (such as letters, punctuation, symbols, whitespace, and
control characters) to integers and ultimately to bits. Each character can be encoded to a unique sequence of bits.
Each single character has a corresponding code point, which you can think of as just an integer. Characters are
segmented into different ranges within the ASCII table:
The entire ASCII table contains 128 characters. This table captures the complete character set that ASCII permits. If
you don’t see a character here, then you simply can’t express it as printed text under the ASCII encoding scheme.
0 NUL (Null) 64 @
5 ENQ (Enquiry) 69 E
6 ACK (Acknowledgment) 70 F
7 BEL (Bell) 71 G
8 BS (Backspace) 72 H
9 HT (Horizontal Tab) 73 I
10 LF (Line Feed) 74 J
11 VT (Vertical Tab) 75 K
12 FF (Form Feed) 76 L
13 CR (Carriage Return) 77 M
14 SO (Shift Out) 78 N
15 SI (Shift In) 79 O
Page 8 of 66
Code Point Character (Name) Code Point Character (Name)
24 CAN (Cancel) 88 X
25 EM (End of Medium) 89 Y
26 SUB (Substitute) 90 Z
27 ESC (Escape) 91 [
28 FS (File Separator) 92 \
29 GS (Group Separator) 93 ]
30 RS (Record Separator) 94 ^
31 US (Unit Separator) 95 _
32 SP (Space) 96 `
33 ! 97 a
34 " 98 b
35 # 99 c
36 $ 100 d
37 % 101 e
38 & 102 f
39 ' 103 g
40 ( 104 h
41 ) 105 i
42 * 106 j
43 + 107 k
44 , 108 l
45 - 109 m
46 . 110 n
47 / 111 o
Page 9 of 66
Code Point Character (Name) Code Point Character (Name)
48 0 112 p
49 1 113 q
50 2 114 r
51 3 115 s
52 4 116 t
53 5 117 u
54 6 118 v
55 7 119 w
56 8 120 x
57 9 121 y
58 : 122 z
59 ; 123 {
60 < 124 |
61 = 125 }
62 > 126 ~
Today’s programs need to be able to handle a wide variety of characters. Python’s string type uses the Unicode
Standard for representing characters. Unicode is a specification that aims to list every character used by human
languages and give each character its own unique code. As you saw, the problem with ASCII is that it’s not nearly a
big enough set of characters to accommodate the world’s set of languages, dialects, symbols, and glyphs. Unicode
fundamentally serves the same purpose as ASCII, but it just encompasses a way, way, way bigger set of code points.
Python 3 is all-in on Unicode and UTF-8 specifically. Here’s what that means:
Python 3 source code is assumed to be UTF-8 by default. This means that you don’t need # -*- coding: UTF-
8 -*- at the top of .py files in Python 3.
All text (str) is Unicode by default. Encoded Unicode text is represented as binary data (bytes). The str type
can contain any literal Unicode character, such as "Δv / Δt", all of which will be stored as Unicode.
Page 10 of 66
*Such as English, Arabic, Greek, and Irish
**A huge array of languages and symbols—mostly Chinese, Japanese, and Korean by volume (also ASCII and Latin
alphabets)
***Additional Chinese, Japanese, Korean, and Vietnamese characters, plus more symbols and emojis
Sample code
2. int: It is a data structure of type numeric used to store a whole number. By default it stores 0. It is immutable.
Example to create a integer type reference
By assigning a value
X=45
By declaring
X=int()
Similarly for the rest
3. float: It is a data structure of type numeric used to store a number with a fractional part. By default it stores 0.0.
It is immutable.
4. Complex: It is a data structure of type numeric used to store a number having real and imaginary part (a+bj) . It is
immutable.
5. String: It is a data structure of type sequence used to store a collection of characters enclosed in single, double
or triple quotes. It is immutable, ordered and indexed. Can store duplicate values.
6. List: It is a data structure of type sequence used to store a list of comma separated values of any data type
between square [ ] brackets. It is mutable, ordered and indexed. Can store duplicate values.
7. Tuple: It is a data structure of type sequence used to store a list of comma separated values of any data type
between parentheses ( ). It is immutable, ordered and indexed. Can store duplicate values.
8. Set: It is a data structure used to store a list of comma separated values of any data type between curly braces {}
. It is immutable, unordered and unindexed. Cannot store duplicate values.
9. Dictionary: It is a data structure of type mapping used to store a collection of comma-separated key:value pairs ,
within curly braces {}. It is mutable and unordered. Can store duplicate values while the keys are immutable and
unique.
Page 11 of 66
Errors and its types
Syntax errors: These errors occur during runtime but suspends execution temporarily giving the error till it is
removed.
Examples
Invalid syntax
Indentation mismatch
Cannot assign to literal
EOL while scanning the literal
Runtime errors: Also known as exceptions. They occur during execution of the program and terminates in between
exiting back to the shell giving a traceback.
Some examples
1. OverflowError: Raised when a calculation exceeds maximum limit for a numeric type.
2. ArithmeticError : Base class for all errors that occur for numeric calculation.
3. FloatingPointError: Raised when a floating point calculation fails.
4. ZeroDivisionError:Raised when division or modulo by zero takes place for all numeric type
5. ImportError:Raised when an import statement fails.
6. IndexError:Raised when an index is not found in a sequence.
7. KeyError:Raised when the specified key is not found in the dictionary.
8. NameError: Raised when an identifier is not found in the local or global namespace.
9. IOError: Raised when an input/ output operation fails, such as the print statement or the open()
function when trying to open a file that does not exist.
10. IndentationError: Raised when indentation is not specified properly
11. TypeError: Raised when an operation or function is attempted that is invalid for the specified data
type.
12. ValueError: Raised when the built-in function for a data type has the valid type of arguments, but
the arguments have invalid values specified.
Logical errors: These errors are identified by the wrong output or an unexpected output. Example: to find the area
of a circle:
x=int(input(“Enter radius: “))
area=22/7*r+r
print(“area = “,area)
because of the wrong formula, the output is incorrect. This would be called a logical error
>>> -25%-3
-1
= -25 – (-25//-3) * -3
= -25 – (8) * -3
= -25 – (-24)
= -25 +24
= -1
Page 13 of 66
6 Addition
2+3
2.5+3
2.5+3.5
“mira”+”model”
7 3+5*5**2**2-8/4
3+5*5**4-8/4
3+5*625-8/4
3+3125-8/4
3+3125-2.0
3+3125-2.0
3128-2.0
3126.0
Built-in Functions
print and input functions: print() is used to display or give output to the user, while input() is to accept values from
the user
Code Output Remarks
Page 14 of 66
print(“hello”) hello
>>> print('hello') hello
>>> print('''hello mira hello mira
how are how are
you''') you
>>> print("he'll'o") he'll'o
>>> print("he'''ll'''o") he'''ll'''o
>>> print('he"ll"o') he"ll"o
>>> print('''he"ll"o he"ll"o 'mira' how are you
'mira' how are you''')
>>> input() '3'
3
>>> x=input()
mira
>>> x=input("Enter a Enter a number
number")
78
Strings
Strings: It is an ordered and immutable data structure to store multiple characters. It is implemented by assigning
consecutive characters within single or double or triple quotes.
Example
>>>s=’India is Great’
>>>print(s)
>>>India is Great
>>>s=”India is Great”
>>>print(s)
>>>India is Great
Single quotes is specially used when we need to use double quotes to highlight something
Example
>>>s=’India is a “Great” Country’
>>>print(s)
>>>India is a “Great” Country
Double quotes is specially used when we need to use single quotes to highlight something
Example
>>>s=”India is a ‘Great’ Country”
>>>print(s)
>>>India is a ‘Great’ Country
Page 15 of 66
Triple quotes is specially used for 2 purposes:
To declare a multiline string
Example
>>>s=’’’India is a country with
multiple languages and religions. People in this country
lives in peace and harmony’’’
>>>print(s)
India is a country with
multiple languages and religions. People in this country
lives in peace and harmony
To declare a multiline comment, applicable in script mode.
Traversal in Strings:
1. using for loop
Example
s=’India’
for i in s:
print(i,sep=’@’)
OUTPUT:I@n@d@i@a
s=’India’
for i in range(len(s)):
print(s[i],sep=’@’)
OUTPUT: I@n@d@i@a
2. using while loop
Example
s=’India’
i=0
while i<len(s):
print(i,sep=’@’)
i+=1
OUTPUT: I@n@d@i@a
Concatenation
Two strings get concatenated with the help of + operator.
Example
Page 16 of 66
s1=’India’
s2=’USA’
s3=s1+s2
print(s3)
OUTPUT: IndiaUSA
Repetition
If a string is multiplied with an integer using * operator, the string gets repeatedly concatenated that
number of times.
Example
s1=’India’
print(3*s1)
OUTPUT: IndiaIndiaIndia
Membership
A string (single or multiple character(s)) is checked for its presence in another string using in operator.
Example
s1=’India’
‘n’ in ‘India’
OUTPUT: True
‘nd’ in ‘India’
OUTPUT: True
‘N’ in ‘India’
OUTPUT: False
Methods of a string:
1. count(substring, start=..., end=...) – The string count() method returns the number of occurrences
of a substring in the given string.
count() method only requires a single parameter for execution. However, it also has two optional
parameters:
● substring - string whose count is to be found.
● start (Optional) - starting index within the string where search starts.
● end (Optional) - ending index within the string where search ends.
2. find(sub[, start[, end]]) – The find() method returns the index of first occurrence of the substring (if
found). If not found, it returns -1.
The find() method takes maximum of three parameters:
● sub - It is the substring to be searched in the str string.
● start and end (optional) - The range str[start:end] within which substring is searched.
3. isupper() – returns True if the string contains all upper case characters otherwise False.
4. islower() - returns True if the string contains all lower case characters otherwise False.
5. isdigit() – returns True if every character in the string is a numeric digit otherwise False.
6. isalpha() - returns True if every character in the string is an alphabet otherwise False.
7. isalnum() - returns True if every character in the string is an alphabet or a numeric digit otherwise
False.
8. isspace() - returns True if every character in the string is a space otherwise False.
9. title() – converts the first alphabet of every word in the string to upper case and rest
of the alphabets to lower case.
10. capitalize() – converts the first alphabet of a string to upper case and all the rest
alphabets to lower case.
11. swapcase() – converts the upper case characters to lower case and vice versa.
12. replace(old, new [ , count] ) – The replace() method returns a copy of the string where all
occurrences of a substring is replaced with another substring.
The replace() method can take maximum of 3 parameters:
● old - old substring you want to replace
● new - new substring which will replace the old substring
Page 17 of 66
● count (optional) - the number of times you want to replace the old substring with the
new substring
Note: If count is not specified, the replace() method replaces all occurrences of the old
substring with the new substring.
13. upper() – converts all the lower case alphabets to upper case in the string.
14. lower() - converts all the upper case alphabets to lower case in the string.
15. split([separator [, maxsplit]]) – The split() method breaks up a string at the specified separator
and returns a list of strings.
split() method takes a maximum of 2 parameters:
● separator (optional)- It is a delimiter. The string splits at the specified separator.
If the separator is not specified, any whitespace (space, newline etc.) string is a
separator.
● maxsplit (optional) - The maxsplit defines the maximum number of splits.
The default value of maxsplit is -1, meaning, no limit on the number of splits.
16. partition(separator) - The partition() method splits the string at the first occurrence of the
argument string and returns a tuple containing the part the before separator, argument string
and the part after the separator.
17. strip(chars[]) - The strip() method removes characters from both left and right based on the
argument (a string specifying the set of characters to be removed).
18. lstrip(chars[])- It removes characters from the left based on the argument (optional - a string
specifying the set of characters to be removed).
19. rstrip(chars[])- It removes characters from the right based on the argument (optional - a string
specifying the set of characters to be removed).
Examples:
>>> s='India and Mandela' >>> s="india is great"
>>> s.find('nd') >>> s.index('ia')
1 3
>>> s.find('nd',3,10) >>> s.index('ia',5,9)
7 Traceback (most recent call last):
>>> s.find('nd',3,15) File "<pyshell#25>", line 1, in <module>
7 s.index('ia',5,9)
>>> s.find('nd',10,15) ValueError: substring not found
12 >>> s.index('i',5,9)
>>> s.find('pd',1,15) 6
-1 >>> s='India and Mandela'
>>> s.count('nd') >>> s.isupper()
3 False
>>> s.count('nd',3,10) >>> s.islower()
1 False
>>> s.count('nd',3) False
2 >>> s.isalpha()
>>> s.count('nd',3,15) False
2 >>> s.isdigit()
>>> s.count('pd') False
0 >>> s.isspace()
>>> s.capitalize() False
'India and mandela' >>> s.isalpha()
>>> s.title() False
'India And Mandela' >>> s.upper()
>>> s 'INDIA AND MANDELA'
'India and Mandela' >>> s.lower()
'india and mandela'
>>> s="mira model mira model mira school miraml" >>> s="miramodel"
>>> s.replace("mira","happy") >>> s.partition(' ')
'happy model happy model happy school happyml' ('miramodel', '', '')
>>> s="mira model mira model mira school miraml" >>> s.partition('m')
Page 18 of 66
>>> s.replace("mira","happy",2) ('', 'm', 'iramodel')
'happy model happy model mira school miraml' >>> s.partition('o')
>>> s="mira model school" ('miram', 'o', 'del')
>>> s.split() >>> s.partition('am')
['mira', 'model', 'school'] ('mir', 'am', 'odel')
>>> s.split('d') >>> s=" mira"
['mira mo', 'el school'] >>> s.lstrip()
>>> s.split('l') 'mira'
['mira mode', ' schoo', ''] >>> s="M mira"
>>> s.split('pq') >>> s.lstrip("M")
['mira model school'] ' mira'
>>> s="M mira"
>>> s.lstrip("M ")
'mira'
Slicing in a String :
A string when declared is indexed left to right by positive numbers starting from 0 to len(string)-1 while
right to left by negative numbers starting from -1 to -len(s).
>>> S='MIRA MODEL'
>>> len(S)
10
Python Lists
List is a python data structure that represents a heterogeneous collection or a sequence of items which is ordered
and mutable. Allows duplicate members. In Python, lists are written with square brackets.
Creating a List
L1 = ["apple", "banana", "cherry"]
print(L1)
Indexing
Same as strings
Access Items
You access the list items by referring to the index number:
Example
Print the second item of the list:
print(L1[1]) or print(L1[-2])
Slicing
Same as strings
Page 20 of 66
Change the second item:
L1[1] = "blackcurrant"
print(L1)
Example
Check if "apple" is present in the list:
L = ["apple", "banana", "cherry"]
if "apple" in L:
print("Yes, 'apple' is in the fruits list")
List Length
To determine how many items a list has, use the len() function:
Example
Print the number of items in the list:
L = ["apple", "banana", "cherry"]
print(len(L))
Traversing a List You can loop through the list items by using a for loop:
Example
Print all items in the list, one by one:
L = ["apple", "banana", "cherry"]
method 1
for x in L:
print(x)
method 2
for i in range(len(L)):
print(L[i])
Remove an Item from a list There are several methods to remove items from a list:
Example
The remove() method removes the specified item:
L = ["apple", "banana", "cherry"]
L.remove("banana")
print(L)
Page 21 of 66
Example
The pop() method removes the specified index, (or the last item if index is not specified):
L = ["apple", "banana", "cherry"]
L.pop()
print(L)
Example
The del keyword removes the specified index:
L = ["apple", "banana", "cherry"]
del L[0]
print(L)
Example
The del keyword can also delete the list completely:
L = ["apple", "banana", "cherry"]
del L
Example
The clear() method empties the list:
L = ["apple", "banana", "cherry"]
L.clear()
Copy a List
You cannot copy a list simply by typing list2 = list1, because: list2 will only be a reference to list1, and changes made
in list1 will automatically also be made in list2.
There are ways to make a copy, one way is to use the built-in List method copy().
Example
Make a copy of a list with the copy() method:
L = ["apple", "banana", "cherry"]
mylist = L.copy()
print(mylist)
Another way to make a copy is to use the built-in method list().
Example
Make a copy of a list with the list() method:
L = ["apple", "banana", "cherry"]
mylist = list(L)
print(mylist)
0 1 2 0 1 2
L1/L2 L1
10 20 30 10 20 30
0 1 2
L2
Another way to join two lists are by appending all the items from list2 into list1, one by one:
Example
Append list2 into list1:
list1 = ["a", "b" , "c"]
list2 = [1, 2, 3]
for x in list2:
list1.append(x)
print(list1)
Or you can use the extend() method, which purpose is to add elements from one list to another list:
Example
Use the extend() method to add list2 at the end of list1:
list1 = ["a", "b" , "c"]
list2 = [1, 2, 3]
list1.extend(list2)
print(list1)
Nested Lists
list1 = ("a", "b" , "c",(1,2,3),”d”)
print(list1[3]) # (1,2,3)
print(list1[3][1]) # 2
Built in functions
len(): To find the number of items in a list
list(): To create an empty list or change the data type of a sequence into list.
sorted(): To return a sorted list.
sorted(l) – ascending order
sorted(l, Reverse=True) – descending order
min(): To return the minimum value from the list
max():To return the maximum value from the list
sum():To return the sum of all the values in the list
List Methods
Python has a set of built-in methods that you can use on lists.
append(): Adds an element at the end of the list clear() Removes all the elements from the list copy() Returns a
copy of the list
count(): Returns the number of elements with the specified value
extend(): Add the elements of a list (or any iterable), to the end of the current list
index(): Returns the index of the first element with the specified value
insert(): Adds an element at the specified position
pop(): Removes the element at the specified position
remove(): Removes the item with the specified value
reverse(): Reverses the order of the list sort() Sorts the list
Python Tuples
A tuple is an ordered collection of heterogeneous items which is immutable. In Python, tuples are written with
round brackets.
Page 23 of 66
Creating a Tuple
T = ("apple", "banana", "cherry")
print(T)
Indexing
Same as strings
Access Items
You access the list items by referring to the index number:
Example
Print the second item of the list:
print(T[1]) or print(T[-2])
Slicing
Same as strings
for x in T:
print(x)
Tuple Length
To determine how many items a tuple has, use the len() method:
Example
Print the number of items in the tuple:
T = ("apple", "banana", "cherry")
print(len(T))
Page 24 of 66
Add Items
Once a tuple is created, you cannot add items to it. Tuples are unchangeable.
Example
You cannot add items to a tuple:
T = ("apple", "banana", "cherry")
T[3] = "orange" # This will raise an error print(T)
Method2:
T+=(“orange”,)
print(T)
print(type(T))
Remove Items
Note: You cannot remove items in a tuple.
Tuples are unchangeable, so you cannot remove items from it, but you can delete the tuple completely:
Example
The del keyword can delete the tuple completely:
T = ("apple", "banana", "cherry")
del T
print(T) #this will raise an error because the tuple no longer exists
Tuple Methods
Python has two built-in methods that you can use on tuples.
count(): Returns the number of times a specified value occurs in a tuple
index(): Searches the tuple for a specified value and returns the position of where it was found
Built in functions
len(): To find the number of items in a tuple
tuple(): To create an empty tuple or change the data type of a sequence into tuple.
Page 25 of 66
sorted(): To return a sorted list.
sorted(t) – ascending order
sorted(t, Reverse=True) – descending order
min(): To return the minimum value from the tuple
max():To return the maximum value from the tuple
sum():To return the sum of all the values in the tuple
Dictionary
Dictionary is an unordered collection of items(key-value pairs). Each key is separated from its value by a colon (:),
the items are separated by commas, and the whole thing is enclosed in curly braces. An empty dictionary without
any items is written with just two curly braces, like this: {}.
Keys are unique within a dictionary while values may not be. The values of a dictionary can be of any type, but the
keys must be of an immutable data type such as strings, numbers, or tuples
Dictionary keys are case sensitive- Same key name but with the different case are treated as different
keys in Python dictionaries.
Keys will be a single element. Values can be a list or list within a list, numbers, etc.
Dictionary values have no restrictions. They can be any arbitrary Python object, either standard objects or user-
defined objects. However, same is not true for the keys.
There are two important points to remember about dictionary keys −
(a) More than one entry per key is not allowed. This means no duplicate key is allowed. When duplicate keys are
encountered during assignment, the last assignment wins
(b) Keys must be immutable. This means you can use strings, numbers or tuples as dictionary keys
but something like ['key'] is not allowed.
Create a dictionary
D = { "brand": "Ford", "model": "Mustang", "year": 1964 }
print(D)
Accessing Items
You can access the items of a dictionary by referring to its key name, inside square brackets:
Example
Get the value of the "model" key:
x = D["model"]
There is also a method called get() that will give you the same result:
Example
Get the value of the "model" key:
x = D.get("model")
Change Values
You can change the value of a specific item by referring to its key name:
Example
Change the "year" to 2018:
D["year"] = 2018
Page 26 of 66
Print all values in the dictionary, one by one:
for x in D:
print(D[x])
Example
You can also use the values() method to return values of a dictionary:
for x in D.values():
print(x)
Example
Loop through both keys and values, by using the items() method:
for x, y in D.items():
print(x, y)
Dictionary Length
To determine how many items (key-value pairs) a dictionary has, use the len() function. Example
Print the number of items in the dictionary:
print(len(D))
Adding Items
Adding an item to the dictionary is done by using a new index key and assigning a value to it:
D["color"] = "red"
print(D)
Removing Items
There are several methods to remove items from a dictionary:
Example
The pop() method removes the item with the specified key name:
D.pop("model")
print(D)
Example
The popitem() method removes the last inserted item (in versions before 3.7, a random item is removed instead):
D.popitem()
print(D)
The del keyword removes the item with the specified key name:
del D["model"]
print(D)
Example
The del keyword can also delete the dictionary completely:
Page 27 of 66
del D
print(D) #this will cause an error because "D" no longer exists.
Example
The clear() method empties the dictionary:
D.clear()
print(D)
Copy a Dictionary
You cannot copy a dictionary simply by typing dict2 = dict1, because: dict2 will only be a reference to dict1, and
changes made in dict1 will automatically also be made in dict2.
There are ways to make a copy, one way is to use the built-in Dictionary method copy().
Example
Make a copy of a dictionary with the copy() method:
D={
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
mydict = D.copy()
print(mydict)
Another way to make a copy is to use the built-in function dict().
Example
Make a copy of a dictionary with the dict() function:
D={
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
mydict = dict(D)
print(mydict)
Built in functions
len(): To find the number of items in a dictionary
dict(): To create an empty dictionary.
sorted(): To return a sorted list of keys.
sorted(d) – ascending order
sorted(d, Reverse=True) – descending order
min(): To return the minimum key from the dictionary
max():To return the maximum key from the dictionary
sum():To return the sum of all the keys in the dictionary
Dictionary Methods
clear(): Removes all the elements from the dictionary
copy(): Returns a copy of the dictionary
fromkeys(): Returns a dictionary with the specified keys and value
get(): Returns the value of the specified key
items(): Returns a list containing a tuple for each key value pair
keys(): Returns a list containing the dictionary's keys
pop(): Removes the element with the specified key
popitem(): Removes the last inserted key-value pair
setdefault(): Returns the value of the specified key. If the key does not exist: insert the key, with the specified
value
update(): Updates the dictionary with the specified key-value pairs
values(): Returns a list of all the values in the dictionary
Page 28 of 66
Each module is a collection of functions
1. math
2. random
3. statistics
4. pickle
5. os
6. csv
To use a function from a module, the module needs to be imported and then the function in the
module is called using a dot operator
example:
If we need to call randint() from random module.
Method 1 Method 2 Method 3
import random from random import randint from random import *
x=random.randint(2,8) x=randint(2,8) x=randint(2,8)
Page 29 of 66
os module functions
1. rename() – to rename an external file
2. remove() – to remove an external file
These two are generally used when deleting data from a text/binary file or while modifying data in a text/binary file
2. writer()- to write the data from the python list into a csv file
3. DictReader()- to read the data from the csv file into a python dictionary
4. DictWriter() –to write the data from a python dictionary into a csv file
In Explicit Type Conversion, users convert the data type of an object to required data type. We use the predefined
functions like int(), float(), str(), etc to perform explicit type conversion.
This type conversion is also called typecasting because the user casts (change) the data type of the objects.
n= 123
type(n) is int
str = "456"
type(str) is string
str= int(str)
type(str) is int
nsum = n+ str
type(nsum) is int
Ans 579
Page 30 of 66
Python programming language assumes any non-zero and non-null values as TRUE, and if it is either
zero or null, then it is assumed as FALSE value.
If ..elif..else
Python programming language provides following types of decision making statements.
1 if statements
An if statement consists of a boolean expression followed by one or more statements.
Syntax
if expression:
statement(s)
2 if...else statements
An if statement can be followed by an optional else statement, which executes when the
boolean expression is FALSE.
Syntax
if expression:
statement(s)
else:
statement(s)
Page 31 of 66
3 If ...elif...else statements
Syntax
if expression1:
statement(s)
elif expression2:
statement(s)
elif expression3:
statement(s)
else:
statement(s)
4 nested if statements
You can use one if or else if statement inside another if or else if statement(s).
If expression1:
statement(s)
if expression2:
statement(s)
elif expression3:
statement(s)
else:
statement(s)
elif expression4:
statement(s)
else:
statement(s)
Loops
A loop statement allows us to execute a statement or group of statements multiple times.
Page 32 of 66
The following diagram illustrates a loop statement −
Python programming language provides following types of loops to handle looping requirements.
Syntax
while expression:
statement(s)
Page 33 of 66
Infinite loop Loop stepping Loop stepping downward
while True: upward i=10
print(“Hello”) i=1 sum=0
sum=0 while i>=1:
while i<=5: sum+=i
sum+=i i-=3
i+=1 print(“Total is ”,sum)
print(“Total is ”,sum)
Loop with else
i=1
while i<=5: The else of while gets executed only when the break
x=int(input(“enter x”)) is not executed. In other words when the loop gets
if x%5==0: terminated normally.
break
sum+=x
i+=1
else:
print(“Thank you”,i)
print(“Total is ”,sum,i)
2 for loop
Executes a sequence of statements multiple times and abbreviates the code that manages the
loop variable.
Syntax
for iterating_var in sequence:
statements(s)
Page 34 of 66
for i in “india”: for i in range(5): for i in range(1,5):
print(i) print(i) print(i)
nested loops
You can use one or more loop inside another.
Syntax
for iterating_var in sequence:
for iterating_var in sequence:
statements(s)
statements(s)
while expression:
while expression:
statement(s)
statement(s)
while True:
print(“Hello”)
• If the else statement is used with a for loop, the else statement is executed when the loop has
exhausted iterating the list.
• If the else statement is used with a while loop, the else statement is executed when the condition
becomes false.
1 break statement
Terminates the loop statement and transfers execution to the statement immediately following
the loop.
2 continue statement
Causes the loop to skip the remainder of its body and immediately retest its condition prior to
reiterating in case of while and assign the next value generated by range or in to start with the
next iteration.
3 pass statement
The pass statement in Python is used when a statement is required syntactically but you do not
want any command or code to execute.
If we want the list of values to start at a value other than 0, we can do that by specifying the starting value. The
statement range(1,5) will produce the list 1, 2, 3, 4. This brings up one quirk of the range function—it stops one
short of where we think it should. If we wanted the list to contain the numbers 1 through 5 (including 5), then we
would have to do range(1,6).
Another thing we can do is to get the list of values to go up by more than one at a time. To do this, we can specify
an optional step as the third argument. The statement range(1,10,2) will step through the list by twos, producing 1,
3, 5, 7, 9.
To get the list of values to go backwards, we can use a step of -1. For instance, range(5,1,-1) will produce the values
5, 4, 3, 2, in that order. (Note that the range function stops one short of the ending value 1). Here are a few more
examples:
range(10) 0,1,2,3,4,5,6,7,8,9
range(1,10) 1,2,3,4,5,6,7,8,9
range(3,7) 3,4,5,6
range(2,15,3) 2,5,8,11,14
range(9,2,-1) 9,8,7,6,5,4,3
Here is an example program that counts down from 5 and then prints a message.
for i in range(5,0,-1):
print('Blast off!!')
Page 36 of 66
54321
Blast off!!!
Functions
Function - It is a subprogram or a sub task (a set of instructions grouped together). A function is created when a
sub task is required to be executed multiple times at multiple places in a program. It helps in reducing the code,
faster execution( that is less time consumption in interpreting).
Types of function (built-in functions, functions defined in module, user defined functions)
Example:
built-in functions: type(), id(), ord() etc
module functions: module name math and it’s functions sin() pow(), round()
user defined functions: programmer defined, it needs to be a valid identifier like find_prime()
Defining a Function:
You can define functions to provide the required functionality. Here are simple rules to define a function in Python.
1. Function blocks begin with the keyword def followed by the function name and parentheses ( ( ) ).
2. Any input parameters or arguments should be placed within these parentheses.
3. The code block within every function starts with a colon (:) and is indented.
4. The statement return [expression] exits a function, optionally passing back an expression to the caller. A return
statement with no arguments is the same as return None.
Syntax
def functionname( parameters ):
function_body return
[expression]
By default, parameters have a positional behavior and you need to inform them in the same order that they were
defined.
Function Arguments
You can call a function by using the following types of formal arguments −
● required arguments
● Positional arguments
● Keyword arguments
● Default arguments
Required arguments
These arguments are the arguments passed to a function. Here, the number of arguments in the function call
should match exactly with the function definition.
To call the function abc(), you definitely need to pass two argument, otherwise it gives a syntax error as follows
def abc(x,y):
z=x+y
print(z)
abc(5,6) # correct
Page 37 of 66
abc(5) # incorrect
Positional arguments
These arguments are the arguments passed to a function in correct positional order. Here, the number of
arguments in the function call should match exactly with the function definition.
To call the function calinterest(), you definitely need to pass three arguments and in proper order, otherwise it
gives a syntax error/incorrect output as follows −
cal_comp_interest(1000,2,3) # as per position principal will get 1000, rate will get 2 and time will get 3
but if we call as
cal_comp_interest(2,3,1000) # as per position principal will get 2, rate will get 3 and time will get 1000
and this will result into a wrong calculation of ci
Keyword arguments
Keyword arguments are related to the function calls. When you use keyword arguments in a function call, the caller
identifies the arguments by the parameter name.
This allows you to skip arguments or place them out of order because the Python interpreter is able to use the
keywords provided to match the values with parameters.
def add( val1,val2 ):
val2=val2+10
print(val1,val2)
add( val2=7,val1=6)
#output: 11 17
Default arguments
A default argument is an argument that assumes a default value if a value is not provided in the function call for
that argument. The following example gives an idea on default arguments, it
prints default age if it is not passed −
def printinfo( name, age = 35 ):
print("Name: ", name)
print("Age ", age)
# Now you can call printinfo function
printinfo( age=50, name="miki" )
printinfo( name="miki" )
When the above code is executed, it produces the following result −
Name: miki Age 50
Name: miki
Age 35
def abc():
p=int(input('Enter principal:'))
r=int(input('Enter rate:'))
t=int(input('Enter time:'))
si=p*r*t/100
print('Simple interest fn-abc():',si)
abc()
def abc1(p,r,t):
si=p*r*t/100
print('Simple interest fn-abc1():',si)
p=int(input('Enter principal:'))
r=int(input('Enter rate:'))
t=int(input('Enter time:'))
abc1(p,r,t)
def abc2():
p=int(input('Enter principal:'))
r=int(input('Enter rate:'))
t=int(input('Enter time:'))
si=p*r*t/100
return si
print('Simple interest:',abc2())
def abc3(p,r,t):
si=p*r*t/100
return si
p=int(input('Enter principal:'))
r=int(input('Enter rate:'))
t=int(input('Enter time:'))
print('Simple interest :',abc3(p,r,t))
Page 39 of 66
def abc4(p,r,t):
si=p*r*t/100
ci=p*(1+r/100)**t -p
return si,ci
p=int(input('Enter principal:'))
r=int(input('Enter rate:'))
t=int(input('Enter time:'))
si,ci=abc4(p,r,t)
print('Simple interest:',si)
print('Compound Interest:',ci)
def abc5(p,r,t):
si=p*r*t/100
ci=p*(1+r/100)**t -p
return si,ci
p=int(input('Enter principal:'))
r=int(input('Enter rate:'))
t=int(input('Enter time:'))
interest=abc4(p,r,t)
print('Simple interest :',interest[0])
print('Compound Interest :',interest[1])
def abc6(l1):
l1.sort()
m=max(l1)
return l1,m
l1=[10,5,60,35,67,1]
print(l1)
l1,m=abc6(l1)
print('The sorted list is :',l1)
print('The maximum value is :',m)
def abc7(d,s):
for i in d:
if d[i][0]==s:
tmarks=sum(d[i][1])
break
else:
Page 40 of 66
tmarks=-1
return tmarks
d={1:['raj',[67,89,90]],2:['joy',[90,87,45]],3:['sohan',[87,76,83]]}
print(d)
s=input('Enter the name whose total marks u want: ')
tm=abc7(d,s)
if tm>=0:
print('The total marks of ',s,' is ',tm)
else:
print(s,' does not exist')
Passing multiple values (non keyword arguments) and catching in a list using *
def abc(*l):
for i in l:
print(i,end=" ")
abc(10,20,30,40)
output:
10 20 30 40
Passing multiple named values (keyword arguments) and catching in a dictionary using **
def abc(**d):
for i in d:
print(i,d[i])
abc(x=10,y=20,z=30,w=40)
Page 41 of 66
output:
x 10
y 20
z 30
w 40
Example
def swap(): Using global variables inside a Changing global variables inside a
p=10 # local function function
q=20 # local def swap(): def swap():
print(p,q) p=10 # local global x,y
q=20 # local temp=x # local
x=100 # global print(p+x,q+y) x=y
y=200 # global y=temp
print(x,y) x=100 # global
swap() y=200 # global x=100 # global
print(x,y) print(x,y) y=200 # global
swap() print(x,y)
print(x,y) swap()
print(x,y)
100 200 100 200 100 200
10 20 110 220 200 100
100 200 100 200
Files in Python
Files are named locations on disk to store related information.
They are used to permanently store data in a non-volatile memory (e.g. hard disk).
Page 42 of 66
Since Random Access Memory (RAM) is volatile (which loses its data when the computer is turned off), we use files
for future use of the data by permanently storing them.
When we want to read from or write to a file, we need to open it first. When we are done, it needs to be closed so
that the resources that are tied with the file are freed.
Hence, in Python, a file operation takes place in the following order:
Open a file -> Read or write (perform operation) -> Close the file
Two ways to open a file
file=open(“welcome.txt”) with open(“welcome.txt” as file:
data=file.read() data=file.read()
… …
file.close() File does not need to be closed
File needs to closed
3 r+ - Opens a file for both reading and writing in text format. If the files already exists, it is
opened and the file pointer placed at the beginning of the file otherwise it gives an error.
4 rb+ - Opens a file for both reading and writing in binary format. If the files already exists, it is
opened and the file pointer placed at the beginning of the file otherwise it gives an error.
5 w - Opens a file for writing only in text format. Overwrites the file if the file exists. If the file
does not exist, creates a new file for writing.
6 wb - Opens a file for writing only in binary format. Overwrites the file if the file exists. If the
file does not exist, creates a new file for writing.
7 w+ - Opens a file for both writing and reading in text format. Overwrites the existing file if
the file exists. If the file does not exist, creates a new file for reading and writing.
8 wb+ - Opens a file for both writing and reading in binary format. Overwrites the existing file
if the file exists. If the file does not exist, creates a new file for reading and writing.
9 a - Opens a file for appending in text format. The file pointer is at the end of the file if the file
exists. That is, the file is in the append mode. If the file does not exist, it creates a new file for
writing.
10 ab - Opens a file for appending in binary format. The file pointer is at the end of the file if the
file exists. That is, the file is in the append mode. If the file does not exist, it creates a new
file for writing.
11 a+ - Opens a file for both appending and reading in text format. The file pointer is at the end
of the file if the file exists and the file opens in the append mode. If the file does not exist, it
creates a new file for reading and writing.
Page 43 of 66
12 ab+ - Opens a file for both appending and reading in binary format. The file pointer is at the
end of the file if the file exists and the file opens in the append mode. If the file does not
exist, it creates a new file for reading and writing.
Text Files
First we will learn about text files, a file that is readable and writable using a text editor(Notepad) and the content
are ASCII/UniCode characters is called a text file. A text file conventionally has an extension “.txt”
2. read(n) – reads n characters in a single/multiline string from the current position of file pointer till the end in the
file.
3. readline() – reads a line in a single line string from the current position of file pointer in the file. Please note EOL
or \n is also extracted as the last character in the string
4. readlines() – reads all the lines in a list ( list of strings where each line is a string) from the current position of file
pointer till the end in the file. Please note EOL or \n is also extracted as the last character in the string
5. write() - writes a single character or a word or a line or multiple lines
print("Number of words=",len(l))
print("Number of capital words=",u)
print("Number of small words=",lw)
print("Number of words beginning with capital=",a)
print("Number of words ending with small=",b)
f.close()
Example5 : using readlines() Note: to display all the lines starting with a vowel using
def read_file5(file): readlines() method. Please note that while using
f=open(file,"r") readlines() only one read is required while using
l=f.readlines() readline() multiple read is required in an infinite loop
for i in l: which leads to a runtime error while performing the
print(i,end="") last read, so try except blocks are used.
f.close()
f.close()
Page 45 of 66
Example9 -to change the upper case to lower case and vice versa in the file
import os
def modify_file1():
f=open("mira.txt","r")
f1=open("temp.txt","w")
s=f.read()
s1=s.swapcase()
f1.write(s1)
f.close()
f1.close()
os.remove("mira.txt")
os.rename("temp.txt","mira.txt")
import os
def delete_file1():
f=open("mira.txt","r")
f1=open("temp.txt","w")
s=f.read()
s1=""
for i in s:
if i not in s1:
s1+=i
f1.write(s1)
f.close()
f1.close()
os.remove("mira.txt")
os.rename("temp.txt","mira.txt")
Binary Files
Pickle is used for serializing and de-serializing Python object. Serialization refers to the process of converting an object
in memory to a byte stream that can be stored on disk (backing storage). Later on, this byte stream can then be
retrieved and de-serialized back to a Python object (variable). In Python process of serialization and de-serialization
is called is pickling. For pickling in Python has pickle module.
Page 46 of 66
Built-in function open() creates a file object. Generally, a binary data has extension .DAT, but a binary data file
can have any other extension. When opening a binary data file, the mode parameter has an extra letter 'b' to
indicate that the data file MYDATA.DAT is a binary data file.
• pickle.dump(data, fobj) – function from pickle module and it writes values stored in the variable data, into a
binary file using file object fobj. Variable data represents data either as a list(tuple) or as a dictionary. In fact
function dump() transfers data to the fobj.
• data=pickle.load(fobj) – is function from pickle module and it reads data from a binary data file using file object
fobj, into a variable (object) data. Variable data can either be a list(tuple) or dictionary type depending how the
data was dumped. If the binary file was created using a list(tuple), then pickle.load(fobj) will read a list(tuple) and
store the data in the variable data. If the binary file was created using a dictionary, then pickle.load(fobj) will read
a dictionary and store the data in the variable data.
• fobj.close() – will close a binary data file using the file object fobj.
Example1: Python function to add a single list with sub lists as records in a binary data file
import pickle
def addrec():
emp=[]
fobj=open('SALARY.DAT', 'ab')
for k in range(5):
code=int(input('Code? '))
name=input('Name? ')
bsal=float(input('BSal? '))
emp+=[code, name.upper(), bsal]
pickle.dump(emp, fobj)
fobj.close()
Variable fobj is a binary data file object created with open(). File mode contains 2-characters string. Letter 'a' for
append mode and letter 'b' for binary. If a binary file is to be opened in write mode, then letter 'w' will replace letter
'a'. Data to be written into the binary is a list emp. Statement pickle.dump(emp, fobj) writes a record into a binary
file data file. One record is written at a time in the binary data file. A binary file can store dictionary type data also.
Example2: Function is given below showing how to add a single dictionary with multiple key:value pairs in a binary
data file:
import pickle
def addrec():
fobj=open('SALARY.DAT', 'ab')
d={}
for k in range(3):
code=int(input('Code? '))
name=input('Name? ')
bsal=float(input('BSal? '))
d.update({code:[name,bsal]})
pickle.dump(d, fobj)
fobj.close()
Example3: Python function to display a binary data file containing a single list of data(with
reference to Example1):
import pickle
def showrec():
fobj=open('SALARY.DAT', 'rb')
emp=pickle.load(fobj)
for i in emp:
print(i[0],i[1],i[2])
Page 47 of 66
fobj.close()
Example4: Python function to display a binary data file containing a single dictionary of
data(with reference to Example2):
import pickle
def showrec():
fobj=open('SALARY.DAT', 'rb')
emp=pickle.load(fobj)
for i in emp:
print(i,emp[i][0],emp[i][1])
fobj.close()
Example5: Python function to add multiple lists as records in a binary data file
import pickle
def addrec():
fobj=open('SALARY.DAT', 'ab')
for k in range(5):
code=int(input('Code? '))
name=input('Name? ')
bsal=float(input('BSal? '))
emp=[code, name.upper(), bsal]
pickle.dump(emp, fobj)
fobj.close()
Example6: Function is given below showing how to add multiple dictionaries in a binary data file:
import pickle
def addrec():
fobj=open('SALARY.DAT', 'ab')
for k in range(3):
d={}
code=int(input('Code? '))
name=input('Name? ')
bsal=float(input('BSal? '))
d[code]=[name,bsal]
pickle.dump(d, fobj)
fobj.close()
Example7: Python function to display a binary data file containing multiple lists of data(with
reference to Example5):
import pickle
def showrec():
fobj=open('SALARY.DAT', 'rb')
try:
while True:
emp=pickle.load(fobj)
for i in emp:
print(i[0],i[1],i[2])
except:
fobj.close()
Example8: Python function to display a binary data file containing multiple dictionaries of
data(with reference to Example6):
import pickle
Page 48 of 66
def showrec():
fobj=open('SALARY.DAT', 'rb')
try:
while True:
emp=pickle.load(fobj)
for i in emp:
print(i,emp[i][0],emp[i][1])
except:
fobj.close()
Kindly note: number of load() must match number dump() when reading from a binary data file. Since it impossible
to remember the count, try-except is used to read from a binary file without triggering any run-time (exception)
error. Data in a binary data file can be stored either as a list type or a dictionary type or any other type, but hence
forth, all the functions will assume that the data is stored as a list in the binary data file.
Example9: Function to search for code in a binary data file (containing list type of data) is given
below:
import pickle
def searchcode():
code=int(input('Code to Search? '))
fobj=open('SALARY.DAT', 'rb')
found=0
try:
while True:
emp=pickle.load(fobj)
if code==emp[0]:
print(emp[0],emp[1],emp[2],sep='\t')
found=1
break
except:
fobj.close()
if found==0:
Example10: Function to search for name in a binary data file (containing list type of data) is given
below:
import pickle
def searchname():
name=input('Name to Search? ')
fobj=open('SALARY.DAT', 'rb')
found=0
try:
while True:
emp=pickle.load(fobj)
if name.upper()==emp[1]:
print(emp[0],emp[1],emp[2],sep='\t')
found=1
break
except:
fobj.close()
Page 49 of 66
if found==0:
Example11: Function to search for salary in a binary data file (containing list type of data) is given
below:
import pickle
def searchbsal():
fobj=open('SALARY.DAT', 'rb')
c=0
try:
while True:
emp=pickle.load(fobj)
if emp[2]>150000.0:
print(emp[0],emp[1],emp[2],sep='\t')
c+=1
except:
fobj.close()
print('Number of Records=',c)
OR,
def searchbsal():
fobj=open('SALARY.DAT', 'rb')
c=0
try:
while True:
emp=pickle.load(fobj)
if emp[2]>150000.0:
print(emp[0],emp[1],emp[2],sep='\t')
c+=1
except:
fobj.close()
if c==0:
Example12: Function to edit all the records in a binary data file (containing list type of data) is given below:
import pickle
from os import remove, rename
def editallrecs():
frobj=open('SALARY.DAT', 'rb')
fwobj=open('TEMP.DAT', 'wb')
try:
while True:
emp=pickle.load(frobj)
emp[2]+=10000
pickle.dump(emp, fwobj)
Page 50 of 66
except:
frobj.close()
fwobj.close()
remove('SALARY.DAT')
rename('TEMP.DAT','SALARY.DAT')
Example13: Function to edit a particular record (by inputting employee code) in a binary data file (containing list
type of data) is given below:
import pickle
from os import remove, rename
def editcode():
frobj=open('SALARY.DAT', 'rb')
fwobj=open('TEMP.DAT', 'wb')
code=int(input('Code to Edit? '))
found=0
try:
while True:
emp=pickle.load(frobj)
if code==emp[0]:
emp[2]+=10000
found=1
pickle.dump(emp, fwobj)
except:
frobj.close()
fwobj.close()
remove('SALARY.DAT')
rename('TEMP.DAT','SALARY.DAT')
if found==1:
else:
print(code, 'No Records Found in the File')
Example14: Function to delete a record from a binary data file (containing list type of data) is given below:
import pickle
from os import remove, rename
def deletecode():
frobj=open('SALARY.DAT', 'rb')
fwobj=open('TEMP.DAT', 'wb')
code=int(input('Code to Edit? '))
found=0
try:
while True:
emp=pickle.load(frobj)
if code==emp[0]:
found=1
Page 51 of 66
else:
pickle.dump(emp, fwobj)
except:
frobj.close()
fwobj.close()
remove('SALARY.DAT')
rename('TEMP.DAT','SALARY.DAT')
if found==1:
print('Record Deleted From the File')
else:
print(code, 'No Records Found in the File')
seek() is used to set the file pointer at a particular position while tell() is used to get the current position of the file
pointer.
How many points the pointer will move is computed from adding offset to a reference point; the reference point is
given by the whence argument.
The allowed values for the whence argument are: –
A whence value of 0 means from the beginning of the file.
A whence value of 1 uses the current file position
A whence value of 2 uses the end of the file as the reference point.
The default value for the whence is the beginning of the file, which is 0
Note:
If your using seek() function in text files (those opened without a b in the access mode), only seeks relative to the
beginning of the file are allowed.
If you try to move the file handle from the current position you’ll get an io.UnsupportedOperation: can't do
nonzero cur-relative seeks error.
So open the file in binary mode if you want to move the file pointer ahead or behind from the current position
Use of seek()
Page 52 of 66
s2= goo
Example2 s3= d fa
f=open("abc.txt","rb") position= 28
f.seek(5)
s1=f.read(5).decode("utf-8")
f.seek(-3,1)
s2=f.read(3).decode("utf-8")
f.seek(-5,2)
s3=f.read(3).decode("utf-8")
print("s1=",s1)
print("s2=",s2)
print("s3=",s3)
f.close()
abc.txt
I am a good man and a bad father.
output
s1= a goo
s2= goo
s3= er.
Absolute path
This refers to the complete path to a text/binary/csv file that we specify when opening the file
example:
assuming the python interpreter location(default)
i.e. C:\Users\raj\AppData\Local\Programs\Python\Python39
f=open(“c:/mira/important/abc.txt”,”r”)
Relative Path
This refers to a file path relative to the current location in the folder directory. Now suppose I have moved my file
“abc.txt” from there to C:\Users\raj\AppData\Local\Programs\raj
(created a folder called raj and placed abc.txt inside it)
f=open("../../raj/abc.txt","rb")
CSV Files
CSV File: These files store data as text separated by comma. (comma separated values)
Page 53 of 66
Create a csv file using MsExcel named data1.csv in the current folder where you will save the python program
Page 54 of 66
Output
Create a csv file using MsExcel named data3.csv in the current folder where you will save the python program
Page 55 of 66
Output
Page 56 of 66
Creating/ writing a csv file from python
Method1 – using a list
Output
Data4.csv is created
Page 57 of 66
Method2 – using a dictionary
Output
Data5.csv is created
Page 58 of 66
Revision for MCQs
Strings - https://youtu.be/YYfiq8s7FWw
Tuples - https://www.youtube.com/watch?v=0DhFEr6-SlM
Lists - https://youtu.be/huowJ2bg898
3.Rewrite the following code in python after removing all syntax error(s). Underline each
correction done in the code.
def Tot(Number) #Method to find Total
Sum=0
for C in Range (1, Number+1):
Sum+=C
RETURN Sum
print(Tot[3]) #Function Calls
print(Tot[6])
5.What are the possible outcome(s) executed from the following code ? Also specify
the maximum and minimum values that can be assigned to variable NUMBER.
STRING=”CBSEONLINE”
NUMBER=random.randint(0,3)
N=9
while STRING[N]!=‘L’:
print(STRING[N]+STRING[NUMBER]+‘#’,)
NUMBER=NUMBER+1
N=N–1
(i) ES#NE#IO# (ii) LE#NO#ON# (iii) NS#IE#LO# (iv) EC#NB#IS#
6.What will be the output of the following python code ? Explain the try and except
used in the code. 2
U=0
V=6
print ‘First’
try:
print ‘Second’
M=V/U
print(‘Third’,M)
except ZeroDivisionError :
print( V*3)
print( ‘Fourth’)
except:
print(V*4)
print( ‘Fifth’)
7.What is operator overloading with methods ? Illustrate with the help of an example
using a python code.
8.Write a method in python to display the elements of list thrice if it is a number and
display the element terminated with ‘#’ if it is not a number.
For example, if the content of list is as follows :
L=[‘41’,‘DROND’,‘GIRIRAJ’, ‘13’,‘ZARA’]
The output should be
414141
DROND#
GIRIRAJ#
131313
ZARA#
9.What will be the status of the following list after fourth pass of bubble sort and
fourth pass of selection sort used for arranging the following elements in
descending order ?
14, 10, –12, 9, 15, 35
10.Write a method in python to search for a value in a given list (assuming that the
Page 60 of 66
elements in list are in ascending order) with the help of Binary Search method. The
method should return –1 if the value not present else it should return position of
the value present in the list.
11.Write PUSH (Books) and POP (Books) methods in python to add Books and
remove Books considering them to act as Push and Pop operations of Stack.
12.Write a method in python to find and display the prime numbers between 2 to N.
Pass N as argument to the method.
13.Evaluate the following postfix notation of expression. Show status of stack after
every operation.
84, 62, –, 14, 3, *, +
2016 1.Out of the following, find those identifiers, which cannot be used for naming Variable or
Functions in a Python program:
2.Name the Python Library modules which need to be imported to invoke the following functions
(i) load()
(ii) pow()
3.Rewrite the following code in python after removing all syntax error(s). Underline each
correction done in the code.
5.What are the possible outcome(s) executed from the following code ? Also specify
the maximum and minimum values that can be assigned to variable PICKER.
import random
PICK=random.randint(0,3)
CITY=[“DELHI”,”MUMBAI”,”CHENNAI”,”KOLKATA”];
for I in CITY:
for J in range(1,PICK):
print(I,end=””)
print()
Page 61 of 66
6.What will be the output of the following python code considering the following set
of inputs ?
JAYA
My 3 books
PICK2
2120
7.What will be the status of the following list after the First, Second and Third pass
of the insertion sort method used for arranging the following elements in
descending order ?
22, 24, –64, 34, 80, 43
Note : Show the status of all the elements after each pass very clearly underlining
the changes.
8.For a given list of values in descending order, write a method in python to search
for a value with the help of Binary Search method. The method should return
position of the value and should return -1 if the value not present in the list.
9.Write Insert(Place) and Delete(Place) methods in python to add Place and Remove
Place considering them to act as Insert and Delete operations of the data structure
Queue.
10.Write a method in python to find and display the prime numbers between 2 to N.
Pass N as argument to the method.
11.Evaluate the following postfix notation of expression. Show status of stack after
every operation.
22,11,/,14,10,–,+,5,–
2017 1.Which of the following can be used as valid variable identifier(s) in Python?
(i) total
(ii) 7Salute
(iii) Que$tion
(iv) global
Page 62 of 66
2.Name the Python Library modules which need to be imported to invoke the
following functions :
(i) ceil()
(ii) randint()
3.Rewrite the following code in Python after removing all syntax error(s). Underline
each correction done in the code.
TEXT=""GREAT
DAY""
for T in range[0,7]:
print(TEXT(T))
print(T+TEXT)
5.What are the possible outcome(s) executed from the following code ? Also specify
the maximum and minimum values that can be assigned to variable N.
import random
SIDES=["EAST","WEST","NORTH","SOUTH"];
N=random.randint(1,3)
OUT=""
for I in range(N,1,–1):
OUT=OUT+SIDES[I]
Print(OUT)
(i) SOUTHNORTH (ii) SOUTHNORTHWEST
(iii) SOUTH (iv) EASTWESTNORTH
7.What will be the status of the following list after the First, Second and Third pass
of the bubble sort method used for arranging the following elements in descending
order ?
Note : Show the status of all the elements after each pass very clearly underlining
the changes.
152, 104, –100, 604, 190, 204
10.Write definition of a Method AFIND(CITIES) to display all the city names from a
list of CITIES, which are starting with alphabet A.
For example :
If the list CITIES contains
["AHMEDABAD","CHENNAI","NEW DELHI","AMRITSAR","AGRA"]
The following should get displayed
AHMEDABAD
AMRITSAR
AGRA
2018 1.Differentiate between Syntax Error and Run-Time Error. Also, write a suitable example in Python
to illustrate both.
2.Name the Python Library modules which need to be imported to invoke the following functions
:
(i) sin()
(ii) search()
3.Rewrite the following code in Python after removing all syntax error(s). Underline each
correction done in the code.
Val = int(input("Value:"))
Adder = 0
for C in range(1,Val,3)
Adder+=C
If C%2=0:
Print( C*10)
Else:
print C*
print(Adder)
Page 64 of 66
5.What possible output(s) are expected to be displayed on screen at the time of execution of the
program from the following code? Also specify the maximum values that can be assigned to each
of the variables BEGIN and LAST.
import random
POINTS=[20,40,10,30,15];
POINTS=[30,50,20,40,45];
BEGIN=random.randint(1,3)
LAST=random.randint(2,4)
for C in range(BEGIN,LAST+1
print(POINTS[C],"#",)
7.Write the definition of a method ZeroEnding(SCORES) to add all those values in the list of
SCORES, which are ending with zero (0) and display the sum. 3
For example :
If the SCORES contain [200, 456, 300, 100, 234, 678]
The sum should be displayed as 600
8.Write AddClient(Client) and DeleteClient(Client) methods in Python to add a new Client and
delete a Client from a List of Client Names, considering them to act as insert and delete
operations of the queue data structure.
9.Write a definition of a method COUNTNOW(PLACES) to find and display those place names, in
which there are more than 5 characters.
For example :
If the list PLACES contains
["DELHI","LONDON","PARIS","NEW YORK","DUBAI"]
The following should get displayed :
LONDON
NEW YORK
We will try to read input from the user. Press ctrl-d and see what happens
>>> s = input('Enter something --> ')
def odd(seq):
for number in seq:
if number % 2:
yield number
print sum(odd(underFourMillion(fib())))
except SyntaxError:
print "\nPlease enter a number only."
continue
print a - b
try:
loop = input('Press 1 to try again > ')
except (NameError,SyntaxError):
loop = 0
Page 66 of 66