Sep 09: More Logic, Tracing Code
Learning Objectives
After today's class, you should be able to:
- Summarize what values Python considers to be true in a Boolean context.
- Predict output when using
if
,elif
,else
, and nestedif
statements. - Use a debugger to step through and examine programs one line at a time.
- Write a function that performs a unit conversion (Ex: celsius to fahrenheit).
Reminders¶
[5 min]
- Due tomorrow
- HW 3 on Canvas
- Quiz 1 on Thursday
- Based on HW 1 and HW 2
- Review questions from Practice Quiz 1
- Study practice exercises on Runestone
- If statements not allowed
MiniLecture from previous class¶
Mini Activity¶
[15 min]
- Boolean Values
- If you are absent today, complete this activity at home
- Bring your completed activity to class or office hours
Code snippet:
value = 123
if value:
print("Truthy")
else:
print("Falsy")
Tracing Practice¶
[20 min]
For each example:
- Predict the output as a team (by hand, on paper)
- Step through the code using Thonny's debugger
Example 1:
hat = "fedora"
if hat == "fedora":
print("A")
else:
print("B")
print("C")
Example 2:
x = 10
if x < 100:
print("A")
elif x < 50:
print("B")
else:
print("C")
print("D")
Example 3:
x = 10
if x < 100:
print("A")
if x < 50:
print("B")
print("C")
Example 4:
x = 10
hat = "fez"
if x > 100 or hat == "fez":
print("A")
if x < 50:
print("B")
else:
print("C")
else:
print("D")
if hat == "fedora":
print("E")
print("F")
Example 5:
x = 1.0
y = 0.0
b1 = x > 0 and y > 0
b2 = not x <= 0 or y <= 0
b3 = not (x <= 0 or y <= 0)
print(b1, b2, b3)
Next Topic Preview: Functions¶
[15 min]
- Functions have parenthesis
- Example from algebra: \(f(x) = 2x\)
- \(f\) is a function, \(x\) is a variable, \(2x\) is the result
- Python keywords:
def
andreturn
def double(number): return 2 * number
- Using descriptive names for functions/variables
- Added Docstring Requirements for Functions
temperature.py | |
---|---|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
|