"Before we learn about control structures, let's learn a bit about the Jupyter Notebook data programming environment that we'll be using throughout this course. Jupyter Notebooks allow you to write formatted text descriptions (**Markdown cells**) alongside runnable Python code (**Code cells**). The text you're reading now is an example of a Markdown cell. You can double-click this text to edit it. Feel free to edit the contents of any cells that we give you: your changes only apply to your own copy.\n",
"\n",
"JupyterHub has a built-in debugger that enables you to pause the program on any line of code and inspect its state. **But**, we are not going to use it because it's an overkill for this course (and even in actual work sometimes).\n",
"> *“The most effective debugging tool is still careful thought, coupled with judiciously placed print statements.” — Brian Kernighan, “Unix for Beginners” (1979)*\n",
"\n",
" \n",
"\n",
"Python code cells, like the one that appears below, can be run by clicking on the cell and then using the ▶️ play button at the top to run it. The keyboard shortcut **Ctrl + Enter** allows you to run the current cell, which comes in handy if you make some edits to a cell and your fingers are already on your keyboard.\n",
"\n",
"Try editing the following cell to replace Yuxuan with your own name and then run it using the keyboard shortcut."
...
...
@@ -30,21 +35,10 @@
},
{
"cell_type": "code",
"execution_count": 1,
"execution_count": null,
"id": "abe596fb-ddc1-4955-ac58-43282c4dd720",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'Hello, my name is Yuxuan'"
]
},
"execution_count": 1,
"metadata": {},
"output_type": "execute_result"
}
],
"outputs": [],
"source": [
"\"Hello, my name is Yuxuan\""
]
...
...
@@ -59,23 +53,12 @@
},
{
"cell_type": "code",
"execution_count": 2,
"execution_count": null,
"id": "0aea4f4e-aac5-4c6a-8712-36e5f0198608",
"metadata": {
"tags": []
},
"outputs": [
{
"data": {
"text/plain": [
"'My favorite course is CSE 163'"
]
},
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
}
],
"outputs": [],
"source": [
"\"Hello, my name is Yuxuan\"\n",
"\"My favorite course is CSE 163\""
...
...
@@ -133,14 +116,12 @@
"source": [
"## Assignment statements\n",
"\n",
"Variables store values. Each Python value is composed of a value and its type. Unlike Java, Python doesn't require you to define the type of a variable. Variables are assigned using **assignment statements**.\n",
"\n",
"JupyterHub has a built-in debugger that enables you to pause the program on any line of code and inspect its state. Let's try it out now by clicking the **Enable Debugger** 🐞 (beetle or bug) icon at the top and then setting a **breakpoint** by clicking on the line number that you want to pause before running."
"Variables store values. Each Python value is composed of a value and its type. Unlike Java, Python doesn't require you to define the type of a variable. Variables are assigned using **assignment statements**."
]
},
{
"cell_type": "code",
"execution_count": 3,
"execution_count": null,
"id": "aacb2b81-8ce8-405a-8859-96aaf7b1e2ed",
"metadata": {},
"outputs": [],
...
...
@@ -161,21 +142,10 @@
},
{
"cell_type": "code",
"execution_count": 4,
"execution_count": null,
"id": "f968cc24-a2d4-4da4-8d38-fdf27ca74201",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"5"
]
},
"execution_count": 4,
"metadata": {},
"output_type": "execute_result"
}
],
"outputs": [],
"source": [
"y"
]
...
...
@@ -192,21 +162,10 @@
},
{
"cell_type": "code",
"execution_count": 5,
"execution_count": null,
"id": "a9fcebca-eaff-488b-ad7f-eda6d092079d",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"True\n",
"False\n",
"False\n",
"True\n"
]
}
],
"outputs": [],
"source": [
"x = 3\n",
"print(x < 4) # Is x less than 4?\n",
...
...
@@ -225,18 +184,10 @@
},
{
"cell_type": "code",
"execution_count": 6,
"execution_count": null,
"id": "7d1349af-ba5c-412d-8539-0136c4a51a8e",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"True\n"
]
}
],
"outputs": [],
"source": [
"x = 2.4\n",
"y = 1.2\n",
...
...
@@ -268,20 +219,12 @@
},
{
"cell_type": "code",
"execution_count": 7,
"execution_count": null,
"id": "8080a8e3-3179-4aed-a1a8-6ee877907bbd",
"metadata": {
"tags": []
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"x-squared is less than y\n"
]
}
],
"outputs": [],
"source": [
"if x ** 2 < y:\n",
" print(\"x-squared is less than y\")\n",
...
...
@@ -312,13 +255,13 @@
"Done!\n",
"```\n",
"\n",
"We can certainly write this out using a lot of print statements, but perhaps we can write a more general solution using loops instead. Lets practice converting this code into a loop."
"We can certainly write this out using a lot of print statements."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "2b7b4b2e-234a-44ff-8eab-277261ba4119",
"id": "003ed3a5-675c-4837-b1f6-b613680e3b5d",
"metadata": {
"tags": []
},
...
...
@@ -335,14 +278,77 @@
"print(\"Done!\")"
]
},
{
"cell_type": "markdown",
"id": "4753f70a-716a-4f37-a382-02fe0a2adf4e",
"metadata": {},
"source": [
"But perhaps we can write a more general solution using loops instead. Let's practice converting this code into a `for` loop."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "9727e6c9",
"id": "0d2a4557-c9ca-4b3d-b696-80d9c1f88663",
"metadata": {},
"outputs": [],
"source": [
"# Let's convert the above cell into a loop!\n"
"# Let's write it as a function that takes in n (integer) and counts down to 0 by 10 seconds decrement.\n",
"# remember to document every function you write! using triple quotes ''' for docstrings.\n",
In this lesson, we will introduce fundamental control structures (`if` statements, `for` loops, and `while` loops) for Python. By the end of this lesson, students will be able to:
1. Explain the difference between the output of running a cell and printed output.
1. Evaluate expressions involving arithmetic and boolean operators.
1. Apply for loops to iterate over a range of numbers increasing/decreasing by a fixed step size.
Before we learn about control structures, let's learn a bit about the Jupyter Notebook data programming environment that we'll be using throughout this course. Jupyter Notebooks allow you to write formatted text descriptions (**Markdown cells**) alongside runnable Python code (**Code cells**). The text you're reading now is an example of a Markdown cell. You can double-click this text to edit it. Feel free to edit the contents of any cells that we give you: your changes only apply to your own copy.
JupyterHub has a built-in debugger that enables you to pause the program on any line of code and inspect its state. **But**, we are not going to use it because it's an overkill for this course (and even in actual work sometimes).
> *“The most effective debugging tool is still careful thought, coupled with judiciously placed print statements.” — Brian Kernighan, “Unix for Beginners” (1979)*
Python code cells, like the one that appears below, can be run by clicking on the cell and then using the ▶️ play button at the top to run it. The keyboard shortcut **Ctrl + Enter** allows you to run the current cell, which comes in handy if you make some edits to a cell and your fingers are already on your keyboard.
Try editing the following cell to replace Yuxuan with your own name and then run it using the keyboard shortcut.
When running this code cell, notice how Jupyter Notebook produces an **output**. Usually, **the output is the value of the last expression that was run**. (There are some fancy ways to override the output but we won't learn how to do this.)
How can I have Python display both of the lines of text? To do this, we will need to `print` out lines of text. The `print` function has the side-effect of outputting the arguments as text.
Variables store values. Each Python value is composed of a value and its type. Unlike Java, Python doesn't require you to define the type of a variable. Variables are assigned using **assignment statements**.
JupyterHub has a built-in debugger that enables you to pause the program on any line of code and inspect its state. Let's try it out now by clicking the **Enable Debugger** 🐞 (beetle or bug) icon at the top and then setting a **breakpoint** by clicking on the line number that you want to pause before running.
Assignment statements don't produce values, so there's no output displayed. If you want to display an output, ask for the value of a variable. This expression evaluates to the current value stored in the variable `y`.
Let's try putting together everything you've seen so far. **Before running the follow code cell**, predict the output that will appear. (`x ** 2` computes `x` raised to the second power.)
> The most effective way to learn all the key programming details is to predict the output of every code cell before running it. Then, you can compare your predicted output to the real output and use that to plan your next steps.
Many of our in-class coding polls will provide an opportunity to pause and predict, but you can actually apply this learning strategy in any class. Even in classes that don't involve coding, comparing what you predict to what actually happens next in a lecture is an effective way to think and stay engaged.
Comparison operators are frequently used together with conditional statements (`if` statements). Whereas Java uses curly braces `{` and `}` to indicate a block of code, Python relies primarily on indentation to indicate blocks of code.
Think about how you might write the following program so that it counts down from one minute decrementing by 10 seconds, producing the following predicted output.
```
One minute countdown
60
50
40
30
20
10
0
Done!
```
We can certainly write this out using a lot of print statements, but perhaps we can write a more general solution using loops instead. Lets practice converting this code into a loop.
We can certainly write this out using a lot of print statements.
A `while` loop has a condition and a body. Each iteration executes the indented code only if the condition is `True`, otherwise the loop ends.
%% Cell type:code id:e97977d8 tags:
``` python
x=1
whilex<100:
print(x)
x=x*2
print("After loop: x =",x)
```
%% Cell type:markdown id:bdebbea4 tags:
## Practice: Countdown with `while` loop
Use a `while` loop to write a function `countdown` that takes a starting whole number of seconds and counts down to 0 (inclusive) decrementing by 10 each time. If the starting number of seconds is less than 0, it should instead print "Start must be non-negative!"
Here are 4 example `countdown` calls (prefixed `>>>`) and followed by the corresponding printed output.