{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# 6 | INTRODUCTION TO PYTHON"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
" ## Introduction"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"This notebook starts with a brief overview of languages and coding environments, before introducing basic coding concepts in the Python languages, including code comments, simple arithmetic, and the control of program flow."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## A computer program\n",
"\n",
"A computer program is a sequence of written (typed) instructions that allows a computer to perform specified tasks.\n",
"\n",
"A computer program is written in one (or more) computer languages. Such languages can be classified in many ways. One such classification compares **compiled languages** to **interpreted languages**. In most languages, the instructions, called the **source code**, is written in human reaable form. This source code is then either **compiled** (translated) into computer instruction specific to a computer type or it is simply **interpreted**.\n",
"\n",
"In the case of interpreted languages, another program called an interpreter, interprets the language code for execution. Python and R are examples of interpreted languages and Julia is an example of a compiled language."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Python\n",
"\n",
"Python is a general-purpose programming language developed by Dutch computer scientist Guido van Rossum. He began work on Python in the late 1980's and published the first version in 1991.\n",
"\n",
"While Python can be used in many programming applications such as game development, app development, web development, and much more, it is arguable best known as the principal language for data analysis, data science, statistics, biostatistics, and machine learning.\n",
"\n",
"Python constantly ranks amongst the most used programming languages. The TIOBE Programming Community index is an indicator of the popularity of programming languages. The index is updated once a month."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Python is an interpreted language as defined above. Lines of code are individually translated to code that a computer can understand and then executed. Since speed is a major benefit of compiled languages, it bares mentioning that Python is slow to execute. Why then, is Python so popular?\n",
"\n",
"There is no doubt that the popularity of Python is rooted in its ease of use. It is remarkable easy to learn Python. The simple nature of the syntax means that it reads almost like English sentences. It is very easy to translate an idea into computer code using Python. The translation from idea to code is referred to as **computational thinking**. Computational thinking is a core skill in research today and applies to the use of any computer language."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Task: Read the [Wikipedia](https://en.wikipedia.org/wiki/Python_(programming_language)) page on the Python programming language. Follow some of the links in the first few paragraphs to learn more about technical computer language terms such as _high-level language_, _code readability_, the use of _significant indentation_, _dynamically-typed languages_, _garbage-collection_, _multiple programming paradigms_, _object-oriented programming_, and _functional programming_."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Coding environments\n",
"\n",
"Computer code is written in a coding environment. Coding environments range from the bare-bones REPL (read-evaluate-print-loop) terminal or command line interfaces, to rich development environments such as PyCharm, Visual Studio Code, and many more.\n",
"\n",
"These notes are created using a modern approach to computing, called a notebook. Many language include the ability to create notebooks. The Wolfram Language was the first langauge to make use of this and the language's creator, Stephen Wolfram, calls these **computational essays**. This document and all the documents that we will use in this class are Jupyter notebooks.\n",
"\n",
"1. __Jupyter notebooks__ started life as IPython notebooks. IPython is a particular _flavor_ of Python and stands for **interactive Python**. In interactive Python, we write a few lines of code called scripts and execute then one at a time. It is ideal for exploration, especially for data exploration.\n",
"\n",
"2. __Ipython notebooks__ were created for the Python language. Today we use this notebook environment for other languages such as Julia and R, hence the name change to Jupyter notebooks.\n",
"\n",
"3. Jupyter notebooks are being replaced by __Jupyter Lab__. Jupyter Lab is a more comprehensive environment that includes notebooks as a part of other useful coding tools. Jupyter notebooks or Jupyter Lab runs in a web browser. Many coding environments such as PyCharm, DataSpell, Visual Studio Code, and more can also generate Jupyter notebooks.\n",
"\n",
"As the term _notebook_ suggest, these computational essays allow us to write normal sentences and paragraphs, with styling such as headings and subheadings, the inclusion of images, sounds, videos (such as YouTube), files, and more.\n",
"\n",
"Code can also be included in a notebook. The code is written as short scripts and are executed immediately, with the result displayed underneath the code.\n",
"\n",
"Lines of code are written in Code cells. Text, images, and such are entered in Markdown cells. A Jupyter notebook consists of many cells. Either a Code cell or a Markdown cell can be created after or between any cells.\n",
"\n",
"Below is a Code cell, with the result of the code displayed following the cell."
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [
{
"data": {
"application/vnd.plotly.v1+json": {
"config": {
"plotlyServerURL": "https://plot.ly"
},
"data": [
{
"hovertemplate": "%{hovertext}
Treatment group=Treatment
Age=%{x}
Diastolic BP=%{y}",
"hovertext": [
"Treatment",
"Treatment",
"Treatment",
"Treatment",
"Treatment",
"Treatment",
"Treatment",
"Treatment",
"Treatment",
"Treatment",
"Treatment",
"Treatment",
"Treatment",
"Treatment",
"Treatment",
"Treatment",
"Treatment",
"Treatment",
"Treatment",
"Treatment",
"Treatment",
"Treatment",
"Treatment",
"Treatment",
"Treatment",
"Treatment",
"Treatment",
"Treatment",
"Treatment",
"Treatment",
"Treatment",
"Treatment",
"Treatment",
"Treatment",
"Treatment",
"Treatment",
"Treatment",
"Treatment",
"Treatment",
"Treatment",
"Treatment",
"Treatment",
"Treatment",
"Treatment",
"Treatment",
"Treatment",
"Treatment",
"Treatment",
"Treatment",
"Treatment",
"Treatment",
"Treatment"
],
"legendgroup": "Treatment",
"marker": {
"color": "#F8766D",
"line": {
"color": "DarkSlateGrey",
"width": 2
},
"opacity": 0.8,
"size": 12,
"symbol": "circle"
},
"mode": "markers",
"name": "Treatment",
"orientation": "v",
"showlegend": true,
"type": "scatter",
"x": [
50,
34,
52,
50,
49,
43,
32,
49,
38,
39,
43,
50,
52,
46,
49,
22,
41,
43,
45,
51,
49,
32,
50,
42,
57,
41,
45,
31,
38,
52,
44,
32,
45,
39,
47,
53,
35,
43,
51,
46,
31,
52,
66,
72,
52,
38,
47,
59,
55,
50,
50,
50
],
"xaxis": "x",
"y": [
90,
78,
85,
88,
85,
79,
87,
77,
70,
84,
84,
79,
82,
81,
85,
72,
87,
75,
67,
73,
86,
81,
88,
78,
78,
79,
73,
82,
78,
77,
77,
79,
84,
65,
85,
77,
64,
81,
86,
66,
63,
84,
86,
88,
84,
74,
87,
85,
84,
87,
76,
81
],
"yaxis": "y"
},
{
"hovertemplate": "%{hovertext}
Treatment group=Placebo
Age=%{x}
Diastolic BP=%{y}",
"hovertext": [
"Placebo",
"Placebo",
"Placebo",
"Placebo",
"Placebo",
"Placebo",
"Placebo",
"Placebo",
"Placebo",
"Placebo",
"Placebo",
"Placebo",
"Placebo",
"Placebo",
"Placebo",
"Placebo",
"Placebo",
"Placebo",
"Placebo",
"Placebo",
"Placebo",
"Placebo",
"Placebo",
"Placebo",
"Placebo",
"Placebo",
"Placebo",
"Placebo",
"Placebo",
"Placebo",
"Placebo",
"Placebo",
"Placebo",
"Placebo",
"Placebo",
"Placebo",
"Placebo",
"Placebo",
"Placebo",
"Placebo",
"Placebo",
"Placebo",
"Placebo",
"Placebo",
"Placebo",
"Placebo",
"Placebo",
"Placebo"
],
"legendgroup": "Placebo",
"marker": {
"color": "#A3A500",
"line": {
"color": "DarkSlateGrey",
"width": 2
},
"opacity": 0.8,
"size": 12,
"symbol": "circle"
},
"mode": "markers",
"name": "Placebo",
"orientation": "v",
"showlegend": true,
"type": "scatter",
"x": [
67,
54,
45,
62,
54,
58,
63,
44,
67,
49,
56,
51,
53,
60,
48,
56,
54,
50,
47,
76,
71,
48,
55,
62,
57,
67,
61,
43,
46,
43,
66,
63,
57,
73,
72,
51,
50,
63,
62,
46,
50,
67,
63,
60,
71,
41,
60,
64
],
"xaxis": "x",
"y": [
108,
93,
91,
115,
96,
94,
100,
94,
99,
91,
111,
100,
100,
100,
92,
111,
97,
109,
102,
98,
107,
94,
95,
96,
100,
92,
125,
91,
103,
92,
105,
98,
94,
116,
107,
91,
94,
92,
98,
94,
99,
104,
105,
108,
109,
94,
94,
91
],
"yaxis": "y"
}
],
"layout": {
"legend": {
"title": {
"text": "Treatment group"
},
"tracegroupgap": 0
},
"template": {
"data": {
"bar": [
{
"error_x": {
"color": "rgb(51,51,51)"
},
"error_y": {
"color": "rgb(51,51,51)"
},
"marker": {
"line": {
"color": "rgb(237,237,237)",
"width": 0.5
},
"pattern": {
"fillmode": "overlay",
"size": 10,
"solidity": 0.2
}
},
"type": "bar"
}
],
"barpolar": [
{
"marker": {
"line": {
"color": "rgb(237,237,237)",
"width": 0.5
},
"pattern": {
"fillmode": "overlay",
"size": 10,
"solidity": 0.2
}
},
"type": "barpolar"
}
],
"carpet": [
{
"aaxis": {
"endlinecolor": "rgb(51,51,51)",
"gridcolor": "white",
"linecolor": "white",
"minorgridcolor": "white",
"startlinecolor": "rgb(51,51,51)"
},
"baxis": {
"endlinecolor": "rgb(51,51,51)",
"gridcolor": "white",
"linecolor": "white",
"minorgridcolor": "white",
"startlinecolor": "rgb(51,51,51)"
},
"type": "carpet"
}
],
"choropleth": [
{
"colorbar": {
"outlinewidth": 0,
"tickcolor": "rgb(237,237,237)",
"ticklen": 6,
"ticks": "inside"
},
"type": "choropleth"
}
],
"contour": [
{
"colorbar": {
"outlinewidth": 0,
"tickcolor": "rgb(237,237,237)",
"ticklen": 6,
"ticks": "inside"
},
"colorscale": [
[
0,
"rgb(20,44,66)"
],
[
1,
"rgb(90,179,244)"
]
],
"type": "contour"
}
],
"contourcarpet": [
{
"colorbar": {
"outlinewidth": 0,
"tickcolor": "rgb(237,237,237)",
"ticklen": 6,
"ticks": "inside"
},
"type": "contourcarpet"
}
],
"heatmap": [
{
"colorbar": {
"outlinewidth": 0,
"tickcolor": "rgb(237,237,237)",
"ticklen": 6,
"ticks": "inside"
},
"colorscale": [
[
0,
"rgb(20,44,66)"
],
[
1,
"rgb(90,179,244)"
]
],
"type": "heatmap"
}
],
"heatmapgl": [
{
"colorbar": {
"outlinewidth": 0,
"tickcolor": "rgb(237,237,237)",
"ticklen": 6,
"ticks": "inside"
},
"colorscale": [
[
0,
"rgb(20,44,66)"
],
[
1,
"rgb(90,179,244)"
]
],
"type": "heatmapgl"
}
],
"histogram": [
{
"marker": {
"pattern": {
"fillmode": "overlay",
"size": 10,
"solidity": 0.2
}
},
"type": "histogram"
}
],
"histogram2d": [
{
"colorbar": {
"outlinewidth": 0,
"tickcolor": "rgb(237,237,237)",
"ticklen": 6,
"ticks": "inside"
},
"colorscale": [
[
0,
"rgb(20,44,66)"
],
[
1,
"rgb(90,179,244)"
]
],
"type": "histogram2d"
}
],
"histogram2dcontour": [
{
"colorbar": {
"outlinewidth": 0,
"tickcolor": "rgb(237,237,237)",
"ticklen": 6,
"ticks": "inside"
},
"colorscale": [
[
0,
"rgb(20,44,66)"
],
[
1,
"rgb(90,179,244)"
]
],
"type": "histogram2dcontour"
}
],
"mesh3d": [
{
"colorbar": {
"outlinewidth": 0,
"tickcolor": "rgb(237,237,237)",
"ticklen": 6,
"ticks": "inside"
},
"type": "mesh3d"
}
],
"parcoords": [
{
"line": {
"colorbar": {
"outlinewidth": 0,
"tickcolor": "rgb(237,237,237)",
"ticklen": 6,
"ticks": "inside"
}
},
"type": "parcoords"
}
],
"pie": [
{
"automargin": true,
"type": "pie"
}
],
"scatter": [
{
"fillpattern": {
"fillmode": "overlay",
"size": 10,
"solidity": 0.2
},
"type": "scatter"
}
],
"scatter3d": [
{
"line": {
"colorbar": {
"outlinewidth": 0,
"tickcolor": "rgb(237,237,237)",
"ticklen": 6,
"ticks": "inside"
}
},
"marker": {
"colorbar": {
"outlinewidth": 0,
"tickcolor": "rgb(237,237,237)",
"ticklen": 6,
"ticks": "inside"
}
},
"type": "scatter3d"
}
],
"scattercarpet": [
{
"marker": {
"colorbar": {
"outlinewidth": 0,
"tickcolor": "rgb(237,237,237)",
"ticklen": 6,
"ticks": "inside"
}
},
"type": "scattercarpet"
}
],
"scattergeo": [
{
"marker": {
"colorbar": {
"outlinewidth": 0,
"tickcolor": "rgb(237,237,237)",
"ticklen": 6,
"ticks": "inside"
}
},
"type": "scattergeo"
}
],
"scattergl": [
{
"marker": {
"colorbar": {
"outlinewidth": 0,
"tickcolor": "rgb(237,237,237)",
"ticklen": 6,
"ticks": "inside"
}
},
"type": "scattergl"
}
],
"scattermapbox": [
{
"marker": {
"colorbar": {
"outlinewidth": 0,
"tickcolor": "rgb(237,237,237)",
"ticklen": 6,
"ticks": "inside"
}
},
"type": "scattermapbox"
}
],
"scatterpolar": [
{
"marker": {
"colorbar": {
"outlinewidth": 0,
"tickcolor": "rgb(237,237,237)",
"ticklen": 6,
"ticks": "inside"
}
},
"type": "scatterpolar"
}
],
"scatterpolargl": [
{
"marker": {
"colorbar": {
"outlinewidth": 0,
"tickcolor": "rgb(237,237,237)",
"ticklen": 6,
"ticks": "inside"
}
},
"type": "scatterpolargl"
}
],
"scatterternary": [
{
"marker": {
"colorbar": {
"outlinewidth": 0,
"tickcolor": "rgb(237,237,237)",
"ticklen": 6,
"ticks": "inside"
}
},
"type": "scatterternary"
}
],
"surface": [
{
"colorbar": {
"outlinewidth": 0,
"tickcolor": "rgb(237,237,237)",
"ticklen": 6,
"ticks": "inside"
},
"colorscale": [
[
0,
"rgb(20,44,66)"
],
[
1,
"rgb(90,179,244)"
]
],
"type": "surface"
}
],
"table": [
{
"cells": {
"fill": {
"color": "rgb(237,237,237)"
},
"line": {
"color": "white"
}
},
"header": {
"fill": {
"color": "rgb(217,217,217)"
},
"line": {
"color": "white"
}
},
"type": "table"
}
]
},
"layout": {
"annotationdefaults": {
"arrowhead": 0,
"arrowwidth": 1
},
"autotypenumbers": "strict",
"coloraxis": {
"colorbar": {
"outlinewidth": 0,
"tickcolor": "rgb(237,237,237)",
"ticklen": 6,
"ticks": "inside"
}
},
"colorscale": {
"sequential": [
[
0,
"rgb(20,44,66)"
],
[
1,
"rgb(90,179,244)"
]
],
"sequentialminus": [
[
0,
"rgb(20,44,66)"
],
[
1,
"rgb(90,179,244)"
]
]
},
"colorway": [
"#F8766D",
"#A3A500",
"#00BF7D",
"#00B0F6",
"#E76BF3"
],
"font": {
"color": "rgb(51,51,51)"
},
"geo": {
"bgcolor": "white",
"lakecolor": "white",
"landcolor": "rgb(237,237,237)",
"showlakes": true,
"showland": true,
"subunitcolor": "white"
},
"hoverlabel": {
"align": "left"
},
"hovermode": "closest",
"paper_bgcolor": "white",
"plot_bgcolor": "rgb(237,237,237)",
"polar": {
"angularaxis": {
"gridcolor": "white",
"linecolor": "white",
"showgrid": true,
"tickcolor": "rgb(51,51,51)",
"ticks": "outside"
},
"bgcolor": "rgb(237,237,237)",
"radialaxis": {
"gridcolor": "white",
"linecolor": "white",
"showgrid": true,
"tickcolor": "rgb(51,51,51)",
"ticks": "outside"
}
},
"scene": {
"xaxis": {
"backgroundcolor": "rgb(237,237,237)",
"gridcolor": "white",
"gridwidth": 2,
"linecolor": "white",
"showbackground": true,
"showgrid": true,
"tickcolor": "rgb(51,51,51)",
"ticks": "outside",
"zerolinecolor": "white"
},
"yaxis": {
"backgroundcolor": "rgb(237,237,237)",
"gridcolor": "white",
"gridwidth": 2,
"linecolor": "white",
"showbackground": true,
"showgrid": true,
"tickcolor": "rgb(51,51,51)",
"ticks": "outside",
"zerolinecolor": "white"
},
"zaxis": {
"backgroundcolor": "rgb(237,237,237)",
"gridcolor": "white",
"gridwidth": 2,
"linecolor": "white",
"showbackground": true,
"showgrid": true,
"tickcolor": "rgb(51,51,51)",
"ticks": "outside",
"zerolinecolor": "white"
}
},
"shapedefaults": {
"fillcolor": "black",
"line": {
"width": 0
},
"opacity": 0.3
},
"ternary": {
"aaxis": {
"gridcolor": "white",
"linecolor": "white",
"showgrid": true,
"tickcolor": "rgb(51,51,51)",
"ticks": "outside"
},
"baxis": {
"gridcolor": "white",
"linecolor": "white",
"showgrid": true,
"tickcolor": "rgb(51,51,51)",
"ticks": "outside"
},
"bgcolor": "rgb(237,237,237)",
"caxis": {
"gridcolor": "white",
"linecolor": "white",
"showgrid": true,
"tickcolor": "rgb(51,51,51)",
"ticks": "outside"
}
},
"xaxis": {
"automargin": true,
"gridcolor": "white",
"linecolor": "white",
"showgrid": true,
"tickcolor": "rgb(51,51,51)",
"ticks": "outside",
"title": {
"standoff": 15
},
"zerolinecolor": "white"
},
"yaxis": {
"automargin": true,
"gridcolor": "white",
"linecolor": "white",
"showgrid": true,
"tickcolor": "rgb(51,51,51)",
"ticks": "outside",
"title": {
"standoff": 15
},
"zerolinecolor": "white"
}
}
},
"title": {
"text": "Diastolic blood pressure as a function of age"
},
"xaxis": {
"anchor": "y",
"domain": [
0,
1
],
"title": {
"text": "Age"
}
},
"yaxis": {
"anchor": "x",
"domain": [
0,
1
],
"title": {
"text": "Diastolic BP"
}
}
}
}
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"import numpy\n",
"import pandas\n",
"from plotly import express\n",
"from plotly import io\n",
"\n",
"io.templates.default = 'ggplot2'\n",
"\n",
"age = numpy.round(\n",
" numpy.random.normal(\n",
" loc=50,\n",
" scale=10,\n",
" size=100\n",
" ),\n",
" decimals=0\n",
")\n",
"\n",
"dbp = numpy.round(\n",
" (0.8 * age) + numpy.random.normal(\n",
" loc=50,\n",
" scale=10,\n",
" size=100\n",
" ),\n",
" decimals=0\n",
")\n",
"\n",
"df = pandas.DataFrame(\n",
" {'Age':age,\n",
" 'Diastolic BP':dbp,\n",
" 'Treatment group':numpy.where(dbp>90, 'Placebo', 'Treatment')}\n",
")\n",
"\n",
"express.scatter(\n",
" df,\n",
" x='Age',\n",
" y='Diastolic BP',\n",
" color='Treatment group',\n",
" hover_name='Treatment group',\n",
" title='Diastolic blood pressure as a function of age'\n",
").update_traces(\n",
" marker=dict(\n",
" size=12,\n",
" opacity=0.8,\n",
" line=dict(\n",
" width=2,\n",
" color='DarkSlateGrey'\n",
" )\n",
" ),\n",
" selector=dict(\n",
" mode='markers'\n",
" )\n",
")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Python 101"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Code comments"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"In most cases, we write code to review it later or to share it with others. In both cases, it makes sense to leave comments about the code. This will remind you what your code is doing when you review it later and help others understand what you tried to achieve.\n",
"\n",
"When we write lines of code, we can prepend any line (or part of a line) uing the pound or hashtag symbol, `#`. The Python interpreter will ignore everyting in a line following the `#` symbol. It is therefor ideal to use when leaving comments on our code.\n",
"\n",
"In most of the code cells below, you wil notice the use of code comments."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
" ### Arithmetic operators"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We are all familiar with the basic arithmetical operators such as addition and multiplication. The simple use of mathematical operations in Python are examples of __expressions__. The actual symbols such as `+` and `-` are termed __operators__. The table below shows a list of these operators.\n",
"\n",
"| Expression | Operator | Example | Result |\n",
"|-----------------|----------|------------|-----------|\n",
"| Adding | `+` | `2 + 2` | `4` |\n",
"| Subtracting | `-` | `8 - 3` | `5` |\n",
"| Multiplying | `*` | `2 * 2` | `4` |\n",
"| Dividing | `/` | `8 / 4` | `2` |\n",
"| Integer devision| `//` | `10 // 3` | `3` |\n",
"| The remainder | `%` | `10 % 3` | `1` |\n",
"| Exponentiation | `**` | `2 ** 4` | `8` |"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Addition"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Adding $2 + 2$, which should result in $4$. Holding down the SHFT key and then hitting ENTER (Windows and Linux) or RETURN (Mac) excutes a cell. There is also a button above each cell in many coding environments that can be clicked."
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"4"
]
},
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Add 2 and 2\n",
"2 + 2"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Note the use of spaces between the $2$ and the $+$ symbol. This is simply for ease of reading. The spaces can be omitted, writing `2+2`. Note also the use of a code comment. A code comment is started by a pound symbol (or hashtag). Python ignores any script following a pound symbol (for a specific line of code).\n",
"\n",
"More than two numbers can be added in a single expression. Below, $2$ and $2$ and $10$ are added."
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"14"
]
},
"execution_count": 3,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Add 2 and 2 and 10\n",
"2 + 2 + 10"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Subtraction"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"One number is subtracted from another using the `-` operator."
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"7"
]
},
"execution_count": 5,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Subtract 3 from 10\n",
"10 - 3"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"More than one number can be used in a subtraction expression."
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"5"
]
},
"execution_count": 6,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Subtract 2 and 3 from 10\n",
"10 - 2 - 3"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Multiplication"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Since keyboards do not have a multiplication key, the `*` symbol is used for this operation. It is ususally a part of the `8` key."
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"6"
]
},
"execution_count": 7,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Multiply 2 by 3\n",
"2 * 3"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"More than two numbers can be multiplied."
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"60"
]
},
"execution_count": 8,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Multiply 2 and 10 and 3\n",
"2 * 10 * 3"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Division"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"As with multiplication, a special key is used since there is no $\\div$ key on a standard keyboard. The forward slash key, `/` is used for division."
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"5.0"
]
},
"execution_count": 9,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Divided 10 by 2\n",
"10 / 2"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Note the use of the integers $10$ and $2$ above. The result, though, is $5.0$, decimal value, known in Python as a floating point value. The result of a division is always a floating point value."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The result of dividing $20$ by $8$ results in a value with a decimal point. The `//` operator can be used to return only the whole number (integer) part of the solution."
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"2"
]
},
"execution_count": 10,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Use integer division to divide 20 by 8\n",
"20 // 8"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The result is $2$, the whole number part of the solution, with $2 \\times 8 + 4 = 20$. The remainder operator, `%` can be used to return the remainder of a division."
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"4"
]
},
"execution_count": 11,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Return the remainder of 20 divided by 8\n",
"20 % 8"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Powers"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Note that $2^{3} = 2 \\times 2 \\times 2 = 8$. The `**` operator is used to raise a number to a power."
]
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"8"
]
},
"execution_count": 12,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Raise 2 to the power of 3\n",
"2 ** 3"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Order of arithmetical operations"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"There is an order to mathematical operations, i.e. division and multiplication comes before subtraction and addition. In the expression $3 + 4 \\times 2$, the $4$ and $2$ and multiplied first resulting in $8$. The $2$ is then added to yield $11$."
]
},
{
"cell_type": "code",
"execution_count": 13,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"11"
]
},
"execution_count": 13,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Add 3 and 4 and multiply by 2\n",
"3 + 4 * 2"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Parentheses can be used to change the order of operations. In the expression $(3 + 4) \\times 2$, the $3$ and $4$ are added first, resulting in $7$. The $7$ is then multiplied by $2$ to yield $14$."
]
},
{
"cell_type": "code",
"execution_count": 14,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"14"
]
},
"execution_count": 14,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# First add 3 and 4, then multiply by 2\n",
"(3 + 4) * 2"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Task: Calculate a solution to the expression below.\n",
"\n",
"$$\\frac{\\left(6 + 4 \\right) \\times 2}{10}$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Comparison operators"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Comparison operators or __conditionals__ are used to return the value of a comparison. The return is one of two Boolean values: `True` or `False` based on the comparison being made."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The two __Boolean__ values are `True` and `False`. The data type of these are printed below using the `type` function. See below under Python data types for more information on the `type` function and data types in Python."
]
},
{
"cell_type": "code",
"execution_count": 15,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"bool"
]
},
"execution_count": 15,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Data type of True\n",
"type(True)"
]
},
{
"cell_type": "code",
"execution_count": 16,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"bool"
]
},
"execution_count": 16,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Data type of False\n",
"type(False)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The Python data type of `True` and `False` are both `bool`. Internally, `True` is stored as the integer $1$ and `False` as the integer $0$. Arithmetic can be done with the values."
]
},
{
"cell_type": "code",
"execution_count": 17,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"2"
]
},
"execution_count": 17,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Add True and True\n",
"True + True"
]
},
{
"cell_type": "code",
"execution_count": 18,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"1"
]
},
"execution_count": 18,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Add True and False\n",
"True + False"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The Python comparison operators are listed in the table below."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"| Comparison | Operator | True example | False Example |\n",
"|----------------------------|----------|--------------|---------------|\n",
"| Less than | < | 2 < 4 | 4 < 2 |\n",
"| Greater than | > | 4 > 2 | 2 > 4 |\n",
"| Less than or equal to | <= | 4 <= 4 | 2 <= 4 |\n",
"| Greater than or equal to | >= | 4 >= 4 | 2 >= 4 |\n",
"| Is equal to | == | 4 == 4.0 | 4 == 2 |\n",
"| Is not equal to | != | 4 != 2 | 4 != 4 |"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"These comparison operators are used in conditional statements. The conditional statements are used to control the flow of a program. The conditional statements are discussed below."
]
},
{
"cell_type": "code",
"execution_count": 20,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"True"
]
},
"execution_count": 20,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Is 2 less than 3?\n",
"2 < 3"
]
},
{
"cell_type": "code",
"execution_count": 21,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"False"
]
},
"execution_count": 21,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Is 2 greater than 3?\n",
"2 > 3"
]
},
{
"cell_type": "code",
"execution_count": 23,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"True"
]
},
"execution_count": 23,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Is 7 less than or equal to 7?\n",
"7 <= 7"
]
},
{
"cell_type": "code",
"execution_count": 24,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"True"
]
},
"execution_count": 24,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Is 7 greater than or equal to 7?\n",
"7 >= 7"
]
},
{
"cell_type": "code",
"execution_count": 25,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"True"
]
},
"execution_count": 25,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Is 3 equal to 3?\n",
"3 == 3"
]
},
{
"cell_type": "code",
"execution_count": 26,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"False"
]
},
"execution_count": 26,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Is 3 not equal to 3?\n",
"3 != 3"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Functions"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Python functions are keywords in Python that have rules of use. The rules are called the **syntax** of the function. The syntax of a function is the rules that govern the use of the function. The `type` function that was used before is an example of a Python function. The syntax of the `type` function is `type(object)`. The `type` function takes a single argument, the object whose type is to be returned. The `type` function returns the data type of the object."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Python function will be covered later in these notes."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Python data types"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Much of content that is used in data science in Python are of a certain computer data type. This type sets the rules for what can be done with the data. For example, a number can be added to another number, but a number cannot be added to text."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The `type` function comes in handy again. Below, are code examples of Python data types."
]
},
{
"cell_type": "code",
"execution_count": 27,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"int"
]
},
"execution_count": 27,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Type of 3\n",
"type(3)"
]
},
{
"cell_type": "code",
"execution_count": 28,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"float"
]
},
"execution_count": 28,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Type of 3.0\n",
"type(3.0)"
]
},
{
"cell_type": "code",
"execution_count": 29,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"complex"
]
},
"execution_count": 29,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Type of 3.0 + 1j\n",
"type(3.0 + 1j)"
]
},
{
"cell_type": "code",
"execution_count": 30,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"str"
]
},
"execution_count": 30,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Type of \"Health Data Science\"\n",
"type(\"Health Data Science\")"
]
},
{
"cell_type": "code",
"execution_count": 31,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"str"
]
},
"execution_count": 31,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Type of '8'\n",
"type('8')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The reason that a function has a type is that (almost) everything in Python is an object. To *function* properly, each object must have a type."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**Casting** or **coercion** converts an object from one type to another. Some casting is allowed in Python. The string `'8'` is coerced to an integer using the `int` function."
]
},
{
"cell_type": "code",
"execution_count": 32,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"8"
]
},
"execution_count": 32,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Convert the string '8' to an integer\n",
"int('8')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The string `'8'` can now be used in an arithmetic expression. The `float` function is demonstrated below in the same way as the `int` function. It coerces the string `'8'` to a floating point number $8.0$."
]
},
{
"cell_type": "code",
"execution_count": 33,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"11.0"
]
},
"execution_count": 33,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Convert the string '8' to a float and add it to 3.0\n",
"float('8') + 3.0"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Variables"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**Computer variables**, or variables for short, are the containers for objects. Objects can be assigned to a variable. This action creates a space in computer memory in which the information about the object, including its type and value, are stored. At least while the Python program or file is active."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"A _human-created name_ is used as a variable name. These should be descriptive of what is contained in (or assigned to) the variable, such that when a file is viewed later, or shared with others, everyone can deduce what is contained in the variable."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Task: There are rules for naming a variable. These are included in a style-guide for writing Python code. The guides are listed in Python Enhancement Guide 8 (PEP 8), available at or go directly to the Naming Convention section at . Read the Naming Convention section of PEP 8."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"An object is assigned to a variable by using the assignment operator, which is the symbol `=`."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"In the code cell below, a variable named `my_variable` is created and a string object is assigned to it. The string object contains the value `I like Python`."
]
},
{
"cell_type": "code",
"execution_count": 34,
"metadata": {},
"outputs": [],
"source": [
"# Create a string object 'I like Python' and assign to the the variable my_variable\n",
"my_variable = 'I like Python'"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"_Calling the variable name_ by simply typing the variable name in a code cell, will return the value of the object assigned to the variable."
]
},
{
"cell_type": "code",
"execution_count": 35,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'I like Python'"
]
},
"execution_count": 35,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Call the variable my_variable\n",
"my_variable"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Note that in a scripting environment such a notebooks, the `print` function,i.e. `print(my_variable)`, is not required to print the object in a variable to the screen."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The assignment operator is not used in the same way as it is used in mathematics. The assignment operator simply assigns what is to its right, to what is to its left. The variable name is on the left and the object is on the right."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Below, the computer variable `i` is created and the value $1$ is assigned to it. The variable is then called."
]
},
{
"cell_type": "code",
"execution_count": 36,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"1"
]
},
"execution_count": 36,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Assign the value 1 to the variable i\n",
"i = 1\n",
"\n",
"# Call the variable i\n",
"i"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now, $1$ is added to the object contained in the variable `i`. The right-hand side is evaluated and the result is reassigned to the variable `i`. This means that the object assigned to a variable can be _over-written_. It is clear that the assignment operator is not used as an equal symbol."
]
},
{
"cell_type": "code",
"execution_count": 37,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"2"
]
},
"execution_count": 37,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Add 1 to i and assign the result to i\n",
"i = i + 1\n",
"\n",
"# Call the variable i\n",
"i"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"On the right-hand side of the assignment operator is `i + 1`. When the code is excuted, `i` contains the value $1$. When $1$, is added to `i` the result is $2$. This is then assigned to the variable that is on the left-hand side of the assignment operator. On the left is a variable that already contains an object. Python allows the content of a variable to be over-written. The variable `i` therefor then contains the integer object with a value of $2$."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Task: Create code such that `x = 5` and `y = x`. Then let `x = 7`. Determine the value of `y`."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Control flow"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The flow (or order of execution) of code can be controlled. This is done using conditional statements. To start with, though, consider the `range` function. The function is convenient for generating sequences. With a single-value integer argument, it generates a list starting at $0$ and increments with a step size of $1$ until the specified value, minus $1$, is reached (the specified value is not included). The function returns a range object that can be used for iteration (over its elements)."
]
},
{
"cell_type": "code",
"execution_count": 38,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"range(0, 10)"
]
},
"execution_count": 38,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Use the range function to create a list of integers from 0 to 9\n",
"range(10)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The `list` function prints the actual values."
]
},
{
"cell_type": "code",
"execution_count": 43,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]"
]
},
"execution_count": 43,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Use the list function to print the list of integers from 0 to 9\n",
"list(range(10))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"A `for` loop can be used to _loop over_ the $10$ values. In each case the current value is printed using the `print` function."
]
},
{
"cell_type": "code",
"execution_count": 39,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"0\n",
"1\n",
"2\n",
"3\n",
"4\n",
"5\n",
"6\n",
"7\n",
"8\n",
"9\n"
]
}
],
"source": [
"# Create a for loop to print the integers from 0 to 9\n",
"for i in range(10):\n",
" print(i)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"A starting value other than $0$ can be specified. In the example below, the `range` function is used to generate a sequence starting at $1$ and ending at $10$ (not including $10$)."
]
},
{
"cell_type": "code",
"execution_count": 40,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"range(1, 10)"
]
},
"execution_count": 40,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Use the range function to create a list of integers from 1 to 9\n",
"range(1, 10)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The step-size can be controlled using a third argument."
]
},
{
"cell_type": "code",
"execution_count": 44,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[1, 3, 5, 7, 9]"
]
},
"execution_count": 44,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Use the range function to create a list of integers from 1 to 9 in steps of 2 and then print the list of values\n",
"list(range(1, 10, 2))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Task: Generate a for loop that prints the square of each integer from $0$ to $5$ to the screen. Remember to use the `**` symbols for calculating a power, and remember that the last value is not included."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"A loop over code can also be achieved while a condition is met. A `while` loop will continue until a condition is met, or more precisely, the loop terminates when the condition returns a `False` value."
]
},
{
"cell_type": "code",
"execution_count": 45,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"0\n",
"1\n",
"2\n",
"3\n",
"4\n",
"5\n",
"6\n",
"7\n",
"8\n",
"9\n"
]
}
],
"source": [
"# Generate a variable i that takes the value 0\n",
"i = 0\n",
"\n",
"# Create a while loop that prints the integers from 0 to 9\n",
"while i < 10: # Check if i is less than 10 (if it is, execute the code below, if not, exit the loop)\n",
" print(i) # Print the current value of i\n",
" i = i + 1 # Increment the current value of i by 1"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Task: Initialize the variable `i` by assigning it the value $0$. This overwrites the current value stored in `i` as used above. Print the square of each $1$-unit increment in `i`, while `i` remains less than $10$."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The `if`, `elif`, and `else` statements allow for branching of the execution of code. Depending on the set conditions, different code can be executed."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"In the code cell below, a variable named `variable` is created, and assigned the integer value $10$ to it."
]
},
{
"cell_type": "code",
"execution_count": 17,
"metadata": {},
"outputs": [],
"source": [
"# Create a variable named variable as assign to integer 10 to it\n",
"variable = 10"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"As an example of using an `if` statement, consider if the integer value in `variable` is larger than $5$. If it is, print the statement `The value is larger than 5` to the screen. If the integer value in `variable` is less than or equal to $5$, print `The value is not larger than 5` to the screen."
]
},
{
"cell_type": "code",
"execution_count": 15,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"The value is not larger than 5.\n"
]
}
],
"source": [
"# Create an if-else expression to print 'The value is larger than 5' if the value of variable is larger than 5 and 'The value not larger than 5' if the value of variable is 5 or smaller\n",
"if variable > 5:\n",
" print('The value is larger than 5.')\n",
"else:\n",
" print('The value is not larger than 5.')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The keyword `if` is used and then a condition is stated, followed by a colon symbol, `:`. The new line is indented and contains the code for execution if the condition in the `if` statement holds (returns a `True` value). A new line uses the `else` keyword (in vertical allignment with the `if` keyword). The `else` keyword is also followed by a colon and then a new indented line containing a final statement to be executed if the prior condition was not met."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"An `elif` (short for _else if_) statement can also be added. As an example, print `The value is exactly 5` if such a condition holds. The `elif` statememt (in vertical alignment with the `if` statement) is followed by a new conditional, a colon, and then a new indented line."
]
},
{
"cell_type": "code",
"execution_count": 48,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"The value is larger than 5\n"
]
}
],
"source": [
"# Add an elif statement to the if-else expression above to print 'The value is equal to 5' if the value of variable is 5\n",
"if variable > 5:\n",
" print('The value is larger than 5.')\n",
"elif variable == 5:\n",
" print('The value is equal to 5.')\n",
"else:\n",
" print('The value is not larger than 5.')"
]
},
{
"cell_type": "code",
"execution_count": 49,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"The value is equal to 5\n"
]
}
],
"source": [
"# Change the value assigned to variable to 5\n",
"variable = 5\n",
"\n",
"# Rerun the if-else expression above\n",
"if variable > 5:\n",
" print('The value is larger than 5.')\n",
"elif variable == 5:\n",
" print('The value is equal to 5.')\n",
"else:\n",
" print('The value is not larger than 5.')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"It is a good idea think through the problem before creating an `if` statement."
]
},
{
"cell_type": "code",
"execution_count": 18,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"1 1\n",
"1 2\n",
"1 3\n",
"2 1\n",
"2 2\n",
"2 3\n",
"3 1\n",
"3 2\n",
"3 3\n",
"4 1\n",
"4 2\n",
"4 3\n",
"5 1\n",
"5 2\n",
"5 3\n"
]
}
],
"source": [
"for i in [1, 2, 3, 4, 5]:\n",
" for j in [1, 2, 3]:\n",
" print(i, j)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Quiz questions"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Questions"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"1. Use Python to calculate solutions to the following expressions."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\begin{align*}\n",
"&3 \\times 8 \\\\ \\\\ \n",
"&\\frac{33 + 7}{5}\n",
"\\end{align*}\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"2. Determine the data type of the output of the code `1+2.` and `1+2`. Explain why the data types are different."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"3. Generate a loop that prints $n^{2}$ for each of the numbers $n = \\{ 1,2,3,4,5 \\}$."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"4. Create the variable `i` by assigning the value $1$ to it. Create a loop that prints the value of $i^{2}$ to the screen. Increment the value of `i` by $1$ until the value of $i^{2}$ exceeds $1000$. Print the value assigned to `i` after the loop has completed. Explain why the solution is `i=32`, where $32^{2}$ is larger than $1000$."
]
}
],
"metadata": {
"kernelspec": {
"display_name": "datascience",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.12.1"
},
"orig_nbformat": 4
},
"nbformat": 4,
"nbformat_minor": 2
}