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:
- Explain the difference between the output of running a cell and printed output.
- Evaluate expressions involving arithmetic and boolean operators.
- Apply for loops to iterate over a range of numbers increasing/decreasing by a fixed step size.
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 and then use the keyboard shortcut Ctrl + Enter to apply your changes, or you can press the play button in the top toolbar to "run" the cell.
In addition to editing cells, you can also make new cells, even in the assessments—so long as your final submission is organized and readable. Making new cells is a great way to explore code ideas and test out different ways of expressing your programs.
Try editing the following code cell to replace Kevin with your own name and then run it using the keyboard shortcut Ctrl + Enter. When running a code cell, Python will evaluate the last-run expression.
"Hello, my name is Kevin"
'Hello, my name is Kevin'
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.)
"Hello, my name is Kevin"
"My favorite course is CSE 163" # What does this line of code do?
'My favorite course is CSE 163'
"My favorite course is CSE" + " 163" + " A" # What does this line of code do?
# Return value (value of expression)
'My favorite course is CSE 163 A'
"163"
'163'
163
163
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.
print("Hello, my name is Kevin")
print("My favorite course is CSE 163") # Return value of print function is None
# Side effect of the print function is to display the given arguments
Hello, my name is Kevin My favorite course is CSE 163
print("My favorite course is CSE" + " 163" + " A")
My favorite course is CSE 163 A
print("My favorite course is CSE", "163", "A")
My favorite course is CSE 163 A
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? What could explain the difference?
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.
x = 2.4
y = 1.2
x = x / y
y = 5
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
.
y # What is the value of y?
5
x
2.0
2.4 / 2
1.2
2.4 // 2
1.0
int(2.4 // 2)
1
1
1
If we restart the kernel and then ask for the value of x
, what do you think will appear?
x
--------------------------------------------------------------------------- NameError Traceback (most recent call last) Cell In[1], line 1 ----> 1 x NameError: name 'x' is not defined
x = print("My name is Kevin") # Returns None
x
My name is Kevin
print(x)
None
x + " Lin"
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[5], line 1 ----> 1 x + " Lin" TypeError: unsupported operand type(s) for +: 'NoneType' and 'str'
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.
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?
True False False True
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.)
x = 2.4
y = 1.2
x = x / y
y = 5
print(x ** 2 <= y) # Is X^2 less than or equal to y?
True
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.
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.
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")
x-squared is less than y
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.
print("One minute countdown")
print(60)
print(50)
print(40)
print(30)
print(20)
print(10)
print(0)
print("Done!")
print("One minute countdown")
seconds = 60
while seconds >= 0:
print(seconds)
seconds -= 10
print("Done!")
One minute countdown 60 50 40 30 20 10 0 Done!
seconds
-10