The content for this lesson is adapted from material by Hunter Schafer and by Kevin Lin.
Objectives¶
In this lesson, we will introduce fundamental control structures for Python. By the end of this lesson, students will be able to:
- Evaluate expressions involving arithmetic and boolean operators.
- Apply
forloops to iterate over a range of numbers increasing/decreasing by a fixed step size. - Apply
whileloops to iterate until reaching a desired program condition.
Setting up¶
Refer to the instructions on our Software page for how to install Anaconda, VS Code, and the CSE 163 environment!
Note!
The linked page is an older version of the setup instructions that we have temporarily linked for the preliminary launch of the course website. The instructions will mostly work. However, note that you should install Python 3.13 instead of 3.9 and use the environment file here instead of the one that is on the page. All other steps and downloads can be followed as they appear on the software setup instructions.
To follow along with the code examples in this lesson, please download the files here:
In this class, we will use a combination of Jupyter notebooks and Python scripts for lessons and coding practice.
In a Jupyter notebook, you will find a combination of text-based Markdown cells and runnable Python snippets, which we call code cells. To edit a Markdown cell, double-click the text to edit it. Then, use the keyboard shortcut Ctrl + Enter to apply your changes. This is a great way to take notes on the course content, if you wish.
You may run individual code cells in a Jupyter notebook and see their output, or you may run all cells at once. In a Python script (i.e., any file that ends in the .py extension), you may see the output by running the script in VS Code.
Python Basics¶
Printing¶
Printing looks a bit different in Python than in other languages. To print any text, we will use the print function.
print("Hello, world!")
Try changing “world” to your name, or to the name of a friend!
One thing that Python is really good at is providing slightly different ways of using the same syntax to do helpful things. For example, you can also pass multiple values to the print function and it adds spaces between them!
print('Hello', 'world', '!')
Quotation Marks
It generally doesn’t matter whether you use single quotes ('') or double quotes ("") for print statements. However, if the string you’re trying to print uses one type of quotation mark, use the other to indicate the string itself! Example: 'Say "what?"' or "What's that?"
Main-method pattern¶
A Python program is a series of statements that are executed from top to bottom. We will learn lots of different statements in this course!
In CSE 163, we will ask you to put a little bit of starter code in every Python script you write. We call this the main-method pattern. We can’t really motivate why you need to use this quite yet; you’ll have to trust us that it is the right thing to do. We introduce this pattern now to get you in the practice of writing from the onset of your Python journey. We will come back in future weeks and actually dive into what this pattern does and why it’s necessary.
Recall that we could write a Python program in a code cell to print “Hello world” like the following:
print("Hello, world!")
Note that if you tried to run this in a Python script or a code cell of a Jupyter notebook, this will run either way. However, instead, we will commonly ask you to write a few extra lines of code “around” the program you wanted to write as the following.
def main():
# Put your code, indented inside here
print('Hello world!')
if __name__ == '__main__':
main()
(Note the comment in the second line, which is prefaced by a #!)
We’ll start you off by providing the main-method pattern as starter code for lessons and practice, but you will get used to writing these weird symbols by yourself! Again, we promise to explain this later, we just don’t have everything we need for that explanation right now!
Warning
For individual code snippets on the course website and in Jupyter notebooks, the main-method pattern will be omitted. It is not needed for the Jupyter notebook, and we omit it from lessons to keep things more readable. For any Python script that you write in this class, including for take-home assessments, you will always need to use the main-method pattern for these files.
Variables¶
Variables store values. Each Python value is composed of a value and its type. Unlike Java and older languages like C, Python doesn’t require you to define the type of a variable. A variable’s type is determined by the value it references. Additionally, throughout the lifetime of the program running, the variable can be made to hold a new value of a different type using an assignment statement.
The following snippet creates a variable named x that stores the value 3 of type int (for integer) and a variable named y that stores the value 4.2 of type float (for floating-point number). One line 3, it then re-assigned x to store the value 3.7 of type float. This is why the program prints x = 3.7 and y = 4.2.
x = 3
y = 4.2
x = 3.7
print('x =', x)
print('y =', y)
Info
In a Jupyter notebook, you can display the output by writing the variable name in a code cell and evaluating that code cell.
Expressions¶
Python supports many operations for built-in types. Specifically, here are the operations defined for numeric types like int and float.
- Addition:
a + b - Subtraction:
a - b - Multiplication:
a * b - Division:
a / b(e.g., 7 / 3 == 2.333333333) - Integer division:
a // b(e.g., 7 // 3 == 2) - Mod:
a % b(i.e., leftover from integer division as in 7 % 3 == 1) - Exponentiation:
a ** b(i.e., $a^b$)
You can also nest expressions (and use parentheses to define order) since all expressions evaluate to some value.
a = 3
print(a - (2 * a) + (a ** (1 + 2)))
What do you think is the output of this print statement?
Types and booleans¶
In addition to string and numeric types, Python also has a bool type (equivalent to Java’s boolean) that only takes on the values True or False.
Just like any other value, a bool can be stored in variables:
b1 = True
b2 = False
print(b1, b2)
They have operations:
a and b:Trueif and only if both values areTruea or b:Trueif either or both values areTruenot a: “flips” to the opposite boolean value
And they can be created by doing comparisons between other values. Just like how you can create a new numeric value from evaluating arithmetic operations, you can create a bool value by using logical operations.
x = 3
print(x < 4) # "Is x is 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?"
While loops¶
If you want to repeat some computation, a programming language usually provides a construct called a loop that lets you repeat code some number of times.
A while loop has a condition and a body. The while loop proceeds in iterations, each iteration executes the body only if the condition is True, otherwise the loop ends. In general, a while loop looks like:
while condition:
# Loop body
statement
statement
statement
Note the indentation and the colon at the end of the condition! Pythonic syntax is sensitive to whitespace, so in order to make sure the body is properly defined, it needs to be indented under the condition.
As an example, let’s take a look at this while loop:
x = 1
while x < 100:
print(x)
x = x * 2
print('After loop', x)
The condition here is x < 100, so the loop keeps executing the body (print(x) and x = x * 2) until the next iteration it is False (when x = 128). After the loop ends, it continues on to the code after the loop: print('After loop', x).
Food for thought: What happens if you indent that final print statement?
For loops¶
Another type of loop that you’ll commonly see in Python is the for loop. The for loop has a body that runs for each item in a sequence and uses a loop variable to keep track of the current item.
We’ll start by showing an example and then explain the parts.
for i in range(5):
print('Loop', i)
The for loop has the following components
range(5)describes the sequence of values we want to use. In this case,range(5)means the values0, 1, 2, 3, 4.We will explainrangein the next section.iis the loop variable that can be used in the body. On the first iteration,i = 0; theni = 1on the next; and so on until the last iteration, wherei = 4.print('Loop', i)is the body.
The for loop operates very similarly to the while loop, but the key difference is it will loop over the sequence of values specified after the in keyword. Just like the while loop, you put a : at the end of the line containing the keyword for and the body is indented inside the loop.
range Function¶
range is a function in Python provided to make it easy to make sequences of numbers in a range. It turns out, there are three different ways to call range that let you do slightly different types of loops!
# From 0 (inclusive) to A (exclusive)
for i in range(10):
print('Loop', i)
# From A (inclusive) to B (exclusive)
for i in range(2, 10):
print('Loop', i)
# From A (inclusive) to B (exclusive) using step size C
for i in range(2, 10, 3):
print('Loop', i)
Food for thought: What do you think would happen if any of these values were negative?
Conditionals¶
Conditional statements let you execute code conditionally based on some condition; they are similar in nature to the while loop but only run at most once.
In Python, the keywords to control these conditionals are if, elif (read as “else if”), and else.
A conditional block is an if block optionally followed by any number of elif blocks optionally followed by at most one else block. Let’s look at an example:
x = 14
if x < 10:
print('A')
elif x >= 13:
print('B')
elif x >= 20:
print('Not possible')
else:
print('C')
Let’s follow along to see what is printed:
- We define
x = 14. - Check if
x < 10. Since 14 is not less than 10, we skip the body of this conditional statement and move on to the next. - Check if
x >= 13. Since 14 is greater than 13, we move into the body of this conditional statement, which says that we shouldprint('B') - We are done!
Food for thought: Why is it impossible to enter the elif x >= 20 statement? What could we do instead to print the string 'Not possible'?
Functions¶
A function is a named procedure with a series of instructions that can be called in your program to execute those instructions.
To call a function, use its name and use () after it to make it a call For example, print is actually a function defined by Python, so a “print statement” is really just calling this print function.
As we saw earlier, we can pass parameters to this function call to give it inputs. For example, the print function takes parameters for the things to print.
print("To be or not to be")
Functions defined by Python are called built-in functions. print and range are two examples of built-in functions. Some functions can also return values, making them available for use outside the function.
If you want to define a function that takes parameters, you put variable names in between the () for each parameter you want the function to take. If you want the function to return a value, you use a return statement like the example below. To call the function, you need to actually use a function call! (Make sure that it’s not indented under your function header!)
def mean(a, b):
print('Calling mean with', a, b)
return (a + b) / 2
mean(1, 2) # Have to call it passing in two parameters!
⏸️ Pause and 🧠 Think¶
Take a moment to review the following concepts and reflect on your own understanding. A good temperature check for your understanding is asking yourself whether you might be able to explain these concepts to a friend outside of this class.
Here’s what we covered in this lesson: * print statements * Variables and variable assignment * Variable types (strings, float, int, bool) * Arithmetic operators (+, -, /, *, //, %, **) * Logical operators (and, or, not, <, >, <= >=, ==, !=) * while loops * for loops * range * Conditionals * Functions
Here are some other guiding exercises and questions to help you reflect on what you’ve seen so far:
- In your own words, write a few sentences summarizing what you learned in this lesson.
- What did you find challenging in this lesson? Come up with some questions you might ask your peers or the course staff to help you better understand that concept.
- What was familiar about what you saw in this lesson? How might you relate it to things you have learned before?
- Throughout the lesson, there were a few Food for thought questions. Try exploring one or more of them and see what you find.
In-Class¶
When you come to class, we will work together on evaluating Pythonic expressions, and completing countdown.py and fibonacci.py. Make sure that you have a way of editing and running these files!
Expressions¶
- What is the output of the following expression?
x = 2.4
y = 1.2
x = x / y
y = 5
print(x ** 2 <= y)
- What is the output of the following expression?
a = 3
b = 1
while (a % 2 != 0):
b += 1
a += a ** b
print(a)
Countdown¶
For this practice problem, refer to countdown.py.
First, let’s write a program in main that counts down from one minute decrementing by 10 seconds. Use a for loop. The output of the program should be the following:
One minute countdown
60
50
40
30
20
10
0
Done!
The lines of numbers should all be produced by your for loop while the first and last lines will appear outside the loop since they only happen once. Think carefully about the inputs to range—the arguments can be negative!
Once you’ve written this program in main, let’s reuse this logic in a function. We’ll write the function countdown that takes a starting number of int seconds and starts the countdown from there instead (still decrementing by 10s).
The format of the output will be slightly different to accommodate this starting point: if the sequence does not exactly count down to 0 (e.g., starting from 15), then 0 will not be printed. If the starting number of seconds is less than 0, it should instead print "Start must be non-negative!"
Here are four example calls to the function with their corresponding outputs. print statements are included for spacing between different calls to countdown.
countdown(60)
print()
countdown(15)
print()
countdown(-4)
print()
countdown(0)
Output:
60 second countdown
60
50
40
30
20
10
0
Done!
15 second countdown
15
5
Done!
Start must be non-negative!
0 second countdown
0
Done!
Fibonacci¶
For this practice problem, refer to fibonacci.py.
The Fibonacci Sequence is the following sequence of numbers: 1, 1, 2, 3, 5, 8, 13, … The sequence starts with 1 and 1. The next number is the sum of the previous two.
Here, we will write a function fibonacci to compute the first Fibonacci number larger than a given value n. As an example, if we call fibonacci(0), then the output would be 1, since 1 is the first Fibonacci number greater than 0.
Our function should return the first Fibonacci number in the sequence that exceeds the given value n. Here are more examples of output, where the expected output is written as an in-line comment next to the print and function call:
print(fibonacci(0)) # 1
print(fibonacci(1)) # 2
print(fibonacci(2)) # 3
Hint: Create two variables representing the curr and prev Fibonacci numbers. The next number is the sum of curr and prev.
Canvas Quiz¶
All done with the lesson? Complete the Canvas Quiz linked here!