Skip to content
Snippets Groups Projects
Commit 6a608f90 authored by Yuxuan Mei's avatar Yuxuan Mei
Browse files

update first lecture notebook

parent 22399e6b
No related branches found
No related tags found
No related merge requests found
......@@ -158,3 +158,6 @@ cython_debug/
# and can be added to the global gitignore or merged into this file. For a more nuclear
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
#.idea/
# vscode
*.code-workspace
\ No newline at end of file
%% Cell type:markdown id:5f97f018-ade9-46ee-9de8-47dcbf58faca tags:
# Control Structures
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.
%% Cell type:markdown id:d12566b5-1c01-4919-ba5f-aa90e24a7183 tags:
## Jupyter Notebooks
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.
%% Cell type:code id:abe596fb-ddc1-4955-ac58-43282c4dd720 tags:
``` python
"Hello, my name is Yuxuan"
```
%% Output
'Hello, my name is Yuxuan'
%% Cell type:markdown id:e57de738-0843-4a97-a791-857e9be68175 tags:
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.)
%% Cell type:code id:0aea4f4e-aac5-4c6a-8712-36e5f0198608 tags:
``` python
"Hello, my name is Yuxuan"
"My favorite course is CSE 163"
```
%% Output
'My favorite course is CSE 163'
%% Cell type:markdown id:447380ec-08c6-4b0e-8cde-ecb0bd977052 tags:
## Print function
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.
%% Cell type:code id:5e7d2beb-873f-4c72-ba62-a70c8ae487f8 tags:
``` python
print("Hello, my name is Yuxuan")
print("My favorite course is CSE 163")
```
%% Cell type:markdown id:484535dc-2a7f-48e7-9293-dcdc721ace4e tags:
This helps us display more than one line of text in a cell, but take a closer look and you'll notice more subtle details happening behind the scenes.
Before we introduced `print`, the cell produced as the last line of output
```
'My favorite course is CSE 163'
```
After we introduced `print`, the cell produced as the last line of output
```
My favorite course is CSE 163
```
What is different between these two outputs? Try to explain the cause for the difference.
%% Cell type:markdown id:b6271f55-3911-48fa-9fbf-75a5dd4abfa9 tags:
## Assignment statements
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.
%% Cell type:code id:aacb2b81-8ce8-405a-8859-96aaf7b1e2ed tags:
``` python
x = 2.4
y = 1.2
x = x / y
y = 5
```
%% Cell type:markdown id:10030e38-e665-40a8-8ce5-37b7193649cb tags:
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`.
%% Cell type:code id:f968cc24-a2d4-4da4-8d38-fdf27ca74201 tags:
``` python
y
```
%% Output
5
%% Cell type:markdown id:fd74c9e1-c543-46e9-ba0b-9a881dec1a15 tags:
## Comparison operators
In addition to the string and numeric values that we see above, Python also has comparison operators that produce boolean (`True` or `False`) values.
%% Cell type:code id:a9fcebca-eaff-488b-ad7f-eda6d092079d tags:
``` python
x = 3
print(x < 4) # Is x less than 4?
print(x >= 5) # Is x greater than or equal to 5?
print(x == 2) # Is x equal to 2?
print(x != 2) # Is x not equal to 2?
```
%% Output
True
False
False
True
%% Cell type:markdown id:e886114d-6026-40e6-925a-4855c6a08edc tags:
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.)
%% Cell type:code id:7d1349af-ba5c-412d-8539-0136c4a51a8e tags:
``` python
x = 2.4
y = 1.2
x = x / y
y = 5
print(x ** 2 <= y)
```
%% Output
True
%% Cell type:markdown id:9ef135ce-93a4-4883-b54b-e6ede2e93bc8 tags:
> 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.
%% Cell type:markdown id:f6eeccd1-c2d7-4e22-97dc-5be64ddc07ff tags:
## Conditional statements
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.
%% Cell type:code id:8080a8e3-3179-4aed-a1a8-6ee877907bbd tags:
``` python
if x ** 2 < y:
print("x-squared is less than y")
elif x ** 2 == y:
print("x-squared is equal to y")
else:
print("x-squared is greater than y")
```
%% Output
x-squared is less than y
%% Cell type:markdown id:fe6bad8e-2352-425a-997f-40e7d455b8ab tags:
## Loops
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.
%% Cell type:code id:2b7b4b2e-234a-44ff-8eab-277261ba4119 tags:
%% Cell type:code id:003ed3a5-675c-4837-b1f6-b613680e3b5d tags:
``` python
print("One minute countdown")
print(60)
print(50)
print(40)
print(30)
print(20)
print(10)
print(0)
print("Done!")
```
%% Cell type:code id:9727e6c9 tags:
%% Cell type:markdown id:4753f70a-716a-4f37-a382-02fe0a2adf4e tags:
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 id:0d2a4557-c9ca-4b3d-b696-80d9c1f88663 tags:
``` python
# Let's convert the above cell into a loop!
# Let's write it as a function that takes in n (integer) and counts down to 0 by 10 seconds decrement.
# remember to document every function you write! using triple quotes ''' for docstrings.
def countdown(n):
"""
your docstring here
"""
pass # your code here
```
%% Cell type:markdown id:2a5cc692-25a9-4ca9-b286-a19a57cc1bbe tags:
Let's try some different test cases.
%% Cell type:code id:cbf9f76e-0eb4-4a3d-9051-528b48c7a90b tags:
``` python
countdown(60)
```
%% Cell type:code id:732786a0-100e-4b25-b9b4-6431d3527ab6 tags:
``` python
countdown(9)
```
%% Cell type:code id:a865bbd7-1338-40d5-b1c9-9ba9ebdc373c tags:
``` python
countdown(0.5)
```
%% Cell type:code id:6d57f8c5-d803-4a2e-82f2-1359e0ddafe3 tags:
``` python
countdown(-1)
```
%% Cell type:markdown id:a590c502 tags:
## While loops
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
while x < 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.
```
>>> countdown(60)
60 second countdown
60
50
40
30
20
10
0
Done!
```
```
>>> countdown(15)
15 second countdown
15
5
Done!
```
```
>>> countdown(-4)
Start must be non-negative!
```
```
>>> countdown(0)
0 second countdown
0
Done!
```
%% Cell type:code id:9480634a tags:
%% Cell type:code id:0151cc77-a6b6-4566-b1f9-56e754b65c41 tags:
``` python
def countdown(n):
"""
your docstring here
"""
pass # your code here
```
%% Cell type:code id:45343154-fcb3-45ba-9971-330e613f3718 tags:
``` python
countdown(60)
```
%% Cell type:code id:351a86df-fd50-4a50-9e4d-08f395418524 tags:
``` python
countdown(15)
```
%% Cell type:code id:8b035334-dc5e-434c-8e9a-86fdb27c0bef tags:
``` python
countdown(-4)
```
%% Cell type:code id:a28180d4-72bc-4a8e-905d-37fc6f86fde4 tags:
``` python
countdown(0)
```
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment