Control structures direct the flow of a program using logical statements. For example, conditionals (
if-elif-else) allow a program to skip sections of code, and iteration (
while), allows a program to repeat a section.
Conditional statements let programs execute different lines of code depending on certain conditions. Let’s review the
Recall the following points:
elifclauses are optional, and you can have any number of
- A conditional expression is an expression that evaluates to either a truthy value (
True, a non-zero integer, etc.) or a falsy value (
- Only the suite that is indented under the first
elifwhose conditional expression evaluates to a true value will be executed.
If none of the conditional expressions evaluate to a true value, then the
elsesuite is executed. There can only be one
elseclause in a conditional statement!
if <conditional expression>: <suite of statements>; elif <conditional expression>: <suite of statements>; else: <suite of statements>;
Python also includes the boolean operators
not. These operators are used to combine and manipulate boolean values.
notreturns the opposite truth value of the following expression (so not will always return either
andevaluates expressions in order and stops evaluating (short-circuits) once it reaches the first false value, and then returns it. If all values evaluate to a true value, the last value is returned.
orshort-circuits at the first true value and returns it. If all values evaluate to a false value, the last value is returned.
>>> not None True >>> not True False >>> -1 and 0 and 1 0 >>> False or 9999 or 1/0 9999
Q1: Jacket Weather?
Alfonso will only wear a jacket outside if it is below 60 degrees or it is raining.
Write a function that takes in the current temperature and a boolean value telling if it is raining and returns
True if Alfonso will wear a jacket and
First, try solving this problem using an
Note that we’ll either return
False based on a single condition, whose truthiness value will also be either
False. Knowing this, try to write this function using a single line.
Q2: (Tutorial) Warm Up: Case Conundrum
These exercises are meant to help refresh your memory of topics covered in lecture and/or lab this week before tackling more challenging problems.
In this question, we will explore the difference between the
What is the result of evaluating the following code?
def special_case(): x = 10 if x > 0: x += 2 elif x < 13: x += 3 elif x % 2 == 1: x += 4 return x special_case()
What is the result of evaluating this piece of code?
def just_in_case(): x = 10 if x > 0: x += 2 if x < 13: x += 3 if x % 2 == 1: x += 4 return x just_in_case()
How about this piece of code?
def case_in_point(): x = 10 if x > 0: return x + 2 if x < 13: return x + 3 if x % 2 == 1: return x + 4 return x case_in_point()
Which of these code snippets result in the same output, and why? Based on your findings, when do you think using a series of
if statements has the same effect as using both
To repeat the same statements multiple times in a program, we can use iteration. In Python, one way we can do this is with a while loop.
while <conditional clause>: <body of statements>
As long as
<conditional clause> evaluates to a true value,
<body of statements> will continue to be executed. The conditional clause gets evaluated each time the body finishes executing.
Q3: Square So Slow
What is the result of evaluating the following code?
def square(x): print("here!") return x * x def so_slow(num): x = num while x > 0: x=x+1 return x / 0 square(so_slow(5))
Q4: (Tutorial) Is Prime?
Write a function that returns
True if a positive integer
n is a prime number and
A prime number n is a number that is not divisible by any numbers other than 1 and n itself. For example, 13 is prime, since it is only divisible by 1 and 13, but 14 is not, since it is divisible by 1, 2, 7, and 14.
Run in 61A Code
Hint: Use the
x % yreturns the remainder of
xwhen divided by
Q5: (Tutorial) Fizzbuzz
fizzbuzz(n), which prints numbers from 1 to
n. However, for numbers divisible by 3, print "fizz". For numbers divisible by 5, print "buzz". For numbers divisibule by both 3 and 5, print "fizzbuzz".
This is a standard software engineering interview question, but we're confident in your ability to solve it!Run in 61A Code
An environment diagram is a model we use to keep track of all the variables that have been defined and the values they are bound to. We will be using this tool throughout the course to understand complex programs involving several different assignments and function calls.
Here's a simple program and its corresponding diagram:
Remember that programs are simply a set of statements, or instructions—so drawing diagrams that represent these programs also involves following sets of instructions! Let’s dive in...
Assignment statements, such as
x = 3, define variables in programs. To execute one in an environment diagram, record the variable name and the value:
- Evaluate the expression on the right side of the
- Write the variable name and the expression’s value in the current frame.
Q6: Assignment Diagram
Use these rules to draw a simple diagram for the assignment statements below:
x = 11 % 4 y = x x **= 2
def statement creates a function object and binds it to a name. To diagram
def statements, record the function name and bind the function object to the name. It’s also important to write the parent frame of the function, which is where the function is defined. Very important note: Assignments for def statements use pointers to functions, which can have different behavior than primitive assignments.
- Draw the function object to the right-hand-side of the frames, denoting the intrinsic name of the function, its parameters, and the parent frame (e.g.
func square(x) [parent = Global]
- Write the function name in the current frame and draw an arrow from the name to the function object.
Q7: def Diagram
Use these rules and the rules for assignment statements to draw a diagram for the code below.
def double(x): return x * 2 def triple(x): return x * 3 hat = double double = triple
Call expressions, such as
square(2), apply functions to arguments. When executing call expressions, we create a new frame in our diagram to keep track of local variables:
- Evaluate the operator, which should evaluate to a function.
- Evaluate the operands from left to right.
Draw a new frame, labelling it with the following:
- A unique index (
- The intrinsic name of the function, which is the name of the function object itself. For example, if the function object is
func square(x) [parent=Global], the intrinsic name is
- The parent frame ([
- A unique index (
- Bind the formal parameters to the argument values obtained in step 2 (e.g.
- Evaluate the body of the function in this new frame until a return value is obtained. Write down the return value in the frame.
If a function does not have a return value, it implicitly returns
None. In that case,
the “Return value” box should contain
Note: Since we do not know how built-in functions like
min(...) or imported functions like
add(...) are implemented, we do not draw a new frame when we call them, since we would not be able to fill it out accurately.
Q8: Call Diagram
Let’s put it all together! Draw an environment diagram for the following code. You may not have to use all of the blanks provided to you.
def double(x): return x * 2 hmmm = double wow = double(3) hmmm(wow)
Q9: (Tutorial) Nested Calls Diagrams
Draw the environment diagram that results from executing the code below. You may not need to use all of the frames and blanks provided to you.
def f(x): return x def g(x, y): if x(y): return not y return y x = 3 x = g(f, x) f = g(f, 0)