Learn Python 3#
+ +Learn Python 3#
by Ankit Mahato
Version 2022.10
How to read this book?#
@@ -754,7 +761,9 @@- A nice web interface - Link -
- A Downloadable PDF - Link +
- A Downloadable PDF - Link
- Directly on GitHub - Link
This led to the invention of high-level programming languages in which programs can be easily written and managed. The human-readable programs written using high-level languages are converted into computer-readable machine code or bytecode using compilers or - interpreters.
+ interpreters. +There are many high-level programming languages that are currently in wide use.
Some of the popular languages are Java, C, C++, C#, Go, Swift, JavaScript, PHP, Dart, Kotlin and Python.
@@ -1145,7 +1155,8 @@Hit 🛡️ Install Now
and complete the setup.
Step 3: Verify Installation
Once the setup is complete, click on the Start
menu and open
- Python 3.9 -> IDLE (Python 3.9 64 bit)
to launch the Python interpreter.
Python 3.9 -> IDLE (Python 3.9 64 bit)
to launch the Python interpreter.
+
Python 3.9 is now successfully installed on your computer.
@@ -1183,10 +1194,11 @@Let us execute some basic Python statements and interact with the Python shell.
Launching the Python Shell
To launch the IDLE application click
- [Windows Start Menu Button] -> [Python 3.9 Folder] -> [IDLE (Python 3.9 64 bit)]
.
[Windows Start Menu Button] -> [Python 3.9 Folder] -> [IDLE (Python 3.9 64 bit)]
.
+
+
The Python interpreter or the Python shell will pop-up on the screen.
- +The version (3.9
) of the Python interpreter is displayed at the top of the window followed
by the >>>
symbol which indicates that the interpreter is ready to take instructions.
Python commands or statements can be input on this prompt. The input statements are executed @@ -1220,7 +1232,8 @@
Basic String Operation
Interactive mode is not just restricted to basic arithmetic or assignments. Let us join two strings -
- "Hello, "
and "world!"
.
"Hello, "
and "world!"
.
+
>>> "Hello, " + "world!"
'Hello, world!'
@@ -1366,7 +1379,8 @@ a
or underscores (_
).
!
, @
, #
, $
,
- %
, etc.%
, etc.
+
Some points to keep in mind while naming identifiers:
-
@@ -1374,14 +1388,16 @@ a
different identifier. e.g.,
- Identifiers differing by only underscores are different. e.g.,
unitlength
and -unit_length
are different identifiers.
+
length
and Length
are different identifiers.
unit_length
are different identifiers.
+
It is also a good practice (although not compulsory) to follow the following procedure while naming identifiers:
- Identifiers should be named carefully with an emphasis on clarity and readability. For example, in a
program that calculates the area of a rectangle, a good choice for identifier names are -
-
length
,breadth
andarea
.
+ - Class names should start with uppercase character.
- Identifiers starting with an underscore have special meaning in a program.
- Variable, function and method names should be in lowercase characters, with underscores separating
@@ -1410,7 +1426,8 @@ a
0
+092
is not a valid decimal integer literal as a zero precedes the first non-zero digit -9
.9
. +ii. Binary or base-2 Integer
A binary integer or base-2 integer begins with
@@ -1423,7 +1440,8 @@ a0b
or0B
followed by binary digits0-1
.A hexadecimal integer or base-16 integer begins with
0x
or0X
followed by digits0-9
or lettersA-F
(case insensitive).For example,
+27
can be written as a hexadecimal integer literal0x1B
or -0x1b
.0x1b
. +Thus, it can be observed that number
@@ -1433,7 +1451,8 @@ a27
can be written in the program as27
(decimal),0b11011
(binary),0o33
(octal) or0x1B
(hexadecimal).One underscore can occur between digits, and after base specifiers like
0o
.They are ignored while determining the actual numerical value of the literal.
Some valid underscore usages are -
+10_00_00_000
,0b_1110_0101
, -0x23_123
.0x23_123
. +Floating Point Literals#
Floating point literals are real numbers present in the source code. They contain fractional component @@ -1452,7 +1471,8 @@ a optional sign (
+
or-
) and digits (0-9
). This exponent is equivalent to multiplying the real number with the power of10
.For example,
+3.4E2
is equivalent to3.4 x 10^2
or340.0
, whereas -3.4e-2
is equivalent to3.4 x 10^-2
or.034
.3.4e-2
is equivalent to3.4 x 10^-2
or.034
. +Imaginary Literals#
To specify complex numbers and perform complex number mathematics, Python supports imaginary literals @@ -1475,7 +1495,8 @@ a literal (
1
) and a imaginary literal (2j
). - numeric literals do not include the minus sign (
-
).-
is actually a unary operator it combines with a numeric literal to represent negative numbers. For example, in --3.14
the numeric literal is3.14
and-
is an operator.
+
length
, breadth
and area
.
+
-3.14
the numeric literal is 3.14
and -
is an operator.
+
Boolean Literals#
@@ -1573,7 +1594,8 @@ E = mc² >>>In the above example, the Python shell does not display any value of a
as it is assigned as
- None
which has no value.
None
which has no value.
+
Collection of Literals#
Python has the provision for specifying a collection of literals in the source code using a special @@ -1671,7 +1693,8 @@ sum_6 = (1 + 2 href="#blocks-and-indentation">#
In traditional programming languages like C++ or Java, programs are organised in form of code blocks.
Each code block contains one or more statements which are enclosed between braces - {
and
- }
and are executed sequentially.
}
and are executed sequentially.
+
A sample C++/Java code is provided below which checks for an input x
.
C++
if (x < 10) {
@@ -1708,7 +1731,8 @@ sum_6 = (1 + 2
Code blocks in Python are inspired by this idea as it makes it easier to understand a Python code.
A block of code is denoted by line indentation, typically 4 spaces (preferred) or a
tab. This indentation is used to determine the logical group of statements, with all
- statements within a group having the same level of indentation.
+ statements within a group having the same level of indentation.
+
The corresponding Python code for the above C++/java examples is provided below.
Notice how the code blocks are indented according to the logic.
if x < 10:
@@ -1798,7 +1822,8 @@ here
int a = 1;
This a
is synonymous to a box of fixed dimensions (fixed type) holding something (value
- 1
) inside it.
+ 1
) inside it.
+
In case we want to change the contents of the box, we can replace it with something similar (same type).
@@ -1851,7 +1876,8 @@ int z = 3;
or underscores (_
).
Should not be a keyword.
No special symbols are allowed like !
, @
, #
, $
,
- %
, etc.
+ %
, etc.
+
Assignment#
Variables can be bound to a reference of an object (of any type) using assignment statements.
@@ -1913,7 +1939,8 @@ NameError: name 'a'
The following built-in data types are available in Python:
- Numeric Types -
int
, float
, complex
,
- bool
+ bool
+
- Sequence Types -
list
, tuple
, str
- Set Type -
set
- Mapping Type -
dict
@@ -1923,13 +1950,15 @@ NameError: name 'a'
are a collection of items on which a user can traverse (iterate).
Numeric Types - int
, float
,
complex
, bool
#
+ href="#numeric-types---int-float-complex-bool">#
+
Numeric data types are used for storing the following types of numbers:
Integer Numbers
Objects holding integer numbers like -1, 0, 200
are of int
data type.
Real or Floating-point Numbers
Objects holding real or floating point numbers like -1.1, 3e2, 20.0
are of
- float
data type.
+ float
data type.
+
Complex Numbers
Objects storing complex numbers like 2 + 1j, -3j, -1 + 2J
are of type complex
.
@@ -1938,10 +1967,12 @@ NameError: name 'a'
Boolean
The boolean data type (bool
) is a subtype of int
. It stores the evaluated value
of expressions represented as keywords - True
(integer value 1
) and
- False
(integer value 0
).
+ False
(integer value 0
).
+
Sequence Types - str
, list
,
tuple
#
+ href="#sequence-types---str-list-tuple">#
+
An ordered collection of items where each item can be accessed using an integer index is known as a
sequence. The following three sequence data types are available in Python:
String
@@ -1952,18 +1983,21 @@ NameError: name 'a'
A list
is sequence of items of same or different data types which are enclosed within
brackets - [ ]
.
Some example lists are - [1, 2, 3]
, ['abc', 23, 3.14]
,
- ['edpunk', 'python']
.
+ ['edpunk', 'python']
.
+
Tuple
A tuple
is an immutable sequence of items of same or different data types which are enclosed
within parentheses - ( )
.
Some example tuples are - (1, 2, 3)
, ('abc', 23, 3.14)
,
- ('edpunk', 'python')
.
+ ('edpunk', 'python')
.
+
Set Type - set
#
A set
is an unordered collection of unique items of same of different data types which are
enclosed in curly braces - { }
.
Some example sets are - {1, 2, 3}
, {'abc', 23, 3.14}
,
- {'edpunk', 'python'}
.
+ {'edpunk', 'python'}
.
+
Mapping Type - dict
#
dict
is a mapping data type which stores values in the form of key-value pairs.
@@ -1972,14 +2006,17 @@ NameError: name 'a'
dictionary where you can lookup the meaning of a given word.
Keys and corresponding values are separated by colon (:
).
The key-value pairs are separated by comma (,
) and enclosed within curly braces -
- { }
.
+ { }
.
+
Some example dictionaries are - {1: "a", 2: "b", 3: "c"}
,
- {"name": "edpunk", "language": "python"}
.
+ {"name": "edpunk", "language": "python"}
.
+
Special Type - None
#
None
is a special data type which is used to denote the absence of value in an object.
It is neither 0
nor False
as these are defined finite values, whereas
- None
implies nothingness.
+ None
implies nothingness.
+
Type Checking#
The built-in type()
function can be used to fetch the data type of an object.
@@ -2086,7 +2123,8 @@ nan
4. tuple()
Creates a tuple
from an iterable of type str
, list
,
- set
or range
.
+ set
or range
.
+
>>> tuple('hello')
('h', 'e', 'l', 'l', 'o')
>>> tuple([1, 2, 3, 4])
@@ -2096,7 +2134,8 @@ nan
5. list()
Creates a list
from an iterable of type str
, tuple
,
- set
or range
.
+ set
or range
.
+
>>> list('hello')
['h', 'e', 'l', 'l', 'o']
>>> list({1, 2, 3, 4})
@@ -2106,7 +2145,8 @@ nan
6. set()
Creates a set
from an iterable of type str
, tuple
,
- list
or range
.
+ list
or range
.
+
>>> set('hello')
{'o', 'e', 'l', 'h'}
>>> set([1, 2, 3, 4])
@@ -2213,7 +2253,8 @@ TypeError: 'tuple'
In the above examples, the id
of the objects (list
, dict
,
set
) do not change, which implies that no new objects are created and the original objects
- are modified.
+ are modified.
+
Input / Output#
How to Accept User Input'EdPunk'
User input can be converted into integer or floating point numbers using the type conversion functions
- int()
and float()
.
int()
and float()
.
+
>>> num = int(input("Enter n: "))
Enter n: 10
>>> type(num)
@@ -2314,7 +2356,8 @@ Hello, world!
All non-keyword arguments or expressions are converted to strings and written to the output stream by the
print()
function. They are separated by sep
and followed by end
.
An empty print()
invocation writes end
parameter (an empty line as
- end
defaults to the newline character '\n'
).
+ end
defaults to the newline character '\n'
).
+
Operators & Expressions#
Introduction to Operators-
(minus): The unary -
operator changes the sign of the operand.
~
(bitwise NOT
): The unary ~
results in the bit-wise
inversion of the integer operand. The bit-wise inversion of x
is defined as
- -(x+1)
.
+ -(x+1)
.
+
>>> x = 5
>>> -x
@@ -2352,16 +2396,20 @@ Hello, world!
A rich set of operators are available in Python which can be categorized as follows:
- Arithmetic Operators -
+
, –
, *
, /
,
- %
, **
, //
+ %
, **
, //
+
- Relational Operators -
==
, !=
, >
, >=
,
- <
, <=
+ <
, <=
+
- Assignment Operators -
+=
, -=
, *=
, /=
,
- %=
, **=
, //=
+ %=
, **=
, //=
+
- Logical Operators -
not
, or
, and
- Identity Operators -
is
, is not
- Membership Operators -
in
, not in
- Bitwise and Shift Operators -
&
, |
, ^
, ~
,
- <<
, >>
+ <<
, >>
+
Arithmetic Operators#
@@ -2374,7 +2422,8 @@ Hello, world!
5.0
In case the operands are of type str
, list
or tuple
, the
- +
operator concatenates these two sequences or strings.
+ +
operator concatenates these two sequences or strings.
+
>>> 'edpunk' + 'python'
'edpunkpython'
>>> ["ed", "punk"] + ["python", ]
@@ -2484,18 +2533,21 @@ Hello, world!
The code point of "p"
(112
) is greater than the code point of "P"
(80
). As 112
is greater than 80
the expression evaluates to
- True
.
+ True
.
+
Let us take another example:
>>> "pYthon" > "python"
False
The code point of first character is same (112
), so the next set of characters are compared.
The code point of "Y"
(89
) is not greater than the code point of
- "y"
(121
) so the expression evaluates to False
.
+ "y"
(121
) so the expression evaluates to False
.
+
If two string operands p
and q
are of unequal lengths
(len(p) < len(q)
) and p
is a substring of q
such that
q = pt
where t is any string of length greater than 0
, then q > p
- returns True
.
+ returns True
.
+
>>> "python" > "py"
True
@@ -2675,7 +2727,8 @@ Hello, world!
href="#logical-state-of-operands">#
In Python, all values except 0
, None
, False
, ""
,
''
, ()
, []
, {}
have their logical state as
- True
.
+ True
.
+
bool()
built-in function can be used to determine the logical state of literals, variables
or expressions.
The logical state of the following literals is False
.
@@ -2823,7 +2876,8 @@ Hello, world!
If a
, b
, c
, …, y
, z
are expressions and
op1
, op2
, …, opN
are comparison operators, then the chained
expression a op1 b op2 c ... y opN z
is equivalent to
- a op1 b and b op2 c and ... y opN z
.
+ a op1 b and b op2 c and ... y opN z
.
+
Conditional Expression#
Python does not have ternary operators (?:
) like other programming languages. Hence, the
@@ -2833,7 +2887,8 @@ Hello, world!
var = t_val if cond else f_val
If the above condition cond
evaluates to True
, then the variable
- var
is assigned t_val
, else it is assigned f_val
.
+ var
is assigned t_val
, else it is assigned f_val
.
+
>>> value = 1 if 2 > 3 else -1
>>> value
-1
@@ -2843,7 +2898,8 @@ Hello, world!
While studying mathematics in middle school, we came across the BODMAS (Bracket, Of,
Division, Multiplication, Addition, and Subtraction) rule which helps us in understanding how
mathematical expressions are computed in the presence of multiple operators (of
,
- x
, /
, +
, -
).
+ x
, /
, +
, -
).
+
In Python, we have a large number of operators and a similar rule to determine the order of evaluation of
an expression. This is known as operator precedence where the operator with higher
precedence is evaluated before the operator with lower precedence in an expression.
@@ -2896,7 +2952,8 @@ Hello, world!
in
, not in
, is
, is not
,
<
, <=
, >
, >=
, !=
,
- ==
+ ==
+
Membership, Identity & Comparisons
@@ -2923,7 +2980,8 @@ Hello, world!
15 - 2 * 4
Solution
Step: *
has higher precedence over -
15 - 2 * 4
=
- 15 - 8
= 7
+ 15 - 8
= 7
+
Example 2
Evaluate the expression
15 - 2 + 4
@@ -2941,7 +2999,8 @@ Hello, world!
3 * 2 + 9 / 4 - 10 % 2 ** 2
Step 1
**
takes precedence
3 * 2 + 9 / 4 - 10 % 2 ** 2
=
- 3 * 2 + 9 / 4 - 10 % 4
+ 3 * 2 + 9 / 4 - 10 % 4
+
Step 2
*
, /
and %
have the same precedence so they are evaluated left to
right.
3 * 2 + 9 / 4 - 10 % 4
= 6 + 2.25 - 2
@@ -2953,7 +3012,8 @@ Hello, world!
Step 1
*
, /
, //
and %
have the same precedence so they are
evaluated left to right.
20 / 4 // 2 * 2 - 4 + 20
=
- 5 // 2 * 2 - 4 + 20
= 2 * 2 - 4 + 20
= 4 - 4 + 20
+ 5 // 2 * 2 - 4 + 20
= 2 * 2 - 4 + 20
= 4 - 4 + 20
+
Step 2
+
and -
evaluation
4 - 4 + 20
= 20
Example 6
@@ -2961,13 +3021,16 @@ Hello, world!
not 6 <= 4 and 3 ** 3 > 12 / 3
Step 1
**
takes precedence
not 6 <= 4 and 3 ** 3 > 12 / 3
=
- not 6 <= 4 and 27 > 12 / 3
+ not 6 <= 4 and 27 > 12 / 3
+
Step 2
/
is next in line of precedence
not 6 <= 4 and 27 > 12 / 3
=
- not 6 <= 4 and 27 > 4
+ not 6 <= 4 and 27 > 4
+
Step 3
Comparison operators are next in line of precedence
not 6 <= 4 and 27 > 4
=
- not False and True
+ not False and True
+
Step 4
Boolean NOT
is evaluated
not False and True
= True and True
@@ -3023,7 +3086,8 @@ SyntaxError: invalid syntax
In the above example there is a syntax error with ^
pointing to print
function
which the parser is unable to understand as there is a missing :
(colon) after
- True
.
+ True
.
+
Runtime Error#
A runtime error occurs when the program is terminated prematurely by the Python interpreter as it is
@@ -3125,7 +3189,8 @@ avg = (n + m) / 2
Some of the built-in exceptions that are raised by the Python interpreter are - ImportError
,
ZeroDivisionError
, NameError
, ValueError
,
IndexError
, KeyError
, TypeError
and
- IndentationError
.
+ IndentationError
.
+
Apart from the Python interpreter, a programmer can also trigger and raise an exception (along with a
custom message) in the code using raise
or assert
statement.
raise#
@@ -3148,7 +3213,8 @@ Traceback (most recent call last):
ZeroDivisionError: division by zero
It can be observed that the Python interpreter raises a ZeroDivisionError
when the value of
- b
is entered as 0
.
+ b
is entered as 0
.
+
Now we can modify the above code to raise an exception for such scenarios.
Code
a = int(input("Enter a: "))
@@ -3249,10 +3315,12 @@ AssertionError: a is not equal to b
try
block: The block of statements within which an exception might be thrown.
except
clause(s): One or more exception handlers. Each except
clause
handles a particular type of exception. In case an exception of a particular type occurs in the
- try
block, the corresponding except
clause code block is executed.
+ try
block, the corresponding except
clause code block is executed.
+
else
clause: An optional else
clause can also be included after the last
except
block. In case no exception is raised, none of the except
blocks
- are executed. In this case, the else
code block is executed.
+ are executed. In this case, the else
code block is executed.
+
finally
clause: An optional finally
clause can be added at the end of the
try statement which includes a block of statements that are executed regardless of whether or not
any error occured inside the try block. This block is usually setup for code cleanup and closing all
@@ -3416,7 +3484,8 @@ Enter 2nd number: 3
Python provides for
and while
statements to perform iteration.
The for
statement can be used to iterate over the items of a sequence (list
,
string
, tuple
, range
). It can also be used to iterate over
- unordered sequences like set
and dict
.
+ unordered sequences like set
and dict
.
+
This process can be demonstrated using the below flowchart:
Let us go through some code examples to demonstrate how for
statement can be used to iterate
@@ -3475,7 +3544,8 @@ n
The range
type represents an immutable sequence of numbers that is usually used in for loops
for looping a certain number of times. range
object always take the same (small) amount of
memory, no matter the size of the range it represents, which is an advantage over a regular
- list
or tuple
.
+ list
or tuple
.
+
Syntax: range(stop)
or
range(start, stop[, step])
>>> range(10)
range(0, 10)
@@ -3567,7 +3637,8 @@ Total interest payable: 78812.5
The factorial of a positive integer n
, denoted by n!
, is the product of all
positive integers less than or equal to
n
.
n! = nĂ—(n-1)Ă—(n-2)...3Ă—2Ă—1
Write a program to calculate
- n!
for a given n
(assume n
is greater than 0
).
+ n!
for a given n
(assume n
is greater than 0
).
+
Code
n = int(input("Enter n: "))
@@ -3609,7 +3680,8 @@ i = 0
5 Volkswagen
In the above example, the test condition is i<len(cars)
and the update statement is
- i+=1
.
+ i+=1
.
+
Exercises#
Let us go through some programming problems which utilize the while
iteration statement.
@@ -3638,7 +3710,8 @@ Total interest payable: 78812.5
The factorial of a positive integer n
, denoted by n!
, is the product of all
positive integers less than or equal to
n
.
n! = nĂ—(n-1)Ă—(n-2)...3Ă—2Ă—1
Write a program to calculate
- n!
for a given n
(assume n
is greater than 0
).
+ n!
for a given n
(assume n
is greater than 0
).
+
Code
n = int(input("Enter n: "))
@@ -3716,7 +3789,8 @@ SyntaxError: unexpected EOF while parsing
break#
The break
statement is used to terminate the execution of immediately enclosing
- for
or while
statement.
+ for
or while
statement.
+
The below code will terminate the for
loop when i
is equal to 4
for i in range(10):
@@ -3739,7 +3813,8 @@ SyntaxError: unexpected EOF while parsing
i+=1
break
will terminate the while
loop when i
is equal to
- 4
+ 4
+
0
1
2
@@ -3915,7 +3990,8 @@ E = mc²
Other Types to String#
In case you want to create a string object from other data types, just use the built-in
- str()
function as follows:
+ str()
function as follows:
+
>>> str(9)
'9'
@@ -3978,14 +4054,16 @@ E = mc²
Python also provides a way to access a substring from a string. This substring is known as a
slice and it can be obtained using the slice operator [n:m]
which returns
the part of the string from the start index (n
) to the end index (m
),
- including the first but excluding the last.
+ including the first but excluding the last.
+
>>> s = "Hello"
>>> s[1:3]
'el'
If the start index (n
) is omitted, the default value of n
is set as
0
which denotes the beginning of the string. If the end index (m
) is omitted,
- the substring ends at the last character of the string.
+ the substring ends at the last character of the string.
+
>>> s = "Hello"
>>> s[:3]
'Hel'
@@ -4001,7 +4079,8 @@ E = mc²
In the above example, -4
is equivalent to len(s) - 4 = 5 - 4 = 1
and
-2
is equivalent to 5 - 2 = 3
. Thus, s[-4:-2]
is same as
- s[1:3]
.
+ s[1:3]
.
+
The slice operator also allows the usage of a third index which is known as step as it allows a user to
step over (skip) characters.
>>> s = "Hello"
@@ -4010,7 +4089,8 @@ E = mc²
In the above example, the substring begins at the start of the string, takes a step size of
2
skipping e
and ends at the last character again skipping the 4th character
- l
.
+ l
.
+
Membership#
in
and not in
operators can be used to determine whether a substring is
present/not present in a string.
@@ -4160,7 +4240,8 @@ E = mc²
partition()#
partition(sep)
method splits the string when the separator (sep
) is encountered
for the first time, and returns a tuple with three items
- (string before separator, separator, string after separator)
.
+ (string before separator, separator, string after separator)
.
+
>>> "Hi|Ed|Punk".partition('|')
('Hi', '|', 'Ed|Punk')
@@ -4234,9 +4315,11 @@ E = mc²
The following string methods are useful for locating substring in a string.
count()#
count(sub[, start[, end]])
returns the number of non-overlapping occurrences of a substring
- sub
in the range [start, end]
.
+ sub
in the range [start, end]
.
+
start
and end
are optional parameters and they default to 0
and
- len(string)
respectively.
+ len(string)
respectively.
+
>>> s = "she sells sea shells"
>>> s.count("she")
2
@@ -4258,12 +4341,15 @@ E = mc²
In the above example, ala
is counted twice as the first occurence is in
valh"ala"
and the next occurance is in "ala"la
. Although ala
can
be located again in al"ala"
, it overlaps with the occurance "ala"la
, hence it
- is not counted.
+ is not counted.
+
find()#
find(sub[, start[, end]])
returns the lowest index in the string where substring
- sub
is located in the range [start, end]
.
+ sub
is located in the range [start, end]
.
+
start
and end
are optional parameters and they default to 0
and
- len(string)
respectively.
+ len(string)
respectively.
+
The method returns -1
in case the substring is not present.
>>> s = "she sells sea shells"
>>> s.find("she")
@@ -4279,9 +4365,11 @@ E = mc²
rfind()#
rfind(sub[, start[, end]])
returns the highest index in the string where substring
- sub
is located in the range [start, end]
.
+ sub
is located in the range [start, end]
.
+
start
and end
are optional parameters and they default to 0
and
- len(string)
respectively.
+ len(string)
respectively.
+
The method returns -1
in case the substring is not present.
>>> s = "she sells sea shells"
>>> s.rfind("she")
@@ -4333,9 +4421,11 @@ ValueError: substring not found
replace()#
replace(oldsub, newsub[, count])
returns a copy of the string with all occurrences of
- oldsub
substring replaced by newsub
.
+ oldsub
substring replaced by newsub
.
+
count
is an optional parameter which when provided, only replaces the first
- count
occurrences from the string.
+ count
occurrences from the string.
+
>>> s = "Oh Python! Oh"
>>> s.replace("Oh", "Hi")
'Hi Python! Hi'
@@ -4405,7 +4495,8 @@ n
This method of creating a list from a collection of literals is known as list display.
Notice, how this list contains items of multiple data types - str
, int
and
- bool
.
+ bool
.
+
Apart from the list display shown above, the built-in list()
function can also be used to
create new lists.
If no arguments are provided to the list()
function, an empty list is created.
@@ -4515,9 +4606,11 @@ n
Slicing#
A subset of list l
can be obtained using the list slice notation given as
l[i:j]
, where the item at start index i
is included, but the item at end index
- j
is excluded.
+ j
is excluded.
+
For example, the slice notation [1:4]
refers to items from index 1
to index
- 3
(i.e. 4-1
).
+ 3
(i.e. 4-1
).
+
>>> l = ["BMW", "Z4", 2019,
... 4, "Red", True]
>>> l[1:4]
@@ -4525,7 +4618,8 @@ n
The slice notation l[i:j:k]
can also include a third number known as the stepper. Here, a
list is sliced from start index i
to end index (j
) - 1 with a step of
- k
items.
+ k
items.
+
>>> l = ["BMW", "Z4", 2019,
... 4, "Red", True]
>>> l[1:4:2]
@@ -4604,9 +4698,11 @@ True
In location based or index based traversal the value of index starts at 0
and increments as
long as it is lesser than the length of the list.
This index value can be used to access the item at that index in a list using the index operator
- []
.
+ []
.
+
for
statement can be used to iterate over the index of the list using the
- range()
and len()
functions.
+ range()
and len()
functions.
+
Code
l = ["BMW", "Z4", 2019,
4, "Red", True]
@@ -4732,9 +4828,11 @@ True
class="header-link" tabindex="-1" href="#counting-or-locating-items-in-a-list">#
An item x
can be located in a list using the index(x[, i[, j]])
method which
returns the first occurrence of the item at or after index i
and before index
- j
.
+ j
.
+
In case i
and j
are not specified they default to i=0
and
- j=len(l)
.
+ j=len(l)
.
+
>>> l = [34, 4, 6, 23, 4]
>>> l.index(4)
1
@@ -4771,7 +4869,8 @@ True
Sorting a List#
Python lists have a built-in sort()
method which sorts the items in-place using
- <
comparisons between items.
+ <
comparisons between items.
+
The method also accepts 2 keyworded arguments:
key
is used to specify a function which is called on each list element prior to making
@@ -4887,7 +4986,8 @@ l = [["Kia", "Sonnet"
Thus, nested list is useful in representing a dataset where each item is a list (datum) containing the
attributes of an observation.
l[i][j]
is the syntax to fetch the j+1th
item of the list at index
- i
of the nested list l
.
+ i
of the nested list l
.
+
>>> l[2][1]
'Z4'
@@ -5127,7 +5227,8 @@ Frequency of Elements
How to Create Tuple?#
Tuples are declared using parentheses ( )
, with successive items separated by a comma
- ,
.
+ ,
.
+
>>> l = ("Hi", "Ed", "Punk")
>>> type(l)
<class 'tuple'>
@@ -5254,9 +5355,11 @@ TypeError: 'tuple'
href="#tuple-slicing">#
A subset of tuple t
can be obtained using the tuple slice notation given as
t[i:j]
, where the item at index i
is included, but the item at index
- j
is excluded.
+ j
is excluded.
+
For example, the slice notation [1:4]
refers to items from index 1
to index
- 3
(i.e. 4-1
).
+ 3
(i.e. 4-1
).
+
>>> t = ("BMW", "Z4", 2019,
... 4, "Red", True)
>>> t[1:4]
@@ -5264,7 +5367,8 @@ TypeError: 'tuple'
The slice notation t[i:j:k]
can also include a third number known as the step. Here, a tuple
is sliced from start index i
to end index (j
) - 1 with a step of
- k
items.
+ k
items.
+
>>> t = ("BMW", "Z4", 2019,
... 4, "Red", True)
>>> t[1:4:2]
@@ -5318,9 +5422,11 @@ True
In location based or index based traversal the value of index starts at 0
and increments as
long as it is lesser than the length of the tuple.
This index value can be used to access the item at that index in a tuple using the index operator
- []
.
+ []
.
+
for
statement can be used to iterate over the index of the tuple using the
- range()
and len()
functions.
+ range()
and len()
functions.
+
Code
t = ("BMW", "Z4", 2019,
4, "Red", True)
@@ -5372,7 +5478,8 @@ True
An item x
can be located in a tuple using the index(x[, i[, j]])
method which
returns the first occurrence of the item at or after index i
and before index
j
. In case i
and j
are not specified they default to
- i=0
and j=len(t)
.
+ i=0
and j=len(t)
.
+
>>> t = (34, 4, 6, 23, 4)
>>> t.index(4)
1
@@ -5440,7 +5547,8 @@ t = (
)
t[i][j]
is the syntax to fetch the j+1 th
item of the tuple at index
- i
of the nested tuple t
.
+ i
of the nested tuple t
.
+
>>> t[2][1]
'Z4'
@@ -5502,7 +5610,8 @@ AttributeError: 'tuple' How to Create a Dictionary'tuple' #
dict.fromkeys(iterable[, value])
can be used to create new dictionary with items of an
iterable
as keys with an optional value (default - None
) corresponding to the
- keys.
+ keys.
+
>>> l = ["yr", "name", 18]
>>> dict.fromkeys(l)
{'yr': None, 'name': None, 18: None}
@@ -5577,7 +5687,8 @@ AttributeError: 'tuple' Index Operator []#
d[x]
can be used to access the value corresponding to a key x
in a dictionary
- d
.
+ d
.
+
>>> d = {"yr": 20, "name": "Ed",
... 18: True}
>>> d["yr"]
@@ -5617,7 +5728,8 @@ AttributeError: 'tuple' update()#
update()
method can be used to add new items or update existing items in a
- dict
.
+ dict
.
+
This method accepts the following:
1. Dictionary
>>> d = {"yr": 20, 18: True}
@@ -5681,7 +5793,8 @@ AttributeError: 'tuple' pop()#
pop(key[, default])
method can be used to remove a key: value
pair.
In case the key is not present in the dictionary, the method returns the value of argument
- default
provided by the user.
+ default
provided by the user.
+
>>> d = {"yr": 20, "name": "Ed",
... 18: True}
>>> d.pop("name")
@@ -5699,7 +5812,8 @@ KeyError: 'name'
popitem()#
popitem()
can be used to destructively iterate over a dictionary removing and returning a
- (key, value)
pair in LIFO (Last Item First Out) order.
+ (key, value)
pair in LIFO (Last Item First Out) order.
+
>>> d = {"yr": 20, "name": "Ed",
... 18: True}
>>> d.popitem()
@@ -5941,7 +6055,8 @@ Sam Singh - 10000
programmers which saves a lot of time as they can be directly used in a program.
We have already used some functions in the previous sections like input()
,
output()
, len()
, sum()
, min()
, max()
,
- list()
, dict()
, etc.
+ list()
, dict()
, etc.
+
Some of the widely used functions can be categorized as follows:
- Mathematical Functions
@@ -5953,7 +6068,8 @@ Sam Singh - 10000
href="#mathematical-functions">#
abs()#
abs(x)
returns the absolute value or magnitude of x
of type int
,
- float
or complex
number.
+ float
or complex
number.
+
>>> abs(-2.3)
2.3
>>> abs(-10)
@@ -5972,7 +6088,8 @@ Sam Singh - 10000
sum()#
sum(sequence [,start])
returns the sum of items in a sequence
of type
- list
, tuple
, range
or set
.
+ list
, tuple
, range
or set
.
+
If a second argument start
is provided, it is added to the sum.
>>> sum([1, 2, -1])
2
@@ -5983,9 +6100,11 @@ Sam Singh - 10000
min()#
min(sequence)
returns the minimum value of items in a sequence
of type
- list
, tuple
, range
, str
or set
.
+ list
, tuple
, range
, str
or set
.
+
Apart from iterables, min(arg1, arg2, ..)
also accepts multiple arguments arg1
,
- arg2
.. of numeric type and returns the smallest among these arguments.
+ arg2
.. of numeric type and returns the smallest among these arguments.
+
>>> min([1, 2, -1])
-1
>>> min(1, 2, -1)
@@ -5998,9 +6117,11 @@ Sam Singh - 10000
max()#
max(sequence)
returns the maximum value of items in a sequence
of type
- list
, tuple
, range
, str
or set
.
+ list
, tuple
, range
, str
or set
.
+
Apart from iterables, max(arg1, arg2, ..)
also accepts multiple arguments arg1
,
- arg2
.. of numeric type and returns the largest among these arguments.
+ arg2
.. of numeric type and returns the largest among these arguments.
+
>>> max([1, 2, -1])
2
>>> max(1, 2, -1)
@@ -6124,7 +6245,8 @@ area = length * breadth
Area: 50
Both, input()
and print()
functions are covered in detail in the chapter
- Input & Output.
+ Input & Output.
+
open()#
open()
function is used to open a file and return the corresponding file object.
This function supports various modes useful for reading from a file and writing to a file.
@@ -6242,9 +6364,11 @@ area = length * breadth
fmod()
fmod(x, y)
returns the value of the expression x - n*y
such that the result has
the same sign as x
and magnitude less than |y|
for some integer
- n
.
+ n
.
+
This function should be preferred when working with floating point numbers as compared to
- x % y
that should be used when working with integers.
+ x % y
that should be used when working with integers.
+
>>> import math
>>> math.fmod(2.14, 0.5)
0.14000000000000012
@@ -6265,7 +6389,8 @@ area = length * breadth
sin(), cos() & tan()
sin(x)
, cos(x)
and tan(x)
return the sine, cosine and tangent of
- x
(radians) respectively.
+ x
(radians) respectively.
+
>>> import math
>>> math.cos(math.pi/3)
0.5000000000000001
@@ -6277,7 +6402,8 @@ area = length * breadth
factorial()
factorial(n)
computes the factorial of a positive integer n
which is the
product of all positive integers less than or equal to
- n
.
n! = nĂ—(n-1)Ă—(n-2)...3Ă—2Ă—1
,
where 0! = 1
+ n
.
n! = nĂ—(n-1)Ă—(n-2)...3Ă—2Ă—1
,
where 0! = 1
+
>>> import math
>>> math.factorial(5)
120
@@ -6295,7 +6421,8 @@ area = length * breadth
Random Integer from Range#
randrange(stop)
is used to randomly select an integer from a range 0
to
- stop
(excluding).
+ stop
(excluding).
+
>>> import random
>>> random.randrange(10)
5
@@ -6327,7 +6454,8 @@ area = length * breadth
Median#
median(data)
returns the median or middle value of data
(list
or
tuple
of int
or float
) using the common "mean of middle two"
- method.
+ method.
+
>>> from statistics import median
>>> median([1, 2, 3, 6])
2.5
@@ -6372,7 +6500,8 @@ area = length * breadth
It is easy to view and modify the contents of a text file using any text editor like notepad or even
IDLE.
Even the python script is stored as a text file given by the extension .py
.
- .txt
is the most popular extension used for a generic text file.
+ .txt
is the most popular extension used for a generic text file.
+
Although text files do not have any structure, there are international standards defining some rules for
creating specialized text files like:
@@ -6506,7 +6635,8 @@ area = length * breadth
After opening a file and performing some file operations, it can be safely closed using the
- close()
method.
+ close()
method.
+
For example, let us write a program to open a file data.txt
in read and append mode and
close the file object in the successive statement.
f = open('data.txt', 'a+')
@@ -6591,7 +6721,8 @@ Thank You
for
statement can also be used to traverse the file row-wise without any requirement of the
readline()
method. Simply iterating over the file object returns the data one row at a
- time.
+ time.
+
Code
f = open('info.txt', 'r')
for line in f:
@@ -6633,7 +6764,8 @@ Thank You
seek()#
seek(offset, reference=0)
can be used to seek a location in the file object which is
- offset
bytes from the provided reference
.
+ offset
bytes from the provided reference
.
+
The default value for reference
is 0
which stands for the beginning of the
file. For this default reference
, the offset
has to be a whole number
(>=0
).
@@ -6646,7 +6778,8 @@ Thank You
Note: In text files (those opened without a b
in the mode string), only
seek relative to the beginning of the file (reference = 0
) is allowed.
- reference = 1 or 2
is only valid when the file is opened in binary mode.
+ reference = 1 or 2
is only valid when the file is opened in binary mode.
+
Let us consider the same file info.txt
for the below example:
>>> f.seek(6)
6
@@ -6677,9 +6810,11 @@ Thank You
The following modes support file writing:
- Writing from the beginning of a file :
r+
, r+b
, w
,
- x
, wb
, w+
, w+b
.
+ x
, wb
, w+
, w+b
.
+
Appending at the end of an existing file : a
, ab
, a+
,
- a+b
.
+ a+b
.
+
The following methods can be used to write data in a file:
write()#
@@ -6716,7 +6851,8 @@ Thank You
Reading & Writing Binary Files using
pickle
Module#
+ href="#reading--writing-binary-files-using-pickle-module">#
+
In Python, the protocols to read and write binary files (.dat
or .pickle
file
extension) have been implemented in the built-in pickle
module.
pickle
is a Python specific binary file format which can not only be used to store binary
@@ -6724,7 +6860,8 @@ Thank You
This process of translating data structures (lists, dictionaries, etc.) and code objects (classes,
functions, etc.) into bytes that can be stored in a binary file is known as
Serialization. This binary file can be stored on disk or shared and it can be
- de-serialized and used later via Python.
+ de-serialized and used later via Python.
+
Dumping Data#
The dump()
function can be used to write the pickled representation of any data or object
@@ -6734,7 +6871,8 @@ Thank You
obj
is the object to be written
file
is an open file object (opened in binary write wb
or append
- ab
mode).
+ ab
mode).
+
>>> import pickle
>>> l = [["Anita","Maths",83],
@@ -6852,7 +6990,8 @@ End of file reached
Reading & Writing a CSV File using
csv
Module#
+ href="#reading--writing-a-csv-file-using-csv-module">#
+
Comma-separated value (CSV) file format is one of the most common data serialization and exchange format
where each row is a set of values separated by a delimiter.
The main rules for creating a CSV file are:
@@ -6886,7 +7025,8 @@ Ira,"Physics,Chemistry,Biology",99.0
object which iterates over CSV file line-by-line and returns it as a list of strings.
The csvfile
file object should be opened with newline=''
argument as the
csv
module has its own newline handling which correctly interprets the newlines depending
- on platform or in case they are embedded inside quoted fields.
+ on platform or in case they are embedded inside quoted fields.
+
Example #1
Let us write a program to read the contents of marks.csv
.
marks.csv
@@ -7041,7 +7181,8 @@ Ira;Science;99.0
followed while naming it. adder
is the name of the function in the above example.
The function name is followed by a pair of parenthesis ( )
.
In case any parameters are required by the function, they are enclosed inside the parentheses.
- f, s, t = None
are the three parameters of the function.
+ f, s, t = None
are the three parameters of the function.
+
Finally, the function header ends with a colon.
Function Body#
@@ -7096,12 +7237,14 @@ sm2 = adder(fst, snd)
Arguments are the values passed to a function (or method) when it is called. In the above example
fst
, snd
and trd
are the arguments. Since t
has a
default value, the function can be invoked with or without the trd
argument as shown for
- sm2
.
+ sm2
.
+
Argument values are assigned to the corresponding function parameters that are available as local
variables inside the function.
Thus, value of fst
is assigned to f
and snd
is assigned to
s
. In case there is no third argument, t
has the default value
- None
.
+ None
.
+
The values of sm1
and sm2
after executing the script are:
>>> sm1
40
@@ -7288,7 +7431,8 @@ repeat(d)
After saving the basics.py
file, reopen IDLE and create a new file test.py
in
the same directory as basics.py.
The name of the file is the module name which is also available as the value of the global variable
- __name__
in the module.
+ __name__
in the module.
+
Import the functions of the basics module in test.py
by executing the following statement.
import basics
@@ -7388,11 +7532,13 @@ Enter b: 5
Introduction to PyPi. How to Create a Python Package?#
A collection of modules which can work together to provide a common functionality is known as a
- package.
+ package.
+
These modules are present in a folder along with the __init__.py
file which tells Python
that this folder is a package.
A package can also contain subfolders (sub-packages), each containing their respective
- __init__.py
files.
+ __init__.py
files.
+
Let us take the example of a package called restaurant
which consists of various modules to
perform activities such as order booking, reservation, staff attendance, etc.
Here is a possible structure for the package:
@@ -7405,7 +7551,8 @@ Enter b: 5
A package is simply the directory containing sub-packages and modules, but when this package or a
collection of packages are made available for others to use (eg. via PyPI) it is known as a
- library.
+ library.
+
For example, restaurant
can be called a library if it provides reusable codes to manage a
restaurant and is built using multiple packages which handle the various aspects of a restaurant like
human resource management, inventory management, order fulfilment and billing, etc.
@@ -7430,7 +7577,7 @@ Enter b: 5
@@ -7463,13 +7610,7 @@ Enter b: 5
Tokens: Identifiers
Tokens: Literals
- - Numeric Literals
-
-
+ - Numeric Literals
- Boolean Literals
- String Literals
- Special Literal
@@ -7477,35 +7618,16 @@ Enter b: 5
Tokens: Operators
- Tokens: Delimiters
-
-
+ Tokens: Delimiters
Character Set
Blocks and Indentation
- Comments
-
-
+ Comments
Variables, Objects & Data Types
- What are Objects & Variables?
- - Variables & Assignment Statements
-
- - Assignment
- - Deletion
- - Multiple Assignment
- - Tuple Swapping
-
-
+ - Variables & Assignment Statements
- Built-in Data Types
- Type Checking
- - Type Casting
-
-
- - Mutable & Immutable Data Types
-
-
+ - Type Casting
+ - Mutable & Immutable Data Types
Input / Output
@@ -7540,55 +7652,23 @@ Enter b: 5
Operators & Expressions
- - Introduction to Operators
-
-
+ - Introduction to Operators
- Arithmetic Operators
- Relational Operators
- Assignment Operators
- - Logical Operators
-
-
+ - Logical Operators
- Identity Operators
- Membership Operators
- - Expressions
-
-
- - Operator Precedence with Examples
-
- - Exercises
-
-
+ - Expressions
+ - Operator Precedence with Examples
Errors & Exception Handling
- Error Types
- - Syntax Error
-
- - Script Mode
- - Interactive Mode
-
-
- - Runtime Error
-
-
- - Logical Error
-
- - Example
-
-
+ - Syntax Error
+ - Runtime Error
+ - Logical Error
- Exceptions
- raise
@@ -7602,25 +7682,9 @@ Enter b: 5
- Introduction to Control Flow
- Sequential Flow
- - Selection Statements: if .. else
-
- - Examples
-
-
- - Iteration: for
-
-
- - Iteration: while
-
- - Exercises
-
-
+ - Selection Statements: if .. else
+ - Iteration: for
+ - Iteration: while
- Jump Statements
- - Nested Loops
-
- - Factorial
- - Nested Loop - break
-
-
+ - Nested Loops
- Strings
- - Strings: Introduction & Creation
-
-
- - Accessing Characters of a String
-
- - Length of String
-
-
- - String Operations
-
- - Slicing
- - Membership
- - Concatenation
- - Repetition
-
-
+ - Strings: Introduction & Creation
+ - Accessing Characters of a String
+ - String Operations
- Introduction to String Methods
- - Convert Case of Strings
-
- - lower()
- - upper()
- - swapcase()
- - capitalize()
- - title()
-
-
- - Check Characters of a String
-
-
- - Split a String
-
- - partition()
- - split()
-
-
- - Strip Characters from a String
-
-
+ - Convert Case of Strings
+ - Check Characters of a String
+ - Split a String
+ - Strip Characters from a String
- Check Prefix or Suffix in a String
- Find & Replace Characters in a String
-
-
- - Traversing a String
-
- - Using
for
- - Using
while
-
+ - Traversing a String
- List
- What is a Python List? How to Create a
List?
- - Accessing Items of a List
-
-
+ - Accessing Items of a List
- Modifying a List
- Removing Item from a List
- - List Operations
-
- - Membership
- - Concatenation
- - Repetition
- - Slicing
-
-
- - Traversing a List
-
-
+ - List Operations
+ - Traversing a List
- Built-in Functions that can be used
for a List
- Introduction to List Methods
@@ -7748,52 +7730,19 @@ Enter b: 5
- Sorting a List
- Copying a List
- Nested List
- - List Comprehension
-
-
- - Sample Programs
-
-
+ - List Comprehension
+ - Sample Programs
- Tuple
- List vs Tuple
- - How to Create Tuple?
-
- - tuple()
-
-
+ - How to Create Tuple?
- What is a Singleton?
- - Accessing Items of a Tuple
-
-
+ - Accessing Items of a Tuple
- Tuples are Immutable
- - Tuple Operations
-
- - Membership
- - Concatenation
- - Repetition
- - Tuple Slicing
-
-
- - Traversing a Tuple
-
-
+ - Tuple Operations
+ - Traversing a Tuple
- Built-in Functions that can be used
for a Tuple
- Locating Items in a Tuple
@@ -7808,123 +7757,31 @@ Enter b: 5
- Dictionary
- What is a Dictionary?
- - How to Create a Dictionary
-
-
+ - How to Create a Dictionary
- Accessing Items (Key:Value) of a
- Dictionary
-
- - Index Operator []
- - get()
-
-
- - Updating a Dictionary
-
- - Index Operator []
- - update()
- - setdefault()
-
-
+ Dictionary
+ - Updating a Dictionary
- Removing an Item (Key:Value) from a
- Dictionary
-
-
- - Dictionary Operations
-
- - Membership
- - Union
-
-
- - Traversing a Dictionary
-
-
- - Built-in Functions for a Dictionary
-
- - Number of Items
- - Min and Max
-
-
+ Dictionary
+ - Dictionary Operations
+ - Traversing a Dictionary
+ - Built-in Functions for a Dictionary
- Creating a Copy of a Dictionary
- Nested Dictionary
- - Sample Programs
-
-
+ - Sample Programs
Python Standard Library
- Built-in Functions
- - Mathematical Functions
-
-
- - Type Functions
-
-
- - I/O Functions
-
-
- - Base/Unicode Conversion Functions
-
-
+ - Mathematical Functions
+ - Type Functions
+ - I/O Functions
+ - Base/Unicode Conversion Functions
- What are Built-in Modules?
- - math Module
-
-
- - random Module
-
-
- - statistics Module
-
-
+ - math Module
+ - random Module
+ - statistics Module
File Handling
@@ -7936,37 +7793,16 @@ Enter b: 5
File Opening & Closing
File Reading
- - Sequential Reading
-
- - read()
- - readline()
- - readlines()
-
-
- - Ad-hoc Reading
-
-
-
-
- Writing a File
-
- -
-
- - write()
- - writelines()
-
-
+ - Sequential Reading
+ - Ad-hoc Reading
+ Writing a File
Reading & Writing Binary Files
using pickle
Module
Reading & Writing a CSV File using
@@ -7981,26 +7817,11 @@ Enter b: 5
User Defined Functions, Modules & Packages
What is a Module? How to Create a Module?
Executable Scripts / Modules