Skip to content
Snippets Groups Projects
Commit ac259682 authored by GURMAIL SINGH's avatar GURMAIL SINGH
Browse files

Lec9 update

parent c55cd6ee
No related branches found
No related tags found
No related merge requests found
.DS_Store
.OTTER_LOG
__pycache__/
.ipynb_checkpoints
%% Cell type:markdown id:25751b55 tags:
# Conditionals 2
## Readings
- Parts of Chapter 5 of Think Python
- Chapter 4.6 to end (skip 4.7) of Python for Everybody
%% Cell type:markdown id:d29fedb7 tags:
## Learning Objectives
- Read and write nested conditional statements
- Define, state reasons for, and provide examples of refactoring
- Refactor code containing conditional statements into boolean expressions
%% Cell type:markdown id:00a02ca4 tags:
### Warmup
%% Cell type:markdown id:4058219f tags:
What's wrong with this code?
%% Cell type:code id:909ef1b6 tags:
``` python
team = "Badgers"
if team == "Gophers" or "Hawkeyes" or "Spartans":
print("Ahh no badgers!")
else:
print("Yay, go badgers!")
```
%% Cell type:markdown id:a9579e28 tags:
**Find a partner to do these TODOs**
TODO: try to compute the boolean expression yourself, by inserting a new cell below. Change team variable's value to all three possible values. Observe what is wrong with the current expression.
TODO: fix the expression after your experiments
%% Cell type:markdown id:dc60b188 tags:
## Example 1: Classifying Children by Age
- Chained conditionals:
- multiple branch within the same conditional
- connected conditions
- if conditional branch
- elif subjective conditional branch(es)
- elif conditions are subjective to the if condition
- that is, only when if condition evaluates to `False`, the next elif condition is evaluated
- only when the first elif condition evaluates to `False`, the second elif condition is evaluated
- and so on ...
- else alternate branch
Age classification:
- "baby" 0 to 1
- "toddler" 2 to 3
- "kid" 4 to 10
- "tween" 11 to 12
- "teen" 13 to 17
- "adult" 18+ (alternate execution)
%% Cell type:code id:2ff08fe4 tags:
``` python
# TODO: get age as user input
age = int(input("Enter your age: "))
def categorize_age(age):
if 0 <= age <= 1:
return "infant" # TODO: discuss why we have a return here instead of print
elif 2 <= age <= 3:
return "toddler"
elif 4 <= age <= 10:
return "kid"
elif 11 <= age <= 12:
return "tween"
elif 13 <= age <= 17:
return "teen"
else:
return "adult"
print("You are a:", categorize_age(age))
```
%% Cell type:markdown id:def170db tags:
## Example 2: Date Printer
- converts 2/14/2022 to "Feb 14th of ‘22"
- decompose a big problem into appropriate steps, by writing functions for individual components
%% Cell type:code id:8c627afc tags:
``` python
def format_month(month):
"""Convert a month (as an integer) into a string.
1 is Jan, 2 is Feb, etc."""
pass
```
%% Cell type:code id:4207cb50 tags:
``` python
def format_day(day):
"""Covert a day into a date string with proper ending.
16 --> '16th', 23 --> '23rd', """
suffix = ""
# TODO: write the conditional here
return suffix
print(format_day(1))
print(format_day(2))
print(format_day(3))
print(format_day(11))
print(format_day(21))
print(format_day(111))
print(format_day(-1))
```
%% Cell type:code id:918b726c tags:
``` python
def format_date(month, day, year):
"""returns a string representing the date, such as Feb 11th of ‘22"""
pass
```
%% Cell type:code id:92cde74e tags:
``` python
format_date(2, 14, 2022)
```
%% Cell type:markdown id:528d781f tags:
## Example 3: Stoplight
<div>
<img src="attachment:Stoplight.png" width="600"/>
</div>
%% Cell type:code id:3c0c3bcd tags:
``` python
def stop_light(color, distance):
pass
```
%% Cell type:markdown id:459296f2 tags:
## Refactoring
What is it?
- Improving/rewriting parts of a program without changing its behavior.
- Like a re-wording of a recipe without changing it
Why do it?
- Make it easier to read and understand the code & what it's doing
- Sometimes to make code run faster
Principles of good refactoring:
- Don't change the program's behavior!
- The program should end up more readable than it started
- Use knowledge of if/else, and/or/not, ==, !=, etc.
%% Cell type:markdown id:d5aae7eb tags:
### Refactoring example 1: nested if conditions
%% Cell type:code id:d03bc22e tags:
``` python
# check combination of a lock
def check_combination(a, b, c):
if a == 2:
if b == 2:
if c == 0:
return True
else:
return False
else:
return False
else:
return False
print(check_combination(2, 2, 0))
print(check_combination(2, 1, 0))
print(check_combination(1, 2, 0))
print(check_combination(3, 1, 9))
```
%% Cell type:code id:feddb4b9 tags:
``` python
def bad_combo(a, b, c):
pass
print(bad_combo(2, 2, 0))
print(bad_combo(2, 1, 0))
print(bad_combo(1, 2, 0))
print(bad_combo(3, 1, 9))
```
%% Cell type:code id:b30eed5f tags:
``` python
def refactor_combo(a, b, c):
pass
print(refactor_combo(2, 2, 0))
print(refactor_combo(2, 1, 0))
print(refactor_combo(1, 2, 0))
print(refactor_combo(3, 1, 9))
```
%% Cell type:markdown id:8b7f186f tags:
### Refactoring example 2: cluttered conditional
%% Cell type:code id:5285840d tags:
``` python
def check_different(b1, b2):
if b1 == True and b2 == False:
return True
elif b1 == False and b2 == True:
return True
elif b1 == True and b2 == True:
return False
elif b1 == False and b2 == False:
return False
print(check_different(True, False))
print(check_different(False, False))
print(check_different(False, True))
print(check_different(True, True))
```
%% Cell type:code id:e53c2cfe tags:
``` python
def refactor_check_different(b1, b2):
pass
print(refactor_check_different(True, False))
print(refactor_check_different(False, False))
print(refactor_check_different(False, True))
print(refactor_check_different(True, True))
```
%% Cell type:markdown id:5dba6585 tags:
## After lecture
- go through examples in slides
- reason about every refactor version and predict correctness of the refactor
- try out each refactor example using Interactive Exercises
- try these sample exam questions on refactoring (predict output, then type your code and run, to confirm your output)
%% Cell type:code id:80c45d13 tags:
``` python
# Refactoring Practice 1: recognizing equivalent code
# Exam 1 Fall 2020
def g(x, y):
# the expression after an if must be a Boolean expression or have a Boolean value
if x:
if y:
return True
else:
return False
else:
return False
# Which of the following will give the same result in all cases, as g(b1, b2)?
# a.) b1 != b2
# b.) b1 and b2
# c.) b1 == b2
# d.) b1 or b2
```
%% Cell type:code id:795e83e4 tags:
``` python
# Refactoring Practice 2:
def h(x, y):
# the expression after an if must be a Boolean expression or have a Boolean value
if x:
return False
else:
if y:
return False
else:
return True
# Which of the following will give the same result in all cases, as h(b1, b2) ?
# a.) b1 != b2
# b.) b1 and b2
# c.) b1 == b2
# d.) not b1 and not b2
```
%% Cell type:code id:6fca19ec tags:
``` python
# Refactoring Practice 3:
def some_bool_eval(x, y):
# the expression after an if must be a Boolean expression or have a Boolean value
if x:
return True
elif y:
return True
else:
return False
print(some_bool_eval(True, False))
print(some_bool_eval(False, True))
print(some_bool_eval(True, True))
print(some_bool_eval(False, False))
# what is the best way to refactor the body of the function ?
# A. return x and y
# B. return x or y
# C. return x != y
# D. return x == y
```
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