Lab 12 Manual
Lab 12 Manual
Muhammad Umar
Javed
University of Wah
Lab 12 Manual
Applications of Information and Communication
Technologies
1|P age
Lab12| Dr. Muhammad Umar
Javed
Table of Contents
Task List.............................................................................................................................................
Task-1 Introduction 3
Task-2 Installing Python 3
Task-3 A Python script 3
Task-4 Jupyter Notebook 4
Task-5 Write Python code in Jupyter notebook 5
Task-6 Run Python code in Jupyter notebook 8
Task-7 Write and render markdown text in a Jupyter notebook 12
Task-8 The Python REPL 16
Task-9 Compute mathematical calculations using the Python REPL 19
Task-10 Define variables and assignment operator = 23
Task-11 Data types and variables 28
Task-12 Use Python’s type() function to determine an object’s data type 28
Task-13 Index and slice strings, lists, and tuples 32
2|P age
Lab12| Dr. Muhammad Umar
Javed
Week-13
3|P age
Lab12| Dr. Muhammad Umar
Javed
formatting, and images. Jupyter notebooks contain three types of cells: code cells, output cells, and
markdown cells.
Professional Developer-friendly
PyCharm
Python IDE
A Jupyter notebook is neither a simple text editor nor a full-featured IDE. Jupyter notebooks provide a
quick and streamlined way for problem-solvers to prototype code and quickly share code.
Jupyter notebooks also provide a way for problem-solvers to share programming solutions with
team members, supervisors, and customers.
4|P age
Lab12| Dr. Muhammad Umar
Javed
In a way, Jupyter Notebook strike a balance between simple text editors, which are fast to start and
simple and easy to manipulate, and IDE's which tend to start slower and be feature-rich and complex.
Simple text editors typically can only edit code, and cannot run the code. A full IDE can edit code, run the
code, debug code, provide syntax highlighting and context help.
In the context of problem-solving, Jupyter notebooks are quite handy. Jupyter notebooks open quickly and
quickly produce output. Data exploration, data cleaning, and plot building are accomplished in Jupyter
notebooks easier and quicker than in a text editor or an IDE.
In the context of sharing solutions to problems, Jupyter notebooks are also useful. Markdown cells
render text in different sizes, bold and italic. Tables and images, plots and code can all be shown together
in the same Jupyter notebook. Notebooks can be exported to a variety of formats including .html and .pdf.
Installing Juypter
The simplest way to install Jupyter notebooks is to download and install the Anaconda distribution of
Python. The Anaconda distribution of Python comes with Jupyter notebook included and no further
installation steps are necessary.
Below are additional methods to install Jupyter notebooks if you are not using the Anaconda distribution
of Python.
5|P age
Lab12| Dr. Muhammad Umar
Javed
Installing Jupyter on Windows using the Anaconda Prompt
To install Jupyter on Windows, open the Anaconda Prompt and type:
> conda install jupyter
Type y for yes when prompted. Once Jupyter is installed, type the command below into the Anaconda
Prompt to open the Jupyter notebook file browser and start using Jupyter notebooks.
> jupyter notebook
Open the Windows start menu and select [Anaconda3(64 bit)] --> [Jupyter Notebook]
6|P age
Lab12| Dr. Muhammad Umar
Javed
This action opens the Jupyter file browser in a web browser tab.
In the upper right select [New] --> [Python 3]
7|P age
Lab12| Dr. Muhammad Umar
Javed
A new notebook will open as a new tab in your web browser.
Try typing the code below in the first cell in the notebook to the right of the In [ ]:
prompt: import this
Then click the run button in the middle of the menu at the top of the notebook.
8|P age
Lab12| Dr. Muhammad Umar
Javed
If you don't see the Anaconda Prompt in the Windows Start Menu, then you need to install the Anaconda
distribution of Python. Download Anaconda at the following link: Anaconda.com/distribution The
Anaconda Prompt window should look something like the image below.
9|P age
Lab12| Dr. Muhammad Umar
Javed
In the upper right select [New] --> [Python 3]. You will see a new tab open in your web browser. This
web browser page is a Jupyter notebook.
10 | P a g e
Lab12| Dr. Muhammad Umar
Javed
An Anaconda Navigator window will open. In the middle of the page, in the Jupyter notebook tile,
click [Launch]
11 | P a g e
Lab12| Dr. Muhammad Umar
Javed
In the upper right select [New] --> [Python 3]
12 | P a g e
Lab12| Dr. Muhammad Umar
Javed
and change the name of the notebook. Note that the file extension .ipynb is not printed in the file name
field, but if you look in the Home tab, you will see that the notebook is saved with the .ipynb extension.
Menus and Buttons
A Jupyter notebook is comprised of a bunch of cells which are arrayed one after another in boxes below
the menu items and buttons. There are three main types of cells: code cells, output cells, and markdown
cells.
Code Cells
In code cells, you can write Python code, then execute the Python code and see the resulting output.
An example of a code cell is shown below.
You can tell you are typing in a code cell because In [ ]: is shown to the left of the cell and the cell-type
drop-down menu shows Code.
To run the Python code in a code cell push the [Run] button or type [Shift]+[Enter]. Hitting [Enter] when the
cursor is inside a code cell brings the cursor down to a new line.
13 | P a g e
Lab12| Dr. Muhammad Umar
Javed
Output Cells
After a code cell is run, an output cell can be produced below the code cell. The output cell contains
the output from the code cell above it. Not all code produces output, so not all code cells produce output
cells. The results in output cells can't be edited. If a code cell produces plots, charts or images, these outputs
are shown in output cells.
You can clear all the output cells and re-run code cells by selecting [Kernal] --> [Restart Kernal and
Clear Output].
Markdown Cells
Markdown cells don't contain Python code. Markdown cells contain text written in Markdown format. Text
in markdown cells can be formatted to show bold or italic text. Tables, images, and lists can also be included
in markdown cells.
Markdown cells are used for documentation and explaining your code. The text in a markdown cell is not
executed. Markdown cells can be formatted with a few special characters. Markdown cells are run like code
cells. The difference is that when markdown cells are run, the text is formatted (when code cells run, code
is executed). Markdown cells are run by clicking the [Run] button or by pressing [Shift] + [Enter].
Text in markdown cells can be formatted using markdown syntax. An example of markdown syntax is
putting an underscore before and after a word to cause the word to be formatted in italics.
14 | P a g e
Lab12| Dr. Muhammad Umar
Javed
Headings
Headings are created in markdown cells using the hash symbol #. One # is the largest heading. Four hashes
#### is the smallest heading.
# H1 Heading
## H2 Heading
### H3 Heading
#### H4 Heading
Code Blocks
Code blocks can be inserted in Jupyter notebook markdown cells. For inline code blocks use the ` left quote
character, the character to the left of the number [1] and above [Tab] on most keyboards.
This is inline code: ` ` ` Inline code block ` ` ` within a paragraph
For a separated code block use three ` left quote characters on one line, followed by the code block on
separate lines. Terminate the separate code block with a line of three ` left quote characters.
```
Separated code block
```
The code in markdown cell code blocks do not execute when the markdown cell is run. A code block in a
markdown cell is formatted when the markdown cell executes.
Bold and Italics
Bold and italic font is displayed by surrounding text with a double asterisk for **bold** and a single
underscore for _italics_
**bold** produces bold
_italics_ produces italics
**_bold and italic_** produces bold and italic
Tables
Tables are displayed using the pipe | character, which is [Shift] + [\] on most keyboards. Columns are
separated by pipes | and rows are separated by lines. After the header row, a row of pipes and dashes --- are
needed to define the table.
| header1 | header 2 | header 3 |
| --- | --- | --- |
| col 1 | col 2 | col 3 |
| col 1 | col 2 | col 3 |
15 | P a g e
Lab12| Dr. Muhammad Umar
Javed
produces:
16 | P a g e
Lab12| Dr. Muhammad Umar
Javed
A horizontal rule is specified with three asterisks *** on a single line.
produces
***
Links
Hyperlinks are specified using a set of square brackets [ ] followed by a pair of parenthesis ( ) The text
inside the square brackets will be the link, the link address goes in the parenthesis.
[Python.org](https://python.org/)
produces
Python.org
Images
Images are embedded in Jupyter Notebook markdown using the exclamation point and square brackets ![
], followed by the image file path in parenthesis ( ). If the image can not be displayed, the text in square
brackets will be shown. The image can be in the same directory as the notebook, or a relative path can be
specified. In this case, the image engineering.png is stored in the images directory, which is a subdirectory
of the directory the notebook is saved in.

displays the image
LaTeX Math
LaTeX Math equations and symbols are rendered by markdown cells. A more extensive list of LaTeX
commands can be found in the appendix.
$$ \int_{a}^{b} \frac{1}{x^2} dx $$
html
Because Jupyter notebooks are rendered by web browsers, just about any HTML tag can be included in the
markdown portion of a notebook. An example of an HTML tag is the <sup> </sup> tags that surround
superscript text.
x<sup>2</sup>
produces
x2
Text can be colored using html <font> </font> tags
<font color=red>Red Text</font>
producess
<font color=red>Red Text</font>
Warning Boxes
17 | P a g e
Lab12| Dr. Muhammad Umar
Javed
bootstrap style warning boxes can be included in Jupyter notebook markdown using <div> tags <div
class="alert alert-danger" role="alert">
<strong>Warning!</strong> Python lists start at 0
</div>
produces
Warning! Python lists start at 0
Creating a new cell
You can create a new cell in a Jupyter Notebook by clicking the [+] button in the upper menu. Clicking the
[+] button produces a new code cell below the active cell.
You can also create a new cell using Insert --> Insert Cell Above or Insert Cell Below. You can choose
to insert a cell above or below the active cell.
Changing the cell type
The type of cell: code cell or markdown cell, is changed by clicking on a cell and selecting the cell type
from the drop-down menu. Typing [Esc] + [m] changes the cell type to a markdown cell. Typing [Esc] +
[y] changes the cell type to a code cell.
Saving a Jupyter Notebook
Jupyter notebooks can be saved using the save icon in the upper menu or by pressing [Ctrl] + [s].
Jupyter notebooks can also be saved as a copy, similar to the Save As command common in many programs.
To save a copy of a Jupyter notebook use File --> Make a Copy...
18 | P a g e
Lab12| Dr. Muhammad Umar
Javed
Python as a Calculator
Python can be used as a calculator to compute arithmetic operations like addition,
subtraction, multiplication and division. Python can also be used for trigonometric calculations and
statistical calculations.
Arithmetic
Python can be used as a calculator to make simple arithmetic calculations. Simple arithmetic calculations
can be completed at the Python Prompt, also called the Python REPL. REPL stands for Read Evaluate Print
Loop. The Python REPL shows three arrow symbols >>> followed by a blinking cursor. Programmers type
commands at the >>> prompt then hit [ENTER] to see the results.
Commands typed into the Python REPL are read by the interpreter, results of running the commands are
evaluated, tand hen printed to the command window. After the output is printed, the >>> prompt appears
on a new line. This process repeats over and over again in a continuous loop.
Try the following commands at the Python REPL:
Suppose the mass of a battery is 5 kg and the mass of the battery cables is 3 kg. What is the mass of the
battery cable assembly?
>>> 5 + 3
8
Suppose one of the cables above is removed and it has a mass of 1.5 kg. What is the mass of the leftover
assembly?
>>> 8 - 1.5
6.5
If the battery has a mass of 5000 g and a volume of 2500 What is the density of the battery? The formula
for density is below, where is density, is mass and is volume.
In the problem above and
Let's solve this with Python.
>>> 5000 / 2500
2.0
What is the total mass if we have 2 batteries, and each battery weighs 5 kg?
>>> 5 * 2
10
The length, width, and height of each battery is 3 cm. What is the area of the base of the battery? To
complete this problem, use the double asterisk symbol ** to raise a number to a power.
>>> 3 ** 2
19 | P a g e
Lab12| Dr. Muhammad Umar
Javed
9
What is the volume of the battery if each the length, width, and height of the battery are all 3 cm?
>>> 3 ** 3
27
Find the mass of the two batteries and two cables.
We can use Python to find the mass of the batteries and then use the answer, which Python saves as an
underscore _ to use in our next operation. (The underscore _ in Python is comparable to the ans variable
in MATLAB)
>>> 2 * 5
10
>>> _ + 1.5 + 1
12.5
Section Summary
A summary of the arithmetic operations in Python is below:
\\
+ addition 2+3 5
- subtraction 8-6 2
- negative number -4 -4
* multiplication 5*2 10
/ division 6/3 2
20 | P a g e
Lab12| Dr. Muhammad Umar
Javed
To use Python's trig functions, we need to introduce a new concept: importing modules. In Python, there
are many operations built into the language when the REPL starts. These include + , -, *, / like we saw in
the previous section. However, not all functions will work right away when Python starts. Say we want to
find the sine of an angle. Try the following: >>> sin(60)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'sin' is not defined
This error results because we have not told Python to include the sin function. The sin function is part of
the Python Standard Library. The Python Standard Library comes with every Python installation and
includes many functions, but not all of these functions are available to us when we start a new Python
REPL session. To use Python's sin function, first import the sin function from the math module which is
part of the Python Standard Library.
21 | P a g e
Lab12| Dr. Muhammad Umar
Javed
0.49999999999999994
>>> cos(pi/6)
0.8660254037844387
>>> tan(pi/6)
0.5773502691896257
Section Summary
22 | P a g e
Lab12| Dr. Muhammad Umar
Javed
>>> log(3.0*e**3.4) # note: natural log
4.4986122886681095
A right triangle has side lengths 3 and 4. What is the length of the hypotenuse? >>>
sqrt(3**2 + 4**2)
5.0
The power function pow() works like the ** operator. pow() raises a number to a power. >>> 5**2
25
>>> pow(5,2)
25.0
Statistics
To round out this section, we will look at a couple of statistics functions. These functions are part of the
Python Standard Library, but not part of the math module. To access Python's statistics functions, we need
to import them from the statistics module using the statement from statistics import mean, median, mode,
stdev. Then the functions mean, median, mode and stdev (standard deviation) can be used.
>>> from statistics import mean, median, mode, stdev
>>> test_scores = [60, 83, 83, 91, 100]
>>> mean(test_scores)
83.4
>>> median(test_scores)
83
>>> mode(test_scores)
83
>>> stdev(test_scores)
14.842506526863986
Alternatively, we can import the entire statistics module using the statement import statistics. Then to use
the functions, we need to use the names statistics.mean, statistics.median, statistics.mode, and
statistics.stdev. See below:
>>> import statistics
>>> test_scores = [60, 83, 83, 91, 100 ]
>>> statistics.mean(test_scores)
83.4
23 | P a g e
Lab12| Dr. Muhammad Umar
Javed
>>> statistics.median(test_scores)
83
>>> statistics.mode(test_scores)
83
>>> statistics.stdev(test_scores)
14.842506526863986
Section Summary
The following functions are part of Python's statistics module. These functions need to be imported from
the statistics module before they are used.
Variables
Variables are assigned in Python using the = equals sign also called the assignment operator. The
statement:
a=2
Assigns the integer 2 to the variable a.
>>> a = 2
>>> a
2
Note the assignment operator =(equals), is different from the logical comparison operator == (equivalent
to).
>>> a == 2
True
Variable names in Python must conform to the following rules:
• variable names must start with a letter
24 | P a g e
Lab12| Dr. Muhammad Umar
Javed
• variable names can only contain letters, numbers, and the underscore character _
• variable names can not contain spaces
• variable names can not include punctuation
• variable names are not enclosed in quotes or brackets
The following code lines show valid variable names:
constant = 4
new_variable = 'var'
my2rules = ['rule1','rule2']
SQUARES = 4
Problem
String Operations
25 | P a g e
Lab12| Dr. Muhammad Umar
Javed
Strings are sequences of letters, numbers, punctuation, and spaces. Strings are defined at the Python REPL
by enclosing letters, numbers, punctuation, and spaces in single quotes ' ' or double quotes " ".
>>> word = "Solution"
>>> another_word = "another solution"
>>> third_word = "3rd solution!"
In Python, string operations include concatenation (combining strings), logical comparisons (comparing
strings) and indexing (pulling specific characters out of strings). String Concatenation
Strings can be concatenated or combined using the + operator.
>>> word = "Solution"
>>> another_word = "another solution"
>>> third_word = "3rd solution!"
>>> all_words = word+another_word+third_word
>>> all_words
'Solutionanother solution3rd solution!'
To include spaces in the concatenated string, add a string which just contains one space " " in between
each string you combine.
>>> word = "Solution"
>>> another_word = "another solution"
>>> third_word = "3rd solution!"
>>> all_words = word + " " + another_word + " " + third_word >>> all_words
'Solution another solution 3rd solution!'
String Comparison
Strings can be compared using the comparison operator; the double equals sign ==. Note the comparison
operator (double equals ==) is not the same as the assignment operator, a single equals sign =.
>>> name1 = 'Gabby'
>>> name2 = 'Gabby'
>>> name1 == name2
True
>>> name1 = 'Gabby'
>>> name2 = 'Maelle'
>>> name1 == name2
False
26 | P a g e
Lab12| Dr. Muhammad Umar
Javed
Capital letters and lower case letters are different characters in Python. A string with the same letters, but
different capitalization are not equivalent.
>>> name1 = 'Maelle'
>>> name2 = 'maelle'
>>> name1 == name2
False
Print Statements
One built-in function in Python is print(). The value or expression inside of the parenthesis of a print()
function "prints" out to the REPL when the print() function is called. An example using the print()
function is below:
>>> name = "Gabby"
>>> print("Your name is: ")
Your name is:
>>> print(name)
Gabby
Remember that strings must be enclosed by quotation marks. The following command produces an
error.
>>> print(Gabby)
27 | P a g e
Lab12| Dr. Muhammad Umar
Javed
1+2
Summary
In this lab, you learned how to use the Python REPL, also called the Python prompt, to solve problems.
You learned how to do arithmetic, powers and logarithms, trigonometry and save values to variables.
Operations on strings were introduced including concatenation and comparison. In the last section of the
chapter, Python's print() function was introduced.
+ addition
- subtraction
* multiplication
/ division
** exponents
_ answer in memory
28 | P a g e
Lab12| Dr. Muhammad Umar
Javed
Trigonometry
pi
exp
29 | P a g e
Lab12| Dr. Muhammad Umar
Javed
Statistics
from statistics
import *
Integers
Integers are one of the Python data types. An integer is a whole number, negative, positive or zero.
In Python, integer variables are defined by assigning a whole number to a variable.
30 | P a g e
Lab12| Dr. Muhammad Umar
Javed
Python's type() function can be used to determine the data type of a variable.
>>> a = 5
>>> type(a)
<class 'int'>
The output <class 'int'> indicates the variable a is an integer. Integers can be negative or zero.
>>> b = -2
>>> type(b)
<class 'int'>
>>> z = 0
>>> type(z)
<class 'int'>
Floating Point Numbers
Floating point numbers or floats are another Python data type. Floats are decimals, positive, negative and
zero. Floats can also be represented by numbers in scientific notation which contain exponents. Both a
lower case e or an upper case E can be used to define floats in scientific notation. In Python, a float can be
defined using a decimal point . when a variable is assigned.
d = -0.03
type(d)
float
Na = 6.02e23
Na
6.02e+23
type(Na)
class 'float'
To define a variable as a float instead of an integer, even if the variable is assigned a whole number, a
trailing decimal point . is used. Note the difference when a decimal point . comes after a whole number:
g=5
type(g)
31 | P a g e
Lab12| Dr. Muhammad Umar
Javed
class 'int'
f = 5.o
type(f)
class float
Complex Numbers
Another useful numeric data type for problem solvers is the complex number data type. A complex
number is defined in Python using a real component + an imaginary component j. The letter j must be
used to denote the imaginary component. Using the letter i to define a complex number returns an error in
Python.
32 | P a g e
Lab12| Dr. Muhammad Umar
Javed
Boolean Data Type
The boolean data type is either True or False. In Python, boolean variables are defined by
the True and False keywords.
b = False
type(b)
class bool
The output <class 'bool'> indicates the variable is a boolean data type.
Note: the keywords True and False must have an Upper Case first letter. Using a lowercase true returns an
error.
>>> c = true
Traceback (most recent call last):
File "<input>", line 1, in <module>
NameError: name 'true' is not defined
>>> d = false
Traceback (most recent call last):
File "<input>", line 1, in <module>
NameError: name 'false' is not defined
Integers and Floats as Booleans
Integers and floating point numbers can be converted to the boolean data type using Python's bool()
function. An int, float or complex number set to zero returns False. An integer, float or complex number
set to any other number, positive or negative, returns True.
>>> zero_int = 0
>>> bool(zero_int)
False
>>> pos_int = 1
>>> bool(pos_int)
True
>>> neg_flt = -5.1
>>> bool(neg_flt)
True
33 | P a g e
Lab12| Dr. Muhammad Umar
Javed
Boolean Arithmetic
Boolean arithmetic is the arithmetic of true and false logic. A boolean or logical value can either
be True or False. Boolean values can be manipulated and combined with boolean operators.
Boolean operators in Python include and, or, and not.
The common boolean operators in Python are below:
• or
• and
• not
• == (equivalent)
• != (not equivalent)
In the code section below, two variables are assigned the boolean values True and False. Then
these boolean values are combined and manipulated with boolean operators.
>>> A = True
>>> B = False
>>> A or B
True
>>> A and B
False
>>> not A
False
>>> not B
True
>>> A == B
False
>>> A != B
True
Boolean operators such as and, or, and not can be combined with parenthesis to make compound boolean
expressions.
>>> C = False
>>> A or (C and B)
True
>>> (A and B) or C
False
34 | P a g e
Lab12| Dr. Muhammad Umar
Javed
A summary of boolean arithmetic and boolean operators is shown in the table below:
A B not A not B A == B A =! B A or B A and B
TFFTFTTF
FTTFFTTF
TTFFTFTT
FFTTTFFF
Strings
Another built-in Python data type is strings. Strings are sequences of letters, numbers, symbols, and
spaces. In Python, strings can be almost any length and can contain spaces. Strings are assigned in Python
using single quotation marks ' ' or double quotation marks " ". Python strings can contain blank spaces. A
blank space is a valid character in Python string.
>>> string = 'z'
>>>> type(string)
<class 'str'>
>>> string = 'Engineers'
>>> type(string)
<class 'str'>
The output <class 'str'> indicates the variable is a string.
Numbers as Strings
Numbers and decimals can be defined as strings too. If a decimal number is defined using quotes ' ', the
number is saved as a string rather than as a float. Integers defined using quotes become strings as well.
>>> num = '5.2'
>>> type(num)
<class 'str'>
>>> num = '2'
>>> type(num)
<class 'str'>
Strings as Boolean Values
Strings can be converted to boolean values (converted to True or False). The empty string "" returns as
False. All other strings convert to True.
>>> name = "Gabby"
>>> bool(name)
35 | P a g e
Lab12| Dr. Muhammad Umar
Javed
True
>>> empty = ""
>>> bool(empty)
False
Note that a string which contains just one space (" ") is not empty. It contains the space character.
Therefore a string made up of just one space converts to True.
>>> space = " "
>>> bool(space)
True
String Indexing
String indexing is the process of pulling out specific characters from a string in a particular order. In
Python, strings are indexed using square brackets [ ]. An important point to remember:
Python counting starts at 0 and ends at n-1.
Consider the word below.
Solution
The letter S is at index zero, the letter o is at index one. The last letter of the word Solution is n. n is in the
seventh index. Even though the word Solution has eight letters, the last letter is in the seventh index. This
is because Python indexing starts at 0 and ends at n-1.
>>> word = 'Solution'
>>> word[0]
'S'
>>> word[1]
'o'
>>> word[7]
'n'
If the eighth index of the word Solution is called, an error is returned.
>>> word[8]
IndexError: string index out of range
Negative Indexing
Placing a negative number inside of the square brackets pulls a character out of a string starting
from the end of the string.
>>> word[-1]
'n'
>>> word[-2]
36 | P a g e
Lab12| Dr. Muhammad Umar
Javed
'o'
String Slicing
String slicing is an operation to pull out a sequence of characters from a string. In Python, a colon on the
inside of the square brackets between two numbers in a slicing operation indicates through. If the index
[0:3] is called, the characters at positions 0 through 3 are returned. Remember Python counting starts at 0
and ends at n-1. So [0:3] indicates the first through third letters, which are indexes 0 to 2.
>>> word[0:3]
'Sol'
A colon by itself on the inside of square brackets indicates all.
>>> word[:]
'Solution'
When three numbers are separated by two colons inside of square brackets, the numbers represent start :
stop : step. Remember that Python counting starts at 0 and ends at n-1.
>>> word[0:7:2] #start:stop:step
'Slto'
When two colons are used inside of square brackets, and less than three numbers are specified, the
missing numbers are set to their "defaults". The default start is 0, the default stop is n-1, and the default
step is 1. The two code lines below produce the same output since 0 is the default start and 7 (n-1) is the
default stop. Both lines of code use a step of 2.
>>> word[0:7:2]
'Slto'
>>> word[::2]
'Slto'
The characters that make up a string can be reversed by using the default start and stop values and
specifying a step of -1.
>>> word[::-1]
'noituloS'
Lists
A list is a data structure in Python that can contain multiple elements of any of the other data type. A list
is defined with square brackets [ ] and commas , between elements.
>>> lst = [ 1, 2, 3 ]
>>> type(lst)
list
>>> lst = [ 1, 5.3, '3rd_Element']
37 | P a g e
Lab12| Dr. Muhammad Umar
Javed
>>> type(lst)
list
Indexing Lists
Individual elements of a list can be accessed or indexed using bracket [ ] notation. Note that
Python lists start with the index zero, not the index 1. For example:
>>> lst = ['statics', 'strengths', 'dynamics']
>>> lst[0]
'statics'
>>> lst[1]
'strengths'
>>> lst[2]
'dynamics'
Remember! Python lists start indexing at [0] not at [1]. To call the elements in a list with 3 values
use: lst[0], lst[1], lst[2].
Slicing Lists
Colons : are used inside the square brackets to denote all
>>> lst = [2, 4, 6]
>>> lst[:]
[2, 4, 6]
Negative numbers can be used as indexes to call the last number of elements in the list
>>> lst = [2, 4, 6]
>>> lst[-1]
6
The colon operator can also be used to denote all up to and thru end.
>>> lst = [2, 4, 6]
>>> lst[:2] # all up to 2
[2, 4]
>>> lst = [2, 4, 6]
>>> lst[2:] # 2 thru end
[6]
The colon operator can also be used to denote start : end + 1. Note that indexing here in not inclusive.
lst[1:3] returns the 2nd element, and 3rd element but not the fourth even though 3 is used in the index.
Remember! Python indexing is not inclusive. The last element called in an index will not be returned.
Dictionaries and Tuples
38 | P a g e
Lab12| Dr. Muhammad Umar
Javed
Besides lists, Python has two additional data structures that can store multiple objects. These data
structures are dictionaries and tuples. Tuples will be discussed first.
Tuples
Tuples are immutable lists. Elements of a list can be modified, but elements in a tuple can only be
accessed, not modified. The name tuple does not mean that only two values can be stored in this data
structure. Tuples are defined in Python by enclosing elements in parenthesis ( ) and separating elements
with commas. The command below creates a tuple containing the numbers 3, 4, and 5.
>>> t_var = (3,4,5)
>>> t_var
(3, 4, 5)
Note how the elements of a list can be modified:
>>> l_var = [3,4,5] # a list
>>> l_var[0]= 8
>>> l_var
[8, 4, 5]
The elements of a tuple can not be modified. If you try to assign a new value to one of the elements
in a tuple, an error is returned.
>>> t_var = (3,4,5) # a tuple
>>> t_var[0]= 8
>>> t_var
TypeError: 'tuple' object does not support item assignment
39 | P a g e
Lab12| Dr. Muhammad Umar
Javed
To create a tuple that just contains one numerical value, the number must be followed by a comma.
Without a comma, the variable is defined as a number.
>>> num = (5)
>>> type(num)
int
When a comma is included after the number, the variable is defined as a tuple.
>>> t_var = (5,)
>>> type(t_var)
Tuple
Dictionaries
Dictionaries are made up of key: value pairs. In Python, lists and tuples are organized and
accessed based on position. Dictionaries in Python are organized and accessed using keys and
values. The location of a pair of keys and values stored in a Python dictionary is irrelevant.
Dictionaries are defined in Python with curly braces { }. Commas separate the key-value pairs
that make up the dictionary. Each key-value pair is related by a colon :.
Let's store the ages of two people in a dictionary. The two people
are Gabby and Maelle. Gabby is 8 and Maelle is 5. Note the name Gabby is a string and the
age 8 is an integer.
>>> age_dict = {"Gabby": 8 , "Maelle": 5}
>>> type(age_dict)
Dict
40 | P a g e
Lab12| Dr. Muhammad Umar
Javed
The values stored in a dictionary are called and assigned using the following syntax:
dict_name[key] = value
>>> age_dict = {"Gabby": 8 , "Maelle": 5}
>>> age_dict["Gabby"]
8
We can add a new person to our age_dict with the following command:
>>> age_dict = {"Gabby": 8 , "Maelle": 5}
>>> age_dict["Peter"]= 40
>>> age_dict
41 | P a g e
Lab12| Dr. Muhammad Umar
Javed
Items can be removed from dictionaries by calling the .pop() method. The dictionary key (and that key's
associated value) supplied to the .pop() method is removed from the dictionary.
>>> age_dict = {"Gabby": 8 , "Maelle": 5}
>>> age_dict.pop("Gabby")
>>> age_dict
{'Maelle': 5}
Summary
In this lab, you learned about a couple of different data types built-in to Python. These data
types include the numeric data types: integers, floats, and complex numbers. The string data
42 | P a g e
Lab12| Dr. Muhammad Umar
Javed
type is composed of letters, numbers, spaces, and punctuation. Python also has container data
types which can store many values. These container data types include lists, tuples, and
dictionaries. Strings, lists and tuples can be indexed and sliced using square brackets [ ].
Summary of Python Functions and Commands
Built-in Data Types
Python Data Type Description
int Integer
float floating point number
bool boolean value: True or False
complex complex number, real and imaginary components str string, sequence of letters, numbers and
symbols
list list, formed with [ ]
dict dictionary, formed with {'key'=value}
tuple an immutable list, formed with ( )
Python Functions
Function Description
type() output a variable or object data type
len() return the length of a string, list dictionary or tuple
str() convert a float or int into a str (string)
int() convert a float or str into an int (integer)
float() convert an int or str into an float (floating point number)
Python List Operators
Operator Description Example Result
[ ] indexing lst[1] 4
: start lst[:2] [ 2, 4 ]
: end lst[2:] [ 6, 8 ]
: through lst[0:3] [ 2, 4, 6 ]
: start, step, end+1 lst[0:5:2] [2, 6]
43 | P a g e