100% found this document useful (1 vote)
148 views

Notes Updated

The document discusses problem solving in Python programming. It describes 4 key steps: 1) Analyzing the problem to understand inputs and outputs, 2) Developing an algorithm using pseudocode or flowcharts, 3) Coding the algorithm, and 4) Testing and debugging the program. It also discusses algorithms, flowcharts, and pseudocode for representing solutions before coding. Problem decomposition is described as breaking complex problems into simpler subproblems.

Uploaded by

NITANT KALRA
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
148 views

Notes Updated

The document discusses problem solving in Python programming. It describes 4 key steps: 1) Analyzing the problem to understand inputs and outputs, 2) Developing an algorithm using pseudocode or flowcharts, 3) Coding the algorithm, and 4) Testing and debugging the program. It also discusses algorithms, flowcharts, and pseudocode for representing solutions before coding. Problem decomposition is described as breaking complex problems into simpler subproblems.

Uploaded by

NITANT KALRA
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 66

Notes in python 3.

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.

Algorithm, Flowchart and Pseudocode


Algorithm: A finite sequence of steps required to get the desired output for a particular problem is called an
algorithm. It will lead to the desired result in a finite amount of time, if followed correctly. Algorithm has a definite
beginning and a definite end, and consists of a finite number of steps.

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

• it clearly reveals the flow of control during execution of the program

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:

1. Flowchart — A flowchart is a visual representation of an algorithm. A flowchart is a diagram made up of boxes,


diamonds and other shapes, connected by arrows. Each shape represents a step of the solution process and the
arrow represents the order or link among the steps. There are standardized symbols to draw flowcharts

Page 1 of 66
Example:

Write an algorithm to find the square of a number.

Before developing the algorithm, let us first identify the input, process and output:

• Input: Number whose square is required

• Process: Multiply the number by itself to get its square

• Output: Square of the number Algorithm to find square of a number.

ALGORITHM

Step 1: Input a number and store it to num

Step 2: Compute num * num and store it in square

Step 3: Print square

FLOWCHART

2. Pseudocode - A pseudocode is another way of representing an algorithm. It is considered as a non-formal


language that helps programmers to write algorithm. It is a detailed description of instructions that a computer
must follow in a particular order. It is intended for human reading and cannot be executed directly by the
computer. No specific standard for writing a pseudocode exists. The word “pseudo” means “not real,” so
“pseudocode” means “not real code”.

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 −

1. It supports functional and structured programming methods as well as OOP.


2. It can be used as a scripting language or can be compiled to byte-code for building large applications.
3. It provides very high-level dynamic data types and supports dynamic type checking.

Execution modes - interactive mode and script mode

Interactive/ shell mode Script/program mode


1. execution takes place 1.debugging takes place
2. a single line of python code can be executed 2. multiple lines of python code can be executed at a
go
3. the code cannot be saved for later use 3. the code can be saved for later use
4. used for learning various use of methods and 4. used for program development
functions

To check the version in python in shell mode

>>> import sys

>>> sys.version

'3.9.0 (tags/v3.9.0:9cf6752, Oct 5 2020, 15:34:40) [MSC v.1927 64 bit (AMD64)]'

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.

To display the keywords

>>> import keyword

>>> 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.

Lvalue and Rvalue


Lvalue: it is an assignable variable/reference/object identifier. It appears in the left side of the expression.

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

x=5 x=y+z**2 x=y 5=x y+z**2=x


correct correct correct wrong wrong

Literals - A fixed or a constant value.


Examples: 34, 89.67, “mms”, None, True, False, ‘a’, 2+3j, [1,2,3], (3,4,5), {1:”mms”,2::dps”}
Page 4 of 66
Variable/ references/ objects - Technically in python it is called a reference that points to a memory that stores
a value.

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:

Python is an object oriented


and an interpreted language.

#Python is an object oriented ‘’’Python is an object oriented


#and an interpreted language. and an interpreted language.’’’

Operator – performs some action on data


1. Arithmetic: +(addition operator) , -(subtraction operator) , * (multiplication operator), / (division operator), %
(remainder operator), **(exponential operator) , // (floor division operator)
Sample code

>>> 5+2 >>> 5//2


7 2
>>> 5-2 >>> 5%2
3 1
>>> 5*2 >>> 5**2
10 25
>>> 5/2
2.5

2. Relational/comparison: < , > , <= , >= , = =, !=

This creates a condition which results either True or False. Generally used with if and while statements.

Sample code

>>> 5>2 >>> 5<=2


True False
>>> 5<2 >>> 5==2
False False
>>> 5>=2 >>> 5!=2
True True
Note: == actually checks the values.

3. Assignment: =
This directly assigns a value or indirectly assigns a value or a literal of another variable.
Sample code

>>> x=10 >>> x=(1,2,3)


>>> x=True >>> x=[2,3,4]
>>> x=7.8 >>> x={1:"abc",2:"cde"}
>>> x=3+8j
4. Augmented assignment operator: += , -= , *= , /=, %= , **= , //=
This actually combines 2 statements like:

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.

6. Identity operators: is , is not


Sample code

>>> 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

>>> x="abcdef" >>> d={1:"abc",2:"cde",3:"mnk"}


>>> "bc" in x >>> 2 in d
True True
>>> x=[1,2,3,4,5] >>> 5 in d
>>> 3 in x False
True

Important comparison ( == and is operators)

>>> x=10 >>> l1=[1,2,3]


>>> y=10 >>> l2=l1
>>> x >>> l1
10 [1, 2, 3]
>>> y >>> l2
20 [1, 2, 3]
>>> id(x) >>> id(l1)
2392597293648 2392638352640
>>> id(y) >>> id(l2)
2392597293648 2392638352640
>>> x is y >>> l1 is l2
True True
>>>x == y >>>l1 == l2
True True
>>> y=20 >>> l2[1]=100
>>> id(y) >>> l1
2392597293968 [1, 100, 3]
>>> x is y >>> l2
False [1, 100, 3]
>>>x == y >>> id(l1)
False 2392638352640
Page 6 of 66
>>> id(l2)
2392638352640
Since x and are y immutable, the id changes as soon as >>> l1 is l2
a new value is assigned. Now x refers to a memory True
with 10 while y refers to a memory with 20. >>>l1 == l2
True
Since list is mutable, the id remains same even if there
is a change in it.

Precedence of operators
The following table lists all operators from highest precedence to lowest.

Operator Description

** Exponentiation (raise to the power)

+- unary plus and minus

* / % // Multiply, divide, modulo and floor division

+- Addition and subtraction

<= < > >= Comparison operators

<> == != Equality operators

= %= /= //= -= += *= **= Assignment operators

is is not Identity operators

in not in Membership operators

not or and Logical operators

Punctuators or Delimiters or Separators


The following tokens serve as delimiters in the grammar:

( ) [ ] { }

, : . ` = ;

The following printing ASCII characters have special meaning as part of other tokens or are otherwise significant to
the lexical analyzer:

' " # \

ASCII and Unicode characters in python


ASCII (American Standard Code for Information Interchange) is a coding that encompasses the following:

 Lowercase English letters: a through z


 Uppercase English letters: A through Z
 Some punctuation and symbols: "$" and "!", to name a couple
 Whitespace characters: an actual space (" "), as well as a newline, carriage return, horizontal tab, vertical
tab, and a few others
 Some non-printable characters: characters such as backspace, "\b", that can’t be printed literally in the
way that the letter A can
Page 7 of 66
So what is a more formal definition of a character encoding?

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:

Code Point Range Class

0 through 31 Control/non-printable characters

32 through 64 Punctuation, symbols, numbers, and space

65 through 90 Uppercase English alphabet letters

91 through 96 Additional graphemes, such as [ and \

97 through 122 Lowercase English alphabet letters

123 through 126 Additional graphemes, such as { and |

127 Control/non-printable character (DEL)

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.

Code Point Character (Name) Code Point Character (Name)

0 NUL (Null) 64 @

1 SOH (Start of Heading) 65 A

2 STX (Start of Text) 66 B

3 ETX (End of Text) 67 C

4 EOT (End of Transmission) 68 D

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

16 DLE (Data Link Escape) 80 P

Page 8 of 66
Code Point Character (Name) Code Point Character (Name)

17 DC1 (Device Control 1) 81 Q

18 DC2 (Device Control 2) 82 R

19 DC3 (Device Control 3) 83 S

20 DC4 (Device Control 4) 84 T

21 NAK (Negative Acknowledgment) 85 U

22 SYN (Synchronous Idle) 86 V

23 ETB (End of Transmission Block) 87 W

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 ~

63 ? 127 DEL (delete)

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.

Decimal Range Hex Range What’s Included Examples


0 to 127 "\u0000" to "\u007F" U.S. ASCII "A", "\n", "7", "&"
128 to 2047 "\u0080" to "\u07FF" Most Latinic alphabets* "ę", "±", "ƌ", "ñ"
2048 to 65535 "\u0800" to "\uFFFF" Additional parts of the multilingual plane "ത", "ᄇ", "ᮈ", "‰"
(BMP)**
65536 to "\U00010000" to "\U0010FFFF" Other*** "𝕂", "ᮈ", "😓", "🂲",
1114111

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

>>> c=65 >>> c=579


>>> chr(c) >>> chr(c)
'A' 'Ƀ'
>>> c=6789 >>> c=2034
>>> chr(c) >>> chr(c)
'᪅' '߲'

Data types in python: In python type of reference or a variable is stated as a class


1. bool: It is a data structure of type boolean used to store either value True or False. By default it stores False. It is
immutable.
Example to create a boolean type reference
By assigning a value
X=True
By declaring
X=bool()

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

Assignment and statements

Correct and incorrect assignments

>>> x=5 #correct


>>> x=5;y=6 #correct
>>> x,y=6,7 #correct
>>> x=5,6 #TypeError: cannot unpack non-iterable int object
>>> x,y,z=6,7 #ValueError: not enough values to unpack (expected 3, got 2)
>>> x,y=5,6,7 #ValueError: too many values to unpack (expected 2)
>>> a,b,c="xyz" #correct
Page 12 of 66
>>> a,b="xyz" #ValueError: too many values to unpack (expected 2)
>>> a,b,c,d="xyz" #ValueError: not enough values to unpack (expected 4, got 3)
>>> x,y,z=10,x+20,y+30 #NameError: name 'x' is not defined

Expressions, it’s evaluation per precedence


1 Exponential valid for integers and decimal values
2**3 8
2**3**2 512
2 Multiplication
2*3 8
2.4*4.5
“mira”*3 or 3*”mira” “miramiramira”
3 Division
4 Floor division Gives the nearest smaller integer
>>> 25/3
8.333333333333334
>>> -25/3
-8.333333333333334
>>> -25/-3
8.333333333333334
>>> 25/-3
-8.333333333333334
>>> 25//3
8
>>> -25//3
-9
>>> 25//-3
-9
>>> -25//-3
8

5 Remainder or modulous x%y= x – (x//y) * y


>>> 25%3 remainder=numerator –
1 quotient*denominator
= 25 – (25//3) * 3
=25 – 8 * 3
=1
>>> -25%3
2
= -25 – (-25//3) * 3
= -25 – (-9) * 3
= -25 – (-27)
= -25 + 27
=2
>>> 25%-3
-2
= 25 – (25//-3) * -3
= 25 – (-9) * -3
= 25 – (27)
= 25 - 27
= -2

>>> -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

Note: only the marked functions are in syllabus and to be learnt.


>>> dir(__builtins__)
['abs', 'all', 'any', 'ascii', 'bin', 'bool', 'breakpoint', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'compile',
'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'exec', 'exit', 'filter', 'float',
'format', 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass', 'iter',
'len', 'license', 'list', 'locals', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print',
'property', 'quit', 'range', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super',
'tuple', 'type', 'vars', 'zip']

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

Optional parameters of print


end and sep are optional parameters of Python. The end parameter basically prints after all the output objects
present in one output statement have been returned. the sep parameter differentiates between the objects.
Code Output Remarks
>>>print(“hello”,”how”,”are”,”you”,sep=”@”) hello@how@are@you
>>>print(“hello”,”how”,”are”,”you”,end=”@”) hello how are you@
>>> print("hello",end="@");print("how") hello@how
>>>print("hello",”how”,”are”,”you”) hello how are you , gives a space by
default
>>>print("hello",”how”,”are”,”you”,sep=””) hellohowareyou Using sep=”” space
gerated by , is
suppressed

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.

The builtin functions applicable for a string:


len()- to calculate the length of a string that includes the new line character \n treated as a single
character.
type()- to display the datatype
id()- to display the identity or the memory address

Explanation for why strings are immutable


In python, strings are immutable, that means the characters in the string once declared cannot be
changed.
Example
>>>s=’India id Great’
>>>print(id(s))
>>>65652767
>>>s=’We love India’
>>>print(id(s))
>>>56652452
Different ids proves that the second string s is a new string and it is not the same as the 1st string. Same
name does not qualify that both have the same memory.

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'

>>> s="M m mira" >>> s=" mira "


>>> s.lstrip("M ") >>> s.rstrip()
'm mira' ' mira'
>>> s=" mira m" >>>
>>> s.rstrip("m") >>> s=" mira "
' mira ' >>> s.strip()
>>> s=" mira m" 'mira'
>>> s.rstrip(" m") >>> s="M mira M"
' mira' >>> s.strip("M ")
>>> s=" mira m" 'mira'
>>> s.rstrip("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

While slicing we have the privilege to specify 3 parameters


S [ <val1> : <val2> : <val3> ]
val1, val2 and val3 all are optional
val1 represents the index from where extraction starts. The default value is 0.
val2 represents the index till where extraction has to be done. Actually val2 is calculated as i.e. actually
val2-1. The default value is len(<string>)-1
val3 represents the step value and the sign gives the direction, positive means left to right while negative
means right to left. By default it is positive 1.
Note:
In case of a negative val3, reading from right to left val1 needs to be ahead of val2, here val2 is actually
val2-1
In case of a positive val3, reading from left to right val2 needs to be ahead of val1, here val2 is actually
val2+1
Examples
>>> S[:] >>> S[1:9:2]
'MIRA MODEL' 'IAMD'
>>> S[3:] >>> S[-8:-2:3]
'A MODEL' 'RM'
Page 19 of 66
>>> S[:7] >>> S[-2:-8:-1]
'MIRA MO' 'EDOM A'
>>> S[2:8] >>> S[::-1]
'RA MOD' 'LEDOM ARIM'
>>> S[3:1] >>> S[10:2:-1]
'' 'LEDOM A'
>>> S[-3:] >>> S[10:2:-2]
'DEL' 'LDMA'
>>> S[:-4]
'MIRA M'
>>> S[-1:-6]
''
>>> S[-7:-2]
'A MOD'

Now an interesting fact on default value.


The default values of first and second depends on the sign of the third value:
s="IndiaisGreat"
print(len(s)) #12
# print(s[: :]) is same, displays the string from left to right
# Here the first by default is 0, second by default is len(s)-1 and for explicit values it is (second-1),
# and the third by default is 1
print(s[ : ]) # IndiaisGreat
print(s[ : 4 : ]) # Indi
print(s[ :-3:]) # IndiaisGr
# as soon as the third is -1, the default for first becomes -1, the default of second becomes -(len(<string>)
# and if the second is a positive or negative explicit value, then it is actually second+1
print(s[ : : -1]) # taerGsiaidnI
print(s[ :4: -1]) # taerGsi
print(s[ :-4: -1]) # tae

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

Change Item Value


To change the value of a specific item, refer to the index number:
Example

Page 20 of 66
Change the second item:
L1[1] = "blackcurrant"
print(L1)

Check if Item Exists


To determine if a specified item is present in a list use the in keyword:

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])

Add Items in a list


To add an item to the end of the list, use the append() method:
Example
Using the append() method to append an item:
L = ["apple", "banana", "cherry"]
L.append("orange")
print(L)

To add an item at the specified index, use the insert() method:


Example
Insert an item as the second position:
L = ["apple", "banana", "cherry"]
L.insert(1, "orange")
print(L)

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)

Interpretation using a diagram


Shallow Copy (id remains same) Deep Copy (id changes)
L1=[10,20,30] L1=[10,20,30]
L2=L1 L2=L1.copy()

0 1 2 0 1 2
L1/L2 L1

10 20 30 10 20 30

0 1 2
L2

Join Two Lists


Page 22 of 66
There are several ways to join, or concatenate, two or more lists in Python.
One of the easiest ways are by using the + operator.
Example
Join two list:
list1 = ["a", "b" , "c"]
list2 = [1, 2, 3]
list3 = list1 + list2
print(list3)

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

Access Tuple Items


You can access tuple items by referring to the index number, inside square brackets: Example
Print the second item in the tuple:
T = ("apple", "banana", "cherry")
print(T[1])

Change Tuple Values


Once a tuple is created, you cannot change its values. Tuples are unchangeable, or immutable as it also is called.
But there is a workaround. You can convert the tuple into a list, change the list, and convert the list back into a
tuple.
Example
Convert the tuple into a list to be able to change it:
x = ("apple", "banana", "cherry")
y = list(x)
y[1] = "kiwi"
x = tuple(y)
print(x)

Traversing through a Tuple


You can loop through the tuple items by using a for loop.
Example
Iterate through the items and print the values:
T = ("apple", "banana", "cherry")

for x in T:

print(x)

Check if Item Exists


To determine if a specified item is present in a tuple use the in keyword: Example
Check if "apple" is present in the tuple:
T = ("apple", "banana", "cherry")
if "apple" in T:
print("Yes, 'apple' is in the fruits tuple")

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)

But there is a way around(but the id of the updated tuple is different)


Method1:
L=list(T)
L.append(“orange”)
T=tuple(L)
print(T)

Method2:
T+=(“orange”,)
print(T)

Create Tuple With One Item


To create a tuple with only one item, you have to add a comma after the item, otherwise Python will not recognize
it as a tuple.
Example
One item tuple, remember the comma:
T = ("apple",)

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

Join Two Tuples


To join two or more tuples you can use the + operator:
Example
Join two tuples:
tuple1 = ("a", "b" , "c")
tuple2 = (1, 2, 3)
tuple3 = tuple1 + tuple2
print(tuple3)
Nested Tuples
tuple1 = ("a", "b" , "c",(1,2,3),”d”)
print(tuple1[3]) # (1,2,3)
print(tuple1[3][1]) # 2

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

Traverse through a Dictionary


You can loop through a dictionary by using a for loop.
When looping through a dictionary, the return value are the keys of the dictionary, but there are methods to return
the values as well.
Example
Print all key names in the dictionary, one by one:
for x in D:
print(x)
Example

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)

Check if Key Exists


To determine if a specified key is present in a dictionary use the in keyword: Example
Check if "model" is present in the dictionary:
if "model" in D:
print("Yes, 'model' is one of the keys in the thisdict dictionary")

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

Built-in Modules in Python

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)

math module Functions


1. ceil(x) Returns the smallest integer greater than or equal to x.
2. fabs(x) Returns the absolute value of x
3. factorial(x) Returns the factorial of x
4. floor(x) Returns the largest integer less than or equal to x
5. fmod(x, y) Returns the remainder when x is divided by y
6. trunc(x) Returns the truncated integer value of x
7. exp(x) Returns e**x
8. log(x[, b]) Returns the logarithm of x to the base b (defaults to e)
9. log10(x) Returns the base-10 logarithm of x
10. pow(x, y) Returns x raised to the power y
11. sqrt(x) Returns the square root of x
12. acos(x) Returns the arc cosine of x
13. asin(x) Returns the arc sine of x
14. atan(x) Returns the arc tangent of x
15. cos(x) Returns the cosine of x
16. sin(x) Returns the sine of x
17. tan(x) Returns the tangent of x
18. degrees(x) Converts angle x from radians to degrees
19. radians(x) Converts angle x from degrees to radians
20. pi Mathematical constant, the ratio of circumference of a circle to it's diameter (3.14159...)
21. e mathematical constant e (2.71828...)

random module functions

1. randrange(start, stop[, step]) :Returns a random integer from the range


2. randint(a, b) :Returns a random integer between a and b inclusive
3. random() :Return the next random floating point number in the range [0.0, 1.0)
4. uniform(a, b) :Return a random floating point number between a and b inclusive

statistics module functions


1. mean() - Arithmetic mean (“average”) of data.
2. median() - Median (middle value) of data.
3. mode() - Single mode (most common value) of the data.
These three functions are generally used in a list or a tuple of numeric data

pickle module functions


1. load() – to read the data from a binary file into a python object
2. dump() – to write the data from the python object into a binary file

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

csv module functions


1. reader() – to read the data from the csv file into a python list

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

Static typing vs dynamic typing


Python is a dynamically typed language. This means that the Python interpreter does type checking only as code
runs, and the type of a variable is allowed to change over its lifetime. >>>x='mira'
>>> type(x)
<class 'str'>
>>> x = 28.1
>>> type(x)
<class 'float'>
The opposite of dynamic typing is static typing. Static type checks are performed without running the program. In
most statically typed languages, for instance C and Java, this is done as your program is compiled. The type of a
variable is not allowed to change over its lifetime.
int x;
x=67; x="mira" // error

implicit and explicit type conversion


In Implicit type conversion, Python automatically converts one data type to another data type. This process doesn't
need any user involvement.
x=45 type(x) is int
y=6.7 type(y) is float
z=x+y type(z) is float

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

Decision making and Iteration in Python

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.

Sr.No. Statement & Description

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.

Sr.No. Loop Type & Description


1 while loop
Repeats a statement or group of statements while a given condition is TRUE. It tests the condition
before executing the loop body.
Here, statement(s) may be a single statement or a block of statements with uniform indent. The
condition may be any expression, and true is any non-zero value. The loop iterates while the
condition is true.
When the condition becomes false, program control passes to the line immediately following the
loop.

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)

Sample output when x


is entered as 2,4,5
Total is 6,2

Sample output when x


is entered as
2,4,6,7,6,9
Thank you 6
Total is 34 6

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)

for i in range(1,5,2): for i in range(5,1,-1): for i in range(5,1,-2):


print(i) print(i) print(i)

for i in range(1,6): Sample output x= 2,4,7,9,12


x=int(input(“enter x”)) Thank you 5
if x%5==0: Total is 34 5
break
sum+=x x=
else: 2,4,7,5
print(“Thank you”,i) Total
print(“Total is ”,sum,i) is 13 3

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)

The Infinite Loop


A loop becomes infinite loop if a condition never becomes FALSE. You must be cautious when using while loops
because of the possibility that this condition never resolves to a FALSE value. This results in a loop that never
ends. Such a loop is called an infinite loop. Example:

while True:

print(“Hello”)

Using else Statement with Loops


Python supports having an else statement associated with a loop statement.

• 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.

Let us go through the loop control statements briefly


Page 35 of 66
Sr.No. Control Statement & Description

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.

The range function in detail


The value we put in the range function determines how many times we will loop. The way range works is it
produces a list of numbers from zero to the value minus one. For instance, range(5) produces five values: 0, 1, 2, 3,
and 4.

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:

Statement Values generated

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(i, end=' ')

print('Blast off!!')

Page 36 of 66
54321
Blast off!!!

The end=' ' just keeps everything on the same line.

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.

Pass by reference vs value


All parameters (arguments) in the Python language are passed by reference. It means if you change what a
parameter refers to within a function, the change also reflects back in the calling function.

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 −

def cal_comp_interest(principal, rate, time ):


amount=principal*(1+rate/100)**time
ci=amount-principal
print(ci)

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

Learn to code a function with a purpose in various alternate methods


Now let us understand the various ways a piece of code can be written using a function. Below is a piece of code
to calculate the simple interest:
p=int(input('Enter principal:'))
r=int(input('Enter rate:'))
t=int(input('Enter time:'))
si=p*r*t/100
print('Simple interest:',si)
Page 38 of 66
Now, there are various ways of creating functions for the same piece of code. abc(), abc1(), abc2(),
abc3()
A function neither having parameters nor returning

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()

A function having parameters but not returning

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)

A function not having parameters but returning

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())

A function having parameters and also returning

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))

Returning multiple values independently

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)

Returning multiple values in a tuple

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])

Taking a list as a parameter and returning a list and a value

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)

Taking a dictionary and a string as parameters and returning a value

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')

*args and **kwargs in Python

1.)*args (Non-Keyword Arguments)


2.)**kwargs (Keyword Arguments)

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

More variations on function with default parameters


def abc8(p=1000,r=5,t=2):
si=p*r*t/100
return si

print('Simple interest :',abc8(2000,3,5))


print('Simple interest :',abc8(2000,3))
print('Simple interest :',abc8(2000))
print('Simple interest :',abc8())
#not possible print('Simple interest :',abc8(,3,5))
#not possible print('Simple interest :',abc8(,,5))
#not possible print('Simple interest :',abc8(2000, ,5))
print('Simple interest :',abc8(r=3,t=5))
print('Simple interest :',abc8(t=5))
print('Simple interest :',abc8(p=2000,t=5))

Scope of a variable (global scope, local scope)


Local variable: a variable declared inside any function is call a local variable.

Global variable: a variable declared outside a function is called a global variable

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

There are 3 types of files in python


a. text files
b. binary files
c. csv files

File opening Modes


Sr.No. Modes & Description
1 r - Opens a file for reading only 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. It is the default
mode.
2 rb - Opens a file for reading only 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.

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”

Important functions for text file handling:


1. read() – reads all the characters in a single/multiline string from the current position of file pointer till the end in
the file.

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

6. writelines() - writes a list of lines

7. open() – to open a file

8. close() – to close a file

Example1 : using read() Example2 : using read(n)


def read_file1(file): def read_file2(file):
f=open(file,"r") f=open(file,"r")
s=f.read() n=int(input("Enter the number of characters to be
print(s) displayed "))
l=s.split() s=f.read(n)
u,lw,a,b,=0,0,0,0 print(s)
for i in l:
if i.isupper():
u+=1
if i.islower():
lw+=1
if i[0].isupper():
a+=1
if i[-1].isupper():
b+=1

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)

Example3 : using readline() Example4 : using try and except


def read_file3(file): def read_file4(file):
f=open(file,"r") f=open(file,"r")
s=f.readline() # reads the 1st line while True:
Page 44 of 66
print(s) # displays the line with \n try:
s=f.readline() # reads the next line s=f.readline()
print(s) # # displays the line with \n... i.e a line gap if s[0] in "AEIOUaeiou":
is seen between print(s,end="") # end="" is used to
f.close() remove the gap inbetween
except:
break

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()

Example7 : using write()

def write_file1(file): # charcater by character


f=open(file,"w")
n=int(input("Enter number of characters : "))
for i in range(n):
c=input("Enter a character: ")
f.write(c)
f.close()
def write_file2(file): # word by word
f=open(file,"w")
n=int(input("Enter number of characters : "))
for i in range(n):
c=input("Enter a word: ")
f.write(c+" ")
f.close()

def write_file3(file): # line by line


f=open(file,"w")
n=int(input("Enter number of characters : "))
for i in range(n):
c=input("Enter a line: ")
f.write(c+'\n')
f.close()
Example8 - to append in the file

def write_file4(file): # line by line


f=open(file,"a")
n=int(input("Enter number of characters : "))
for i in range(n):
c=input("Enter a line: ")
f.write(c+'\n')

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")

Example10 - to change all the "and" to "or" in the file


import os
def modify_file2():
f=open("mira.txt","r")
f1=open("temp.txt","w")
s=f.read()
s1=s.replace("and","or")
f1.write(s1)
f.close()
f1.close()
os.remove("mira.txt")
os.rename("temp.txt","mira.txt")

Example11 - to remove all the duplicate characters from the file

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.

Important functions for binary file handling:


• fobj=open('MYDATA.DAT','wb')

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:

print(code, 'not found in the file')

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:

print(name, 'not found in the file')

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:

print('No Records Found in the File')

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:

print('Record Updated in the File')

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() and tell() functions

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.

Syntax: f.seek(offset, whence)

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()

Text file Example3


Example1: f=open("abc.txt","rb")
f=open("abc.txt","r") f.seek(5,0)
f.seek(5) s1=f.read(5).decode("utf-8")
s1=f.read(5) f.seek(-3,1)
s2=f.read(3) s2=f.read(3).decode("utf-8")
f.seek(3) f.seek(-11,2)
s3=f.read() s3=f.read(4).decode("utf-8")
print("s1=",s1) x=f.tell()
print("s2=",s2) print("s1=",s1)
print("s3=",s3) print("s2=",s2)
f.close() print("s3=",s3)
print("position=",x)
abc.txt f.close()
I am a good man and a bad father.
output abc.txt
s1= a goo I am a good man and a bad father.
s2= d m output
s3= m a good man and a bad father.
s1= a goo

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.

Relative and absolute path

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)

Then my relative path will be

f=open("../../raj/abc.txt","rb")

(.. represents parent directory)

CSV Files

Reading/ writing csv files from python

CSV File: These files store data as text separated by comma. (comma separated values)

Reading a csv file

Method1 – reading each row as a string

Page 53 of 66
Create a csv file using MsExcel named data1.csv in the current folder where you will save the python program

Method 2: reading each row as a list


Create a csv file using MsExcel named data2.csv in the current folder where you will save the python program

Page 54 of 66
Output

Method3 – reading each row as a dictionary

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

Csv files - https://youtu.be/XtDQnkHIs6s

Text files - https://youtu.be/_GPF3nP9R-g

User defined functions - https://www.youtube.com/watch?v=TyaFmJwTU7Y

Strings - https://youtu.be/YYfiq8s7FWw

Tuples - https://www.youtube.com/watch?v=0DhFEr6-SlM

Lists - https://youtu.be/huowJ2bg898

Random module - https://youtu.be/ANwA34BeKqo

If – else –if - https://youtu.be/PpPnGpJWqEU

Expressions and conditions - https://www.youtube.com/watch?v=40NWgv4vWcs

Variables and Basics - https://www.youtube.com/watch?v=avd_EZ9Hk38

Datatypes and operators - https://youtu.be/FvtPi0F-04s

Python revision from previous papers


2015 1.How is _init( ) _different from _del ( ) __ ?

2.Name the function/method required to


(i) check if a string contains only uppercase letters
(ii) gives the total length of the list.

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])

4.Find and write the output of the following python code :


Page 59 of 66
for Name in [‘Jayes’, ‘Ramya’, ‘Taruna’, ‘Suraj’]:
print(Name)
if Name[0]== ‘T’:
break
else :
print ‘Finished!’
print(‘Got it!’)

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:

Price*Qty, class, For, do,


4thCol, totally, Row31, _Amount

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.

for Name in [Amar,Shveta,Parag]


IF Name[0]=’S’:
print(Name)

4.Find and write the output of the following python code :


Numbers = [9,18,27,36]
for Num in Numbers:
for N in range(1, Num%8):
print(N,”#”,end=””)
print()

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

Also, explain the try and except used in the code.


Counter=0
while True:
try :
Number=int(input(“Give a Number”))
break
except ValueError:
Counter=Counter+2
print(“Re-enter Number”)
print(Counter)

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)

4.Find and write the output of the following Python code :


STR = ["90","10","30","40"]
COUNT = 3
SUM = 0
for I in [1,2,5,4]:
S = STR[COUNT]
SUM = float (S)+I
print(SUM)
COUNT–=1

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

6.Write two methods in Python using concept of Function Overloading


(Polymorphism) to perform the following operations :
(i) A function having one argument as side, to calculate Area of Square as
side*side
(ii) A function having two arguments as Length and Breadth, to calculate Area of
Rectangle as Length*Breadth.

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

8.Write definition of a method OddSum(NUMBERS) to add those values in the list


Page 63 of 66
of NUMBERS, which are odd.

9.Write Addnew(Book) and Remove(Book) methods in Python to Add a new Book


and Remove a Book from a List of Books, considering them to act as PUSH and
POP operations of the data structure Stack.

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

11.Evaluate the following Postfix notation of expression :


2,3,*,24,2,6,+,/,–

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)

4.Find and write the output of the following Python code :


Data = ["P",20,"R",10,"S",30]
Times = 0
Alpha = ""
Add = 0
for C in range(1,6,2):
Times = Times + C
Alpha = Alpha + Data[C-1]+"$"
Add = Add + Data[C]
Print( Times,Add,Alpha)

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],"#",)

6.Consider the following randomly ordered numbers stored in a list :


786, 234, 526, 132, 345, 467
Show the content of the list after the First, Second and Third pass of the bubble sort method used
for arranging in ascending order ?
Note : Show the status of all the elements after each pass very
clearly underlining the changes.

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

10.valuate the following Postfix notation of expression :


91 18

2019 1.What all can be possible output's of the following code


def myfunc(x=None):
result = ""
if x is None:
result = "No argument given"
elif x == 0:
result = "Zero"
Page 65 of 66
elif 0 < x <= 3:
result = "x is between 0 and 3"
else:
result = "x is more than 3"
return result

We will try to read input from the user. Press ctrl-d and see what happens
>>> s = input('Enter something --> ')

2.What will happen when following functions are executed?


def fib():
x,y = 1,1
while True:
yield x
x,y = y, x+y

def odd(seq):
for number in seq:
if number % 2:
yield number

def under Four Million(seq):


for number in seq:
if number > 4000000:
break
yield number

print sum(odd(underFourMillion(fib())))

3.Find out the situation(s) in which following code may crash


while loop == 1:
try:
a = input('Enter a number to subtract from > ')
b = input ('Enter the number to subtract > ')
except NameError:
print "\nYou cannot subtract a letter"
continue

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

4.Describe, what is the following module doing:


def test(start = 0):
c = start
while True:
value = yield c
if value != None:
c = value
else:
c += 1

Page 66 of 66

You might also like