Chapter 1
A quick Introduction to Python
This chapter presents a crash course on Python to kick
start the statistical techniques using Python. First, the
complete installation of Anaconda distribution of
Python is described for Windows, Mac OS and Linux
operating systems. Second, mathematical operators,
functions, control statements and Python data
structures are explained with practical examples.
Finally, mostly used Python libraries for statistics are
presented.
1.1 Installation and Setup of Python
Environment
This book utilizes Python 3, the latest release of
Python. We may download and install Python from the
official website Python Software
Foundation https://www.python.org/download.
However, we have to install libraries and packages
separately when we follow the aforementioned
installation.
One of the convenient ways to get started is to install
Python using Anaconda distribution. Anaconda is a
free and open-source distribution that comes with its
own package manager. Moreover, it includes multiple
libraries for Windows, Linux, and macOS operating
systems. Since libraries are included in this
distribution, we do not need to install them separately.
.
Figure 1.1: Anaconda Installers for Windows, MacOS
and Linux Individual Edition.
We download Anaconda Individual Edition from
https://www.anaconda.com/products/individual as
shown in Figure 1.1. We select the proper operating
system and its version either 32-bit or 64-bit from the
aforementioned link. To install Anaconda and setup
Python, the following sections give a step-by-step
guide for Windows, Mac OS and Linux.
1.1.1 Windows
1. Download the graphical Windows installer from
https://www.anaconda.com/products/individual
2. Double-click the downloaded file and click
continue to start the installation.
3. Answer the prompts on the Introduction, Read
Me, and License screens.
4. Click the Install button to install Anaconda in a
specified directory (C:\Anaconda3_Python)
directory given in the installation.
Figure 1.2: Installing Anaconda on Windows.
Figure 1.3: Installing Anaconda on Windows.
Figure 1.4: Installing Anaconda on Windows.
Figure 1.5: Installing Anaconda on Windows.
Figure 1.6: Installing Anaconda on Windows.
Figure 1.7: Installing Anaconda on Windows.
Figure 1.8: Installing Anaconda on Windows.
Figure 1.9: Installing Anaconda on Windows.
1.1.2 Apple OS X
1. Download the graphical MacOS installer from
https://www.anaconda.com/products/individual
2. Double-click the downloaded file and click
continue to start the installation.
3. Click the Install button to install Anaconda in the
specified directory
Figure 1.10: Installing Anaconda on Mac OS.
Figure 1.11: Installing Anaconda on Mac OS.
Figure 1.12: Installing Anaconda on Mac OS.
Figure 1.13: Installing Anaconda on Mac OS.
1.1.3 GNU/Linux
Since graphical installation is not available, we use
Linux command line to install Anaconda. The copy of
the installation file is downloaded from
https://www.anaconda.com/products/individual
We follow the procedure mentioned below for
Anaconda installation on Linux system.
1. Open a copy of Terminal on Linux.
2. Change directories to the downloaded copy of
Anaconda on the system.
3. The name of the file normally appears as
Anaconda‐3.7.0‐Linux‐x86.sh for 32‐bit systems
and Anaconda‐3.7.0‐Linuxx86_64.sh for 64‐bit
systems. The version number appears in the
filename. In our case, the filename refers to version
3.7, which is the version used for this book.
4. Type
bash ~/Downloads/Anaconda3-2020.02-Linux-
x86.sh (for the 32‐bit version) or
bash ~/Downloads/Anaconda3-2020.02-Linux-
x86_64.sh (for the 64‐bit version) and press Enter.
5. An installation wizard opens up and asks you to
accept the licensing terms for using Anaconda.
6. Accept the terms using the method required for the
version of Linux.
7. The wizard asks you to provide an installation
location for Anaconda. Choose a location, and click
next.
8. The application extraction begins. A completion
message pops up once the extraction is complete.
1.1.4 Creating and Using Notebooks
Once Python installation is complete, we start
exploring its features and writing code to perform tasks.
We launch Jupyter Notebook accompanied with
Anaconda installation. The Jupyter Notebook is a web
application that allows us to create Python code, plots,
visualizations and equations. It can be launched by
• the Anaconda Navigator by searching it in Windows
Search Box. Open Jupyter Notebook as shown in
Figure 1.14.
• writing Jupyter Notebook in Windows Search Box
as shown in Figure 1.15.
Figure 1.14: Launching the Jupyter Notebook using
Anaconda Navigator.
Figure 1.15: Launching Jupyter Notebook from
Windows search box.
Figure 1.16: Creating a new Python 3 file in Jupyter
Notebook.
Jupyter Notebook opens in a new browser page as
shown in Figure 1.16. To create a new notebook, go to
New on the top right side of the page and select Python
3.
The box highlighted in the bottom of Figure 1.17 has
In [ ]: written next to it. This is the place where we
can start typing our Python code. The Notebook can be
given a meaningful name by clicking on Untitled1 next
to the Jupyter icon in the top left corner of the
Notebook. Make sure the highlighted box in the middle
of Figure 1.17 is selected to Code.
Figure 1.17: Start working with a Jupyter Notebook.
We are now ready to write our first program. Place the
cursor in the cell. Type print("Hello World") and
click on the Run button on the toolbar. The output of
this line of code appears on the next line as shown in
Figure 1.18.
Figure 1.18: Output of the print statement in Python.
The shortcut to run the code present in a cell is to hit
shift+enter keys together. Notebook shows the result
of running the code right below the cell. A new cell is
automatically created for next commands / piece of
code to be entered.
Besides code, Jupyter Notebook’s cells can be used to
enter text to elaborate the code. For this purpose, we
use markdown cells. A markdown cell displays text and
mathematical equations formatted using a markdown
language. To convert to a markdown cell, we click on
cell menu and select Markdown as shown in Figure
1.19. The In [ ] prompt will disappear to signify that
the text written in the cell is not an executable Python
code.
Figure 1.19: A markdown cell
The Python is an interpretable language: The Python
code is executed on a Python virtual machine one line
at a time. The interpreter acts as a calculator. We can
type an expression in the cell and it will return us the
output value. The significance of an interpreted
language such as Python is that there is abstraction
between the code and the platform. This makes Python
code portable across different platforms. For example,
the same code running on Windows can also run on
Linux.
We can download and save a Notebook by clicking on
the File drop down menu, selecting Download as and
clicking on Notebook (.ipynb) as shown in Figure 1.20.
The downloaded files can be used in future by going to
the File drop down menu and clicking open.
The code, we generate for the tasks presented in this
book resides in a repository on the hard drive of the
computer system. A repository is a kind of filing cabinet
or folder where we save our code. We can modify and
run individual pieces of code within the folder, and add
new code to the existing one.
Figure 1.20: Saving a Jupyter Notebook for future
use.
1.2 Mathematical Operators in Python
Data comes in numerous forms such as numbers,
logical values, special symbols and text. Numbers can
be integer or floating-point whereas the logical values
can be true or false that can be used to make
decisions. For example, to find out whether one
quantity is greater than another one, we may use
logical values.
The arithmetic operators in Python are symbols which
are used to perform arithmetic operations for instance
addition, subtraction, multiplication and division.
Similarly, logical operators are used to perform logical
operations. First, we discuss the data types used by
Python to represent numbers and logical values. Next,
we discuss arithmetic and logical operators.
Python offers numerous data types to represent
numbers and logic values; these are given below.
Integer: An integer is a whole number without any
fractional part. 5 is a whole number; it is an integer.
Conversely, 5.0 is not an integer because it has a
decimal part. Integers are represented by the data type
int in Python.
Float: A floating-point number contains a decimal part.
For example, 3.5 is a floating‐point number. Python
stores floating‐point values in the data type float.
Complex: A complex number comprises of paired
numbers: a real number and an imaginary number. The
imaginary part of a complex number always appears
with a j. If we create a complex number with 2 as the
real part and 8 as the imaginary part, we make an
assignment like this:
1. cmplx_no = 2 + 8j
Bool: Logical arguments require Boolean values
represented by data type bool in Python. A variable of
type bool can either be True or False. The first letter of
both keywords is capital. We can assign a Boolean
value to any variable using the keywords True or False
as
1. x = True
2. type(x) # it returns the type of x as bool.
Alternatively, to define a bool variable, we create an
expression that defines a logical idea. As an example,
1. bool_variable = 8 < 4
returns False because 8 is not smaller than 4.
1.2.1 Arithmetic Operators
To perform addition, subtraction, multiplication and
division, we use arithmetic operators +, -, * and /,
respectively. Arithmetic operations can be combined
using parentheses ( ). To understand the working of
these operators, type the following code.
1. 3+10-6
Output:
7
1. 30-5*8
Output:
-10
1. (30-5*8)/5
Output:
-2
1. 20 / 8 # division returns a floating-point
number
Output:
2.5
The integer numbers, e.g., the number 20 has type int,
whereas 2.5 has type float. To get an integer result
from division by discarding fractional part, we use the
// operator.
1. 20 // 6
Output:
3
To calculate the remainder, we use % operator.
1. 20%6
Output:
2
To calculate powers in Python, we use ** operator.
1. 3**4
Output:
81
Operations involving int and float type operands return
the output having the data type float.
1. type(5 * 4.6)
Output:
float
Python supports complex numbers; it uses the suffix j
or J to indicate the imaginary part of a complex number.
To create a complex number, we type the following
command.
1. 2+7j
Output:
(2+7j)
1.2.2 Bitwise operators
To comprehend bitwise operations, we have to
understand how data is stored and processed in
computers as binary numbers. A bit is a binary digit 0
or 1. The computer represents every number as a
series of 0s and 1s in its memory. For instance, decimal
number 5 equals 0000 0101 in binary when we use 8
bits to represent a binary number in a computer.
Negative numbers are represented in computers with
a leading 1 on the left side instead of a leading 0. This
procedure has two steps:
1. Invert individual bits of the number (this is
known as taking 1’s complement of the
number). Operator ~ is used to take 1’s
complement.
2. Adding a 1 to 1’s complement (this is known as
taking 2’s complement of the number).
For example, decimal -4 can be converted to binary by
first taking 1’s complement of 4 (0000 0100) that results
in 1111 1011 in binary. Now adding a 1 to 1111 1011
results in 1111 1100 that is a binary representation of -
4. To take negative of number 4 in Python, we may
type.
1. # ~4 calculates 1’s complement, 1 is added to it
to get 2’s complement or negative of 4.
2. ~4+1
Output:
-4
Bitwise operators operate on individual bits of the
operands. Let the operands be
• x = 3 (0000 0011 in binary) and
• y = 9 (0000 1001 in binary).
We discuss bitwise operators and apply them to the
aforementioned operands.
Bitwise AND ( & ): It returns 1 if corresponding bits of
x and y are 1, otherwise it returns 0.
1. x & y
Output: 1
Bitwise OR ( | ): It returns 1 if any of the corresponding
bit of x or y is 1, otherwise it returns 0.
1. x | y
Output:
11
Bitwise NOT ( ~ ): It returns -(x+1), for a variable x,
that is one’s complement of x. In other words, it inverts
all the bits of x.
1. ~x
Output:
-4
Bitwise XOR ( ^ ): It returns 1 if only one of the
corresponding bits of x or y is 1, otherwise it returns 0.
1. x ^ y
Output:
2
Bitwise right shift ( >> ): It shifts the bits of the
operand towards right by the amount specified in
integers on the right side of the operator. Specifying a
float on the right side of the operator >>, for example,
y>>3.5, gives an error message.
1. y >> 2
Output:
2
Bitwise left shift ( << ): It shift the bits of the operand
towards left by the amount specified in integers on the
left side of the operator. Specifying a float on the right
side of the operator <<, for example, y<<3.5, gives an
error message.
1. x << 2
Output:
12
1.2.3 Assignment Operators
A variable is used to store the operands and result of
the operations performed on these operands. It can be
considered as a container that holds our information.
We store our results in a Python Notebook using
variables. We make an assignment to a variable to
store our data. Various assignment operators
supported by Python are given below. The equal sign
(=) is used to assign a value to a variable.
1. marks1 = 75
2. marks2 = 85
3. marks1 + marks2
Output:
160
Variable names in Python are case-sensitive. It means
that variable name height and Height are not the same.
If a variable is not assigned any value (not defined), we
get an error when we try to use it:
1. Marks1
Output:
NameError: name 'Marks1' is not defined
The following code assigns value 10 to my_var, then
adds value 20 to it. Thus, the result stored in my_var
becomes 30.
1. my_var = 10
2. my_var+=20
3. my_var
Output:
30
In the aforementioned code, we have used += as an
assignment operator in my_var+=20 that is equivalent
to my_var=my_var+20. Other arithmetic operators,
such as -, *, / etc. can be used along with = as
assignment operators. For example, try the following
code to observe the output.
1. my_var1 = 10
2. my_var2 = 4
3. my_var1**= my_var2
4. my_var1
Output:
10000
1.2.4 Logical Operators
Logical operators work on logical operands that can
assume one of two values: True and False. The logical
operators used in Python are given below.
Logical and: It returns True only when both the
operands are true.
1. x=True
2. y=False
3. x and y
Output:
False
Logical or: It returns True if either of the operands is
true.
1. x=True
2. y=False
3. x or y
Output:
True
Logical not: It complements the operand.
1. x=True
2. not x
Output:
False
1.2.5 Comparison Operators
Comparison operators are used to find relationship
between two operands if they are equal or one of the
operands is greater than another operand or vice
versa. These operators return either True or False, and
are extensively employed to make decisions in
programming. The details of comparison operators is
given below.
Let x = 6 and y = -8 be the operands.
Equal ==: It checks if both operands x and y are
equal.
1. x==y
Output:
False
Not equal !=: It checks if both operands x and y are
not equal.
1. x!=y
Output:
True
Greater than >: It checks if one operand is greater
than the other operand.
1. x > y
Output:
True
Less than <: It checks if one operand is smaller than
the other operand.
1. x < y
Output:
False
Greater than or equal to >=: It checks if one operand
is greater than or equal to the other operand.
1. x >= y
Output:
True
Less than or equal to <=: It checks whether one
operand is less than or equal to the other operand.
1. x <= y
Output:
False
1.2.6 Membership Operators
These operators are used to find whether a particular
item or set of items are present in a collection or not.
The membership operators are in and not in.
They are used to test whether a value or variable is
found in a sequence such as string, list, tuple, set and
dictionary. These operators are used in the following
example.
1. x = 'Hello world' # x is a string of characters
2. print('H' in x) # returns True if ‘H’ is in x
3. print('Hello' not in x) # returns True if ‘Hello
’ is not present in x
4.
Output:
True
False
1.3 String Operations
Text data includes numbers, alphabets, spaces and
special characters such as comma, full stop and
colon. Python represents text using string data type. It
provides us with rich resources to manipulate strings.
Since computers work on binary numbers, they convert
string characters into numbers using a standard called
Unicode. This number is then stored in the memory.
For instance, the letter A is converted to its Unicode 65.
Type ord("A") in the Jupyter cell, and press Enter to
observe 65 as an output. If a decimal number is
represented as text, its Unicode value will be different
from that number. For example, Unicode for number 9
is 57. In Python, strings are specified either by:
• Enclosing characters in single quotes ('...') or
• Enclosing characters in double quotes ("...")
In Python, a string is an array of bytes representing
Unicode characters. A single character is a string with
a length of 1. Type the following code to observe the
output.
'An example string in single quotes.'
Output:
'An example string in single quotes.'
"A string in double quotes."
Output:
' A string in double quotes.'
Multiple strings can be specified and printed using the
print statement. A comma is used to separate different
strings. Try the following code to print multiple strings.
print( 'Mango', 'and apple', 'are fruits')
Output:
Mango and apple are fruits
We get an error message when we try to print a single
quote in a string enclosed in '…'. The same error
message is displayed if we try to print a double quote
in a string enclosed in “…”.
print('Why don't we visit the museum?')
Output:
File "<ipython-input-96-868ddf679a10>", line 1
print(' Why don't we visit the museum?')
^
SyntaxError: invalid syntax
To print such characters, we use backslash \, called the
escape character.
1. print('Why don\'t we visit the museum?.')
Output:
Why don't we visit the museum?
The print () function omits the enclosing quotes in the
output. Special tasks can be performed using escape
characters. For example, \t generates a tab and \n
produces a new line within the print statement.
print('Why don\'t we visit \t the museum?')
Output:
Why don't we visit the museum?
print(' Why don\'t we visit \n the museum?')
Output:
Why don't we visit
the museum?
Suppose we want to display the path of a directory
such as C:\new_directory using a print statement. We
will get a new line because \n in the directory name
produces a new line. To ignore the new line due to \n
in the directory path, we use the letter 'r' in the start of
the directory name as follows:
print(r'c:\new_directory')
Output:
c:\new_directory
When an 'r' or 'R' prefix is used in a string, a character
following a backslash is not considered as an escape
character, and all backslashes are taken as string
characters.
The operator + can be used to concatenate strings
together.
1. mystr1 = 'Computer Vision'
2. mystr2 = ' using'
3. mystr3 = ' Python'
4. mystr1 + mystr2+ mystr3
Output:
' Computer Vision using Python'
String Indexing
The string elements, individual characters or a
substring, can be accessed in Python using positive as
well as negative indices. Indexing used by Python is
shown in Figure 1.21.
Figure 1.21: Access elements of a string using
positive and negative indices.
Square brackets are used to access string elements.
For instance:
1. x = "This is a test string"
2. print(x[0])
Output:
T
The indices start from 0 in Python. To access last
character of the string, we may write
print(x[-1])
Output:
g
A substring can be extracted from a string using
indexing. This process is known as string slicing. If x
is a string, an expression of the form x[i1:i2] returns the
x from position i1 to just before i2. A range of indices is
specified to access multiple characters of a string.
1. print(x[0:7])
Output:
This is
The characters of x from index 0 to 6 are returned by
the aforementioned statement. The index 7 is not
included. To get string characters from a specific index
to the last index, we may type the following statement.
print(x[8:len(x)])
Output:
a test string
The string slice begins from the start of the string even
if we omit the first index: x[:i2] and x[0:i2] give the same
result.
If we want to get every kth character in the string, we
specify a stride or a step in the string indexing. A stride
or a step specifies the size of step between string
characters. A stride is set if we add an additional colon
in string indexing. For example, to retrieve every
second character of the string x starting from index 1
to index 11, we specify a step of 2 as follows:
1. x = 'This is a test string'
2. x[1:12:2]
Output:
'hsi e'
If we use a negative stride, we step backward through
the string. Negative stride requires the first index to be
greater than the second one. To retrieve string
characters from the last index to the index 1, we may
type the following.
1. x = 'This is a test string'
2. x[:0:-2]
Output:
'git stas i'
Note that the first character of string x, T, is not
displayed because we have specified a range of
indices from end to 1 (index 0 is not included). We get
a different output, when we write the following script.
1. x = 'This is a test string'
2. x[::-2]
Output:
'git stas iT'
To replicate a string multiple times, we use the operator
*. To generates five copies of the string ‘Hello’, type.
1. str = 'Hello ' * 5
2. str
Output:
'Hello Hello Hello Hello Hello '
In Python, strings can be manipulated using numerous
built-in methods (functions). The method strip()
eradicates any whitespace from the beginning or the
end of a string.
1. str1 = " This is a text string "
2. print(str1.strip())
Output:
This is a text string
To convert a string to lower case, we use the method
lower().
1. str2 = "This is a text string"
2. print(str2.lower())
Output:
this is a text string
To convert a string to upper case, we use the method
upper().
1. str3 = "This is a text string"
2. print(str3.upper())
Output:
THIS IS A TEXT STRING
To replace characters of a sting, we use the method
replace().
1. str4 = "I ate a banana"
2. print(str4.replace("banana", "mango"))
Output:
I ate a mango
To break a sting into smaller strings, we use the
method split() along with a specified separator.
1. str5 = 'Hi mate, how do you do?'
2. print(str5.split(","))
Output:
['Hi mate', ' how do you do?']
In the aforementioned code, we have used a comma
as a separator. Other characters can also be specified
to serve as separators.
1.4 Conditional Statements and Iterations
Conditional statements are used when we need to
make decisions in our program. A block of code is
executed only if a certain condition is satisfied, and a
different piece of code is run otherwise. Conditional
statements provided by Python are:
1. 'if',
2. 'elif' and
3. 'else'.
'If' statement can be used standalone, but 'elif' and
'else' are always accompanied by a corresponding
'if' statement. We give the details and usage of these
statements in the following sections.
1.4.1 If, elif and else Statements
'If'
statement is the simplest conditional statement.
The syntax (proper arrangement of symbols and
keywords to constitute a correct programming
command) of an 'if' statement is:
if(condition):
Statement1
Note that the line following the if(condition): is
indented. We may specify more indented statements
after the Statement1. Statements indented the same
amount after the colon (:) are part of the 'if' statement.
These statements run when the condition of if
statement is True. In case this condition is False,
Statement1 and other indented statements will not be
executed. Figure 1.22 shows the flowchart of an if
statement.
Figure 1.22: Flow chart of an 'if' statement.
For instance, we want to record and display the marks
of a students obtained in a particular subject. The total
marks obtained should not exceed 100. The program
should display an error or warning when marks are
greater than 100. Python script incorporating an if
statement would be as follows.
1. student_marks = 90
2. if(student_marks > 100):
3. print("Marks exceed 100.")
The colon (:) after if(student_marks>100) is important
because it separates the condition from the
statements. The condition inside if(condition) is
evaluated; it returns True if the condition is fulfilled, and
False otherwise. Arithmetic, logical and conditional
operators can be employed to design a condition.
An input from a user can also be used to form a
condition. For instance, a user of the program can be
asked to enter student_marks that can be used inside
an if statement.
1. print('Enter marks obtained by a student')
2. student_marks = int(input())
3. if(student_marks > 100):
4. print("Marks exceed 100.")
Note that the input() function gets the input from the
user; it saves the input as a string. We use int(input())
to get an integer from the string. If we execute the
aforementioned program, and input marks greater than
100, we get a warning "Marks exceed 100". If the
entered marks are 100 or less, no warning message is
displayed.
else Statement
The statement 'else' is always accompanied by an
accompanying if statement, i.e., 'if-else'. The syntax
of if-else is given below.
if(condition):
Indented statement(s) when condition is True
else:
Indented statement(s) when condition is False
In our previous examples on student marks, let us
display the message “Outstanding”, if student_marks
are 80 or greater. A message “Not outstanding” is
displayed otherwise.
1. print('Input marks of a student')
2. student_marks = int(input())
3. if(student_marks >= 80):
4. print("Outstanding")
5. else:
6. print("Not outstanding ")
Figure 1.23: Flow chart of an 'if-else' statement.
Figure 1.23 presents the flowchart of an 'if-else'
statement. It can be observed that one of two blocks of
code will be executed based upon the evaluated
condition.
Nested Decisions
To take decisions under multiple conditions, Python
allows us to perform nested decisions. The 'if-elif-
else' statements are employed to accomplish nested
decisions. Continuing with the example of student
marks, if the marks of a student are greater than 100
or less than 0, a waring should be displayed.
Additionally, if obtained marks are 80 or greater,
Outstanding should be displayed. Otherwise, Not
outstanding should be displayed.
1. print('Enter marks of a student')
2. student_marks = int(input())
3. if(student_marks > 100 or student_marks < 0):
4. print("Invalid marks.")
5. elif(student_marks >= 80):
6. print("Outstanding")
7. else:
8. print("Not outstanding")
Note that we have a used a logical operator 'or' to
combine two conditions together inside the if
statement.
Figure 1.24: Flow chart of an 'if-elif-else' statement.
Figure 1.24 shows the flowchart of an 'if-elif-else'
statement. It can be observed that one block of code
will be executed based upon the condition to be
evaluated.
Further Readings
More information about conditional statements can
be found at
https://www.techbeamers.com/python-if-else/
1.4.2 For Loop
Iteration statements provided by Python allows us to
perform a task more than once. To iterate a task fixed
number of times, a 'for' loop is used. A 'for' loop has
a definite beginning and end. We provide a sequence
or a variable to the loop as an input that causes the
loop to execute a fixed number of times. The syntax of
a for loop is given as.
for loop_variable in sequence:
Statement(s) to be executed in the for loop
The flow chart of a 'for' loop is given in Figure 1.25.
Figure 1.25: Flow chart of a for loop.
Note the Statement(s) to be executed in the body of the
'for' loop are indented. The loop_variable is used
inside the 'for' loop, and the number of times the loop
runs depends upon the length of the sequence. To
implement the 'for' loop, type the following code.
1. subjects = ["Computer Vision",
"Machine Learning", "Data Science",
2. "Artificial Intelligence"]
3. for k in subjects:
4. print(k)
Output:
Computer Vision
Machine Learning
Data Science
Artificial Intelligence
In this example, “subjects” is a variable containing 4
items. This is used to decide the number of iterations
of a for loop. The loop runs 4 times because the
number of items in the variable subjects is 4.
The function range() is normally used in a 'for' loop to
generate a sequence of numbers. For example,
range(5) generates numbers from 0 to 4 (5 numbers).
The following code generates the first 5 numbers.
1. for k in range(5):
2. print(k)
Output:
0
1
2
3
4
We can also specify a step size other than 1 within the
range () function as follows.
1. for x in range(3, 12, 3):
2. print(x)
Output:
3
6
9
In range(3, 12, 3), 3 is the step size. The statements
break and continue are sometimes used inside the
loops. The break statement discontinues the execution
of the loop. The continue statement skips all the
statements of the for loop following the continue
statement. The usage of both statements is illustrated
in the following example.
1. students = ["Adam", "Alice", "Bob", "Emma",
"Julia"]
2.
3. for k in students:
4. if k == "Bob":
5. continue
6. print(k)
7. if k == "Emma":
8. break
Output:
Adam
Alice
Emma
The name Bob is not printed in the output because the
continue statement is executed when the value of k
equals Bob. Note that print(k) statement is not indented
with the 'if' statement; thus, it is not part of the 'if'
statement. Moreover, the code breaks right after it has
printed the name Emma.
1.4.3 While Loop
The 'while' loop runs certain statements iteratively as
long as its condition is true. The syntax of the while loop
is given below.
while (condition):
Statement(s) to be executed in the while loop
For instance, to add natural numbers up-to the number
input by a user, we use a while loop as follows.
1. # This program finds sum of first n natural numbe
rs, where the value of n is input by the user.
2.
3. n = int(input("Input an integer = "))
4.
5. # initialize variables sum and j (counter)
6. sum = 0
7. j = 1
8. while j <= n:
9. sum = sum + j
10. j = j+1 # update the counter variable
11. print("First", n, "natural numbers add up to ", s
um)
The user of this program is asked to input a natural
number upon execution of this program. A sum of 10 is
obtained if the number 4 is entered, and a sum of 55 is
returned upon entering the number 10. The 'while' loop
allows us to use break, continue and else statements
inside a while loop like a 'for' loop. Figure 1.26 presents
the flow chart of a while loop.
Figure 1.26: Flow chart of a while loop.
Nested Loops
A loop, either 'for' or 'while', can be used inside another
loop. This is known as a nested loop that can be used
when we work with the data in 2-dimensions. The
following program uses two 'for' loops, one nested
inside another, to print all the combinations of two
variables.
1. attributes = ["heavy", "wooden", "fast"]
2. objects = ["chair", "table", "computer"]
3. for j in attributes:
4. for k in objects:
5. print(j, k)
Output:
heavy chair
heavy table
heavy computer
wooden chair
wooden table
wooden computer
fast chair
fast table
fast computer
Further Readings
More information about iteration statements can be
found at
http://www.lastnightstudy.com/Show?id=84/Pytho
n-3-Iteration-Statements
https://www.w3schools.com/python/default.asp
1.5 Functions in Python
A function is a piece of code that performs a specific
task. Functions execute when they are called by their
names. Python permits us to define/create functions
using the keyword def. For instance, to define a
function, named as my_function1, we write the
following code.
1. def my_function1():
2. print("This is a test function")
To run this function, we type its name.
1. my_function1()
Output:
This is a test function
A function can accept one or more inputs by passing
parameters or arguments inside the braces ( ). For
instance, the following function accepts a string as its
input.
1. def my_function2(str_in):
2. print("This function prints its input that is
" + str_in)
3.
4. my_function2("computer")
5. my_function2("table")
6. my_function2("chair")
Output:
This function prints its input that is computer
This function prints its input that is table
This function prints its input that is chair
If a * is added before the parameter name while
defining the function, an input of variable size can be
passed as input / argument to the function. Thus, the
function is able to receive multiple inputs. The following
function elaborates this idea.
1. def my_function3(*myfruits):
2. print(myfruits[2], "is my favorite fruit.")
3. my_function3("Mango", "Apple", "Orange") # 3 inpu
ts.
Output:
Orange is my favorite fruit.
1. my_function3("Mango", "Orange","Apricot","Apple"
) # 4 inputs.
Output:
Apricot is my favorite fruit.
Data can be returned from a function when we use the
return statement as follows.
1. def mult_by_10(k):
2. return 10 * k
3. print(mult_by_10(2))
4. print(mult_by_10(-8))
5. print(mult_by_10(100))
Output:
20
-80
1000
Python allows us to define a function without any
name. This is called a lambda function (anonymous
function) which can receive multiple input arguments,
but has only one statement. To define a lambda
function, we use
lambda arguments : statement
To illustrate the creation and use of a lambda function,
we may type the following code.
1. x = lambda input_number : input_number - 10
2. print(x(10))
3. print(x(-10))
4. print(x(20))
Output:
0
-20
10
The aforementioned lambda function subtracts 10
from each input number.
1.6 Data Structures
In addition to commonly used data types int, float and
str, Python offers data types to store a collection of
multiple entries from numbers, alphabets,
alphanumeric, strings and special characters. The four
commonly used collection data types provided by
Python are as follows.
• List is a mutable and ordered collection that
allows duplicate entries.
• Tuple is an immutable and ordered collection
that also allows duplicate entries.
• Set is an unordered and unindexed collection
that, like real sets, prohibits duplicate entries.
• Dictionary is a mutable, unordered and indexed
collection of entries that prohibits duplicate
entries.
The following sections discuss these data types and
their usages.
1.6.1 Lists
A list is a mutable and ordered collection of elements.
Lists are specified using square brackets in Python.
For instance, to create a list named as item_list, type
the following code.
1. item_list = ["backpack", "laptop", "ball point",
"sun glasses"]
2. print(item_list)
Output:
['backpack', 'laptop', 'ball point', 'sun glasses']
To access any particular element / item of a list, we
refer its index number. For instance, to print the third
item of the list, we type the following code.
1. print(item_list[2])
Output:
ball point
Since Python permits negative indexing, we can use
them to access elements of a list. As an example, the
following piece of code prints the third last item of the
list.
1. item_list = ["backpack", "laptop", "ball point",
"sun glasses"]
2. print(item_list[-3])
Output:
laptop
To return the second and the third list items, we type
the following code.
print(item_list[1:3]) # Elements at index 1 and 2 but
not the one at 3.
Output:
['laptop', 'ball point']
Try the following, and observe the output
1. print(item_list[:3]) # returns list elements
from the start to "ball point"
2.
3. print(item_list[2:]) # returns elements from
"ball point" to the last element
4.
5. print(item_list[-3:-
1]) # returns elements from index -3 to -2
The index of a specific element can be used to change
the value of that element. For instance, to change the
second element of the item_list, type the following
1. item_list[1] = "computer"
2. print(item_list)
Output:
['backpack', 'computer', 'ball point', 'sun glasses']
Conditional statements can be used with a list. The
elements of a list can be checked using an if statement
and the keyword in as follows.
1. if "sun glasses" in item_list:
2. print("sun glasses are present in the list")
3. else:
4. print("sun glasses are not present in the lis
t")
Output:
sun glasses are present in the list
1.6.2 Tuples
A tuple is immutable and ordered collection of items. In
Python, tuples are specified using round brackets ().
The following code creates a tuple.
1. py_cv = ("Python", "for", "Computer Vision")
2. print(py_cv)
Output:
('Python', 'for', 'Computer Vision')
Elements of a tuple can be accessed using [ ]. For
instance:
1. print(py_cv[2])
Output:
Computer Vision
Similar to lists, we can use negative indexing and a
range of indexing. Since tuples are immutable, the
values present in a tuple are not changed once stored.
However, we can use loops to go through elements of
a tuple. The keyword 'in' can be used to determine if a
specified element is present in a tuple. The method
len() finds out the number of items present in a tuple.
The + operator can be employed to join two or more
tuples together. Finally, to delete a tuple named py_cv,
use the statement del py_cv.
The tuple method count() returns the number of times
a particular value appears in a tuple.
1. py_cv2 = ('Python', 'has support for', 'Computer
Vision')
2. print(py_cv2.count('Computer'))
3. print(py_cv2.count('Computer Vision'))
Output:
0
1
The tuple method index() is used to search the tuple
for a particular value. It returns the position where the
specified value is found. For example, type the
following code.
1. print(py_cv2.index('Python'))
2. print(py_cv2.index('Computer'))
Output:
0
ValueError: tuple.index(x): x not in tuple
A ValueError is printed if the value to be indexed for
does not exist in the tuple.
1.6.3 Sets
A set is an unindexed and unordered collection of
items. Python specifies sets using curly brackets { }.
For example, type the following code.
1. my_animals = {"cat", "dog", "tiger", "fox"}
2. print(my_animals)
Output:
{'dog', 'tiger', 'cat', 'fox'}
No index is linked to set items because sets are
unordered. Nevertheless, a loop can be used to go
through the set elements.
3. my_animals = {"cat", "dog", "tiger", "fox"}
4. for x in my_animals:
5. print(x)
Output:
dog
cat
tiger
fox
The printed output follows no order. The keyword 'in' is
used to check if a particular value is present in a set.
1. print("tiger" in my_animals)
2. print("lion" in my_animals)
Output:
True
False
Once a set is created, its elements cannot be changed.
However, new elements can be added to a set. The
method add() adds a single element to a set.
1. my_animals = {"cat", "dog", "tiger", "fox"}
2. my_animals.add("lion")
3. print(my_animals)
Output:
{'lion', 'cat', 'tiger', 'dog', 'fox'}
The output of the aforementioned program displays
items without any order. The method update() adds
multiple elements to a set.
1. my_animals = {"cat", "dog", "tiger", "fox"}
2. my_animals.update(["sheep", "goat", "sheep"])
3. print(my_animals)
Output:
{'cat', 'tiger', 'dog', 'goat', 'sheep', 'fox'}
The item 'sheep' appears once in the output because
sets do not allow duplicate entries. To find the number
of elements of a set, we use the method len() with the
set as an argument to this method.
To remove an element in a set, we use either the
method remove() or the method discard(). For
instance, we remove "tiger" as follows.
1. my_animals = {"cat", "dog", "tiger", "fox"}
2. my_animals.remove("tiger")
3. print(my_animals)
Output:
{'dog', 'cat', 'fox'}
Two or more sets can be joined together using the
method union(). Alternatively, the method update()
can be used to insert elements from one set into
another. Let us try the following code.
1. myset1 = {"X", "Y" , "Z"}
2. myset2 = {4, 5, 6}
3. myset3 = myset1.union(myset2)
4. print(myset3)
Output:
{4, 5, 6, 'Y', 'X', 'Z'}
Moreover, the method pop( ) removes a random item
from a set. The method clear ( ) empties the set, and
the keyword del before the name of the set deletes the
set completely.
1.6.4 Dictionaries
A dictionary is a mutable, unordered and indexed
collection of items. A dictionary in Python has a
key:value pair for each of its elements. Dictionaries
retrieve values when the keys are known. To create a
dictionary, we use curly braces { }, and put key:value
elements inside these braces where each pair is
separated from others by commas. For example, the
following piece of code creates a dictionary named
py_cv_dict.
1. py_cv_dict = {
2. "name": "Python",
3. "purpose": "Computer Vision",
4. "year": 2021
5. }
6. print(py_cv_dict)
Output:
{'name': 'Python', 'purpose': 'Computer Vision', 'year':
2021}
The dictionaries require the keys to be unique and
immutable string, number or tuple. The values, on the
other hand, can be of any data type and can repeat.
Square brackets are used to refer to a key name to
access a specified value of a dictionary.
1. print(py_cv_dict['name']) # accesses value for
key 'name'
2. print(py_cv_dict.get('purpose')) # accesses valu
e for key 'purpose'
Output:
Python
Computer Vision
A message: None is displayed if we try to access a
non-existent key.
print(py_cv_dict.get('address'))
Output:
None
We get the error: KeyError: 'address' to indicates that
the key 'address' does not exist, when we run
print(py_cv_dict['address']). The value of an element
can be changed by referring to its key as shown below.
1. py_cv_dict["year"] = 2020
2. py_cv_dict
Output:
{'name': 'Python', 'purpose': 'Computer Vision', 'year':
2020}
A for loop can be used to go through a dictionary; it
returns keys of the dictionary.
1. for k in py_cv_dict:
2. print(k)
Output:
name
purpose
year
The values can be returned as well.
1. for k in py_cv_dict:
2. print(py_cv_dict[k])
Output:
Python
Computer Vision
2020
The same output is obtained when we use the
following.
1. for k in py_cv_dict.values():
2. print(k)
To access both keys and values together, we use the
method items() as follows.
1. for x, y in py_cv_dict.items():
2. print(x, y)
Output:
name Python
purpose Computer Vision
year 2020
To check if a key exists within a dictionary, we employ
a conditional if statement.
1. if "year" in py_cv_dict:
2. print("'year' is one of the valid keys")
Output:
'year' is one of the valid keys
To add a new element to a dictionary, a new key is
used and a value is assigned to this key as given
below.
1. py_cv_dict["pages"] = 300
2. print(py_cv_dict)
Output:
{'name': 'Python', 'purpose': 'Computer Vision', 'year':
2020, 'pages': 300}
To remove a specific element, the method pop() can
be used.
1. py_cv_dict.pop("year") # del py_cv_dict["year"]
does the same job.
2. print(py_cv_dict)
Output:
{'name': 'Python', 'purpose': 'Data science', 'pages':
300}
The keyword del removes the whole dictionary when
we use del py_cv_dict. The method clear() deletes all
elements of a dictionary.
1. py_cv_dict.clear()
2. py_cv_dict
Output:
{ }
The method len(dictionay_name) is used to print the
number of key:value pairs present in the dictionary.
1. py_cv_dict = {
2. "name": "Python",
3. "purpose": "Computer Vision",
4. "year": 2021
5. }
6. print(len(py_cv_dict))
Output:
3
A dictionary cannot be copied by a simple assignment
such as py_cv_dict2 = py_cv_dict. It is because
py_cv_dict2 is just a reference to the original dictionary
py_cv_dict. Whatever changes are made to
py_cv_dict, same are automatically made to
py_cv_dict2 as well. To copy the elements of a
dictionary, we use the method copy() as follows.
1. py_cv_dict2 = py_cv_dict.copy()
2. print(py_cv_dict)
3. print(py_cv_dict2)
Output:
{'name': 'Python', 'purpose': 'Computer Vision', 'year':
2021}
{'name': 'Python', 'purpose': ' Computer Vision',
'year': 2021}
Further Reading
A detailed tutorial on Python is given in
https://docs.python.org/3/tutorial/
https://www.w3schools.com/python/default.asp