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

Lec8 update

parent 875968c4
No related branches found
No related tags found
No related merge requests found
Showing
with 1607 additions and 2 deletions
File added
File added
%% Cell type:markdown id:7dba8f50 tags:
# Announcements - Friday
* Get a worksheet
* Q2 due Today
%% Cell type:markdown id:309ae71d tags: %% Cell type:markdown id:309ae71d tags:
   
# Conditionals 1 # Conditionals 1
   
## Readings ## Readings
- Parts of Chapter 5 of Think Python - Parts of Chapter 5 of Think Python
- Chapter 5.5 to 5.8 of Python for Everybody - Chapter 5.5 to 5.8 of Python for Everybody
   
%% Cell type:markdown id:1e0a09a9 tags: %% Cell type:markdown id:1e0a09a9 tags:
   
### Review 1: `return` statement is final in a function execution ### Review 1: `return` statement is final in a function execution
   
When you call the below `rect_area` function, how many times does # line 3 get executed? When you call the below `rect_area` function, how many times does # line 3 get executed?
   
%% Cell type:code id:691c702a tags: %% Cell type:code id:691c702a tags:
   
``` python ``` python
def rect_area(length, breadth = 2): # line 1 def rect_area(length, breadth = 2): # line 1
return length * breadth # line 2 return length * breadth # line 2
print("Area of rectangle is: " + length * breadth) # line 3 print("Area of rectangle is: " + length * breadth) # line 3
   
rect_area(10) rect_area(10)
``` ```
   
%% Output %% Output
   
20 20
   
%% Cell type:markdown id:1ba9eb50 tags: %% Cell type:markdown id:1ba9eb50 tags:
   
### Review 2: Indentation ### Review 2: Indentation
   
What is the output of the below code? What is the output of the below code?
- vertical blank space does not matter - vertical blank space does not matter
- Python only cares about indentation to identify function definition lines of code - Python only cares about indentation to identify function definition lines of code
   
%% Cell type:code id:19e9fbf6 tags: %% Cell type:code id:19e9fbf6 tags:
   
``` python ``` python
print("A") print("A")
print("B") print("B")
   
def print_letters(): def print_letters():
print("C") print("C")
   
   
print("D") print("D")
   
print("E") print("E")
print("F") print("F")
   
print_letters() print_letters()
``` ```
   
%% Output %% Output
   
A A
B B
E E
F F
C C
D D
   
%% Cell type:markdown id:45be75af tags: %% Cell type:markdown id:45be75af tags:
   
### Review 3: Argument passing ### Review 3: Argument passing
   
What is the output of the below code? What is the output of the below code?
   
%% Cell type:code id:55244dd8 tags: %% Cell type:code id:55244dd8 tags:
   
``` python ``` python
def h(x=1, y=2): def h(x=1, y=2):
print(x, y) # what is printed? print(x, y) # what is printed?
   
def g(x, y): def g(x, y):
print(x, y) # what is printed? print(x, y) # what is printed?
h(y) h(y)
   
def f(x, y): def f(x, y):
print(x, y) # what is printed? print(x, y) # what is printed?
g(x=x, y=y+1) g(x=x, y=y+1)
   
x = 10 x = 10
y = 20 y = 20
f(y, x) f(y, x)
``` ```
   
%% Output %% Output
   
20 10 20 10
20 11 20 11
11 2 11 2
   
%% Cell type:markdown id:9f23b102 tags: %% Cell type:markdown id:9f23b102 tags:
   
## Learing Objectives ## Learing Objectives
   
- Write conditional statements - Write conditional statements
- using conditional execution (if) - using conditional execution (if)
- using alternate execution (if/else) - using alternate execution (if/else)
- using chained conditionals (if/elif/elif/…/else) - using chained conditionals (if/elif/elif/…/else)
   
- Identify code blocks (indentation layers) in a program - Identify code blocks (indentation layers) in a program
- count the number of blocks in a segment of code - count the number of blocks in a segment of code
   
- Determine the output of code with conditional statements - Determine the output of code with conditional statements
   
%% Cell type:markdown id:424fa9f4 tags: %% Cell type:markdown id:424fa9f4 tags:
   
<div> <div>
<img src="attachment:Condition_flow_chart.png" width="600"/> <img src="attachment:Condition_flow_chart.png" width="600"/>
</div> </div>
   
%% Cell type:markdown id:7f821152 tags: %% Cell type:markdown id:7f821152 tags:
   
### Terminology ### Terminology
   
- conditional - conditional
- condition - condition
- conditional execution - conditional execution
- alternate execution - alternate execution
- branches (also known as "Paths of execution") - branches (also known as "Paths of execution")
   
<div> <div>
<img src="attachment:Conditional_terminology.png" width="600"/> <img src="attachment:Conditional_terminology.png" width="600"/>
</div> </div>
   
%% Cell type:markdown id:2035b7e1 tags: %% Cell type:markdown id:2035b7e1 tags:
   
<div> <div>
<img src="attachment:Branch1.png" width="600"/> <img src="attachment:Branch1.png" width="600"/>
</div> </div>
   
%% Cell type:markdown id:7b0116a8 tags: %% Cell type:markdown id:7b0116a8 tags:
   
<div> <div>
<img src="attachment:Branch2.png" width="600"/> <img src="attachment:Branch2.png" width="600"/>
</div> </div>
   
%% Cell type:markdown id:927debdc tags: %% Cell type:markdown id:927debdc tags:
   
### Python code for the below flowchart ### Python code for the below flowchart
   
<div> <div>
<img src="attachment:updated_flowchart.png" width="400"/> <img src="attachment:updated_flowchart.png" width="400"/>
</div> </div>
   
%% Cell type:code id:774ea61f tags: %% Cell type:code id:774ea61f tags:
   
``` python ``` python
x = input("enter x: ") x = input("enter x: ")
x = int(x) x = int(x)
   
if x % 2 == 0: # condition if x % 2 == 0: # condition
# conditional execution # conditional execution
print("it’s even") print("it’s even")
print("we wanted odd") print("we wanted odd")
else: else:
# alternate execution # alternate execution
print("it’s odd") print("it’s odd")
print("good!") print("good!")
   
print("thank you") print("thank you")
print("all done") print("all done")
``` ```
   
%% Output %% Output
   
enter x: 12 enter x: 12
it’s even it’s even
we wanted odd we wanted odd
thank you thank you
all done all done
   
%% Cell type:markdown id:a5935b5d tags: %% Cell type:markdown id:a5935b5d tags:
   
### Example 0: Classify English words as "short" ### Example 0: Classify English words as "short"
   
- TODO: discuss what number can be filled into the below blank - TODO: discuss what number can be filled into the below blank
- A word in English is "short" if it has \_\_\_5_\_\_ letters or less otherwise it is "long" - A word in English is "short" if it has \_\_\_5_\_\_ letters or less otherwise it is "long"
   
%% Cell type:code id:99f93d73 tags: %% Cell type:code id:99f93d73 tags:
   
``` python ``` python
# TODO: initialize word with some short word # TODO: initialize word with some short word
word = "snow" word = "snow"
   
# TODO: compute length of word # TODO: compute length of word
word_length = len(word) word_length = len(word)
   
# Now let's write our first conditional for short words # Now let's write our first conditional for short words
if word_length <= 5: if word_length <= 5:
print(word, "is short") print(word, "is short")
print("short words are fun") print("short words are fun")
``` ```
   
%% Output %% Output
   
snow is short snow is short
short words are fun short words are fun
   
%% Cell type:code id:97a0e006 tags: %% Cell type:code id:97a0e006 tags:
   
``` python ``` python
# TODO: initialize word with some long word # TODO: initialize word with some long word
word = "spectacular" word = "spectacular"
   
# TODO: compute length of word # TODO: compute length of word
word_length = len(word) word_length = len(word)
   
# TODO: write another conditional for long words # TODO: write another conditional for long words
if word_length > 5: if word_length > 5:
print(word, "is long") print(word, "is long")
print("long words are interesting") print("long words are interesting")
``` ```
   
%% Output %% Output
   
spectacular is long spectacular is long
long words are interesting long words are interesting
   
%% Cell type:markdown id:28d15336 tags: %% Cell type:markdown id:28d15336 tags:
   
## Example 0 (version 2): Classify English words as "short" or "long" ## Example 0 (version 2): Classify English words as "short" or "long"
   
- `if` block conditional execution - `if` block conditional execution
- `else` block alternate execution - `else` block alternate execution
   
%% Cell type:code id:dafc0074 tags: %% Cell type:code id:dafc0074 tags:
   
``` python ``` python
# TODO: initialize word with some short word # TODO: initialize word with some short word
word = "edify" word = "edify"
   
# TODO: compute length of word # TODO: compute length of word
word_length = len(word) word_length = len(word)
   
# Now let's write our first conditional for short / long words # Now let's write our first conditional for short / long words
if word_length <= 5: if word_length <= 5:
# conditional execution # conditional execution
print(word, "is short") print(word, "is short")
print("short words are fun") print("short words are fun")
else: else:
# alternate execution # alternate execution
print(word, "is long") print(word, "is long")
print("long words are interesting") print("long words are interesting")
   
# TODO: go back to line 2 and change word's initialization to a long word # TODO: go back to line 2 and change word's initialization to a long word
``` ```
   
%% Output %% Output
   
edify is short edify is short
short words are fun short words are fun
   
%% Cell type:markdown id:b14628c6 tags: %% Cell type:markdown id:b14628c6 tags:
   
## PythonTutor visualization ## PythonTutor visualization
   
- copy and paste the final version of example 0 into PythonTutor and step through the code, to solidify understanding of control flow - copy and paste the final version of example 0 into PythonTutor and step through the code, to solidify understanding of control flow
   
%% Cell type:markdown id:3dced4fd tags: %% Cell type:markdown id:3dced4fd tags:
   
<div> <div>
<img src="attachment:code_blocks.png" width="600"/> <img src="attachment:code_blocks.png" width="600"/>
</div> </div>
   
%% Cell type:markdown id:be10dae4 tags: %% Cell type:markdown id:be10dae4 tags:
   
### Identifying code blocks ### Identifying code blocks
   
- Step 1: look for a colon at end of a line - Step 1: look for a colon at end of a line
- Step 2: start drawing a line on next code line that is indented in - Step 2: start drawing a line on next code line that is indented in
- Step 3: continue down until you hit code that is less indented - Step 3: continue down until you hit code that is less indented
- Step 4: box off the code - Step 4: box off the code
- Step 5: look for the next colon to find more boxes and then repeat steps 1 to 4 - Step 5: look for the next colon to find more boxes and then repeat steps 1 to 4
   
<div> <div>
<img src="attachment:identified_code_blocks.png" width="400"/> <img src="attachment:identified_code_blocks.png" width="400"/>
</div> </div>
   
%% Cell type:markdown id:99706f6e tags: %% Cell type:markdown id:99706f6e tags:
   
## Worksheet problem 1 ## Worksheet problem 1
- let's do problem 1 in today's lecture worksheet - let's do problem 1 in today's lecture worksheet
   
%% Cell type:markdown id:97da9526 tags: %% Cell type:markdown id:97da9526 tags:
   
## Example 1: Classifying Children by Age ## Example 1: Classifying Children by Age
- does anyone know what is the age bound for "baby"? - does anyone know what is the age bound for "baby"?
- what about a "toddler"? - what about a "toddler"?
- Chained conditionals: - Chained conditionals:
- multiple branch within the same conditional - multiple branch within the same conditional
- connected conditions - connected conditions
- if conditional branch - if conditional branch
- elif subjective conditional branch(es) - elif subjective conditional branch(es)
- elif conditions are subjective to the if condition - elif conditions are subjective to the if condition
- that is, only when if condition evaluates to `False`, the next elif condition is evaluated - 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 - only when the first elif condition evaluates to `False`, the second elif condition is evaluated
- and so on ... - and so on ...
- else alternate branch - else alternate branch
   
%% Cell type:code id:b969d76d tags: %% Cell type:code id:b969d76d tags:
   
``` python ``` python
# TODO: get age as user input # TODO: get age as user input
# TODO: what is the default return type of input function call? # TODO: what is the default return type of input function call?
age = int(input("Enter your age: ")) age = int(input("Enter your age: "))
   
def categorize_age(age): def categorize_age(age):
if 0 <= age <= 1: if 0 <= age <= 1:
return "baby" return "baby"
elif 2 <= age <= 3: elif 2 <= age <= 3:
return "toddler" return "toddler"
elif 4 <= age <= 10: elif 4 <= age <= 10:
return "kid" return "kid"
elif 11 <= age <= 12: elif 11 <= age <= 12:
return "tween" return "tween"
elif 13 <= age <= 17: elif 13 <= age <= 17:
return "teen" return "teen"
else: else:
return "adult" return "adult"
   
print("You are a:", categorize_age(age)) print("You are a:", categorize_age(age))
``` ```
   
%% Output %% Output
   
Enter your age: 3 Enter your age: 3
You are a: toddler You are a: toddler
   
%% Cell type:markdown id:172ace46 tags: %% Cell type:markdown id:172ace46 tags:
   
## Example 2: Date Printer ## Example 2: Date Printer
- converts 2/11/2022 to "Feb 11th of ‘22" - converts 2/11/2022 to "Feb 11th of ‘22"
   
%% Cell type:code id:96709e36 tags: %% Cell type:code id:96709e36 tags:
   
``` python ``` python
def format_month(month): def format_month(month):
"""Convert a month (as an integer) into a string. """Convert a month (as an integer) into a string.
1 is Jan, 2 is Feb, etc.""" 1 is Jan, 2 is Feb, etc."""
if month == 1: if month == 1:
return "Jan" return "Jan"
elif month == 2: elif month == 2:
return "Feb" return "Feb"
elif month == 3: elif month == 3:
return "Mar" return "Mar"
elif month == 4: elif month == 4:
return "Apr" return "Apr"
elif month == 5: elif month == 5:
return "May" return "May"
elif month == 6: elif month == 6:
return "Jun" return "Jun"
elif month == 7: elif month == 7:
return "Jul" return "Jul"
elif month == 8: elif month == 8:
return "Aug" return "Aug"
elif month == 9: elif month == 9:
return "Sep" return "Sep"
elif month == 10: elif month == 10:
return "Oct" return "Oct"
elif month == 11: elif month == 11:
return "Nov" return "Nov"
elif month == 12: elif month == 12:
return "Dec" return "Dec"
else: else:
return "Invalid month!" return "Invalid month!"
``` ```
   
%% Cell type:code id:528f10f6 tags: %% Cell type:code id:528f10f6 tags:
   
``` python ``` python
def format_day(day): def format_day(day):
"""Covert a day into a date string with proper ending. """Covert a day into a date string with proper ending.
16 --> '16th', 23 --> '23rd', """ 16 --> '16th', 23 --> '23rd', """
suffix = "" suffix = ""
if day < 1: if day < 1:
suffix = "error" suffix = "error"
elif 11 <= day % 100 <= 20: elif 11 <= day % 100 <= 20:
suffix = str(day) + "th" suffix = str(day) + "th"
elif day % 10 == 1: elif day % 10 == 1:
suffix = str(day) + "st" suffix = str(day) + "st"
elif day % 10 == 2: elif day % 10 == 2:
suffix = str(day) + "nd" suffix = str(day) + "nd"
elif day % 10 == 3: elif day % 10 == 3:
suffix = str(day) + "rd" suffix = str(day) + "rd"
else: else:
suffix = str(day) + "th" suffix = str(day) + "th"
   
return suffix return suffix
   
print(format_day(1)) print(format_day(1))
print(format_day(2)) print(format_day(2))
print(format_day(3)) print(format_day(3))
print(format_day(11)) print(format_day(11))
print(format_day(21)) print(format_day(21))
print(format_day(111)) print(format_day(111))
print(format_day(-1)) print(format_day(-1))
``` ```
   
%% Output %% Output
   
1st 1st
2nd 2nd
3rd 3rd
11th 11th
21st 21st
111th 111th
error error
   
%% Cell type:code id:fd3a653d tags: %% Cell type:code id:fd3a653d tags:
   
``` python ``` python
def format_date(month, day, year): def format_date(month, day, year):
"""returns a string representing the date, such as Feb 11th of ‘22""" """returns a string representing the date, such as Feb 11th of ‘22"""
result_str = "" result_str = ""
result_str += format_month(month) result_str += format_month(month)
result_str += " " + format_day(day) result_str += " " + format_day(day)
result_str += " of '" + str(year % 100) result_str += " of '" + str(year % 100)
   
return result_str return result_str
``` ```
   
%% Cell type:code id:8ecd4d9d tags: %% Cell type:code id:8ecd4d9d tags:
   
``` python ``` python
format_date(9, 23, 2022) format_date(9, 23, 2022)
``` ```
   
%% Output %% Output
   
"Sep 23rd of '22" "Sep 23rd of '22"
   
%% Cell type:markdown id:cb4e6eb9 tags: %% Cell type:markdown id:cb4e6eb9 tags:
   
### Worksheet problem 2 ### Worksheet problem 2
- let's do problem 2 in today's lecture worksheet - let's do problem 2 in today's lecture worksheet
......
%% Cell type:markdown id:4ef43c12 tags:
# Announcements - Friday
* Get a worksheet
* Q2 due Today
%% Cell type:markdown id:309ae71d tags: %% Cell type:markdown id:309ae71d tags:
   
# Conditionals 1 # Conditionals 1
   
## Readings ## Readings
- Parts of Chapter 5 of Think Python - Parts of Chapter 5 of Think Python
- Chapter 5.5 to 5.8 of Python for Everybody - Chapter 5.5 to 5.8 of Python for Everybody
   
%% Cell type:markdown id:1e0a09a9 tags: %% Cell type:markdown id:1e0a09a9 tags:
   
### Review 1: `return` statement is final in a function execution ### Review 1: `return` statement is final in a function execution
   
When you call the below `rect_area` function, how many times does # line 3 get executed? When you call the below `rect_area` function, how many times does # line 3 get executed?
   
``` ```
def rect_area(length, breadth = 2): # line 1 def rect_area(length, breadth = 2): # line 1
return length * breadth # line 2 return length * breadth # line 2
print("Area of rectangle is: " + length * breadth) # line 3 print("Area of rectangle is: " + length * breadth) # line 3
   
rect_area(10) rect_area(10)
``` ```
   
%% Cell type:code id:691c702a tags: %% Cell type:code id:691c702a tags:
   
``` python ``` python
# TODO: copy / paste the above code and test your answer # TODO: copy / paste the above code and test your answer
``` ```
   
%% Cell type:markdown id:1ba9eb50 tags: %% Cell type:markdown id:1ba9eb50 tags:
   
### Review 2: Indentation ### Review 2: Indentation
   
What is the output of the below code? What is the output of the below code?
- vertical blank space does not matter - vertical blank space does not matter
- Python only cares about indentation to identify function definition lines of code - Python only cares about indentation to identify function definition lines of code
   
``` ```
print("A") print("A")
print("B") print("B")
   
def print_letters(): def print_letters():
print("C") print("C")
   
   
print("D") print("D")
   
print("E") print("E")
print("F") print("F")
   
print_letters() print_letters()
``` ```
   
%% Cell type:code id:19e9fbf6 tags: %% Cell type:code id:19e9fbf6 tags:
   
``` python ``` python
# TODO: copy / paste the above code and test your answer # TODO: copy / paste the above code and test your answer
``` ```
   
%% Cell type:markdown id:45be75af tags: %% Cell type:markdown id:45be75af tags:
   
### Review 3: Argument passing ### Review 3: Argument passing
   
What is the output of the below code? What is the output of the below code?
   
``` ```
def h(x=1, y=2): def h(x=1, y=2):
print(x, y) # what is printed? print(x, y) # what is printed?
   
def g(x, y): def g(x, y):
print(x, y) # what is printed? print(x, y) # what is printed?
h(y) h(y)
   
def f(x, y): def f(x, y):
print(x, y) # what is printed? print(x, y) # what is printed?
g(x=x, y=y+1) g(x=x, y=y+1)
   
x = 10 x = 10
y = 20 y = 20
f(y, x) f(y, x)
``` ```
   
%% Cell type:code id:55244dd8 tags: %% Cell type:code id:55244dd8 tags:
   
``` python ``` python
# TODO: copy / paste the above code and test your answer # TODO: copy / paste the above code and test your answer
``` ```
   
%% Cell type:markdown id:9f23b102 tags: %% Cell type:markdown id:9f23b102 tags:
   
## Learing Objectives ## Learing Objectives
   
- Write conditional statements - Write conditional statements
- using conditional execution (if) - using conditional execution (if)
- using alternate execution (if/else) - using alternate execution (if/else)
- using chained conditionals (if/elif/elif/…/else) - using chained conditionals (if/elif/elif/…/else)
   
- Identify code blocks (indentation layers) in a program - Identify code blocks (indentation layers) in a program
- count the number of blocks in a segment of code - count the number of blocks in a segment of code
   
- Determine the output of code with conditional statements - Determine the output of code with conditional statements
   
%% Cell type:markdown id:424fa9f4 tags: %% Cell type:markdown id:424fa9f4 tags:
   
<div> <div>
<img src="attachment:Condition_flow_chart.png" width="600"/> <img src="attachment:Condition_flow_chart.png" width="600"/>
</div> </div>
   
%% Cell type:markdown id:7f821152 tags: %% Cell type:markdown id:7f821152 tags:
   
### Terminology ### Terminology
   
- conditional - conditional
- condition - condition
- conditional execution - conditional execution
- alternate execution - alternate execution
- branches (also known as "Paths of execution") - branches (also known as "Paths of execution")
   
<div> <div>
<img src="attachment:Conditional_terminology.png" width="600"/> <img src="attachment:Conditional_terminology.png" width="600"/>
</div> </div>
   
%% Cell type:markdown id:2035b7e1 tags: %% Cell type:markdown id:2035b7e1 tags:
   
<div> <div>
<img src="attachment:Branch1.png" width="600"/> <img src="attachment:Branch1.png" width="600"/>
</div> </div>
   
%% Cell type:markdown id:7b0116a8 tags: %% Cell type:markdown id:7b0116a8 tags:
   
<div> <div>
<img src="attachment:Branch2.png" width="600"/> <img src="attachment:Branch2.png" width="600"/>
</div> </div>
   
%% Cell type:markdown id:927debdc tags: %% Cell type:markdown id:927debdc tags:
   
### Python code for the below flowchart ### Python code for the below flowchart
   
<div> <div>
<img src="attachment:updated_flowchart.png" width="400"/> <img src="attachment:updated_flowchart.png" width="400"/>
</div> </div>
   
%% Cell type:code id:774ea61f tags: %% Cell type:code id:774ea61f tags:
   
``` python ``` python
x = input("enter x: ") x = input("enter x: ")
x = int(x) x = int(x)
   
if x % 2 == 0: # condition if x % 2 == 0: # condition
# conditional execution # conditional execution
print("it’s even") print("it’s even")
print("we wanted odd") print("we wanted odd")
else: else:
# alternate execution # alternate execution
print("it’s odd") print("it’s odd")
print("good!") print("good!")
   
print("thank you") print("thank you")
print("all done") print("all done")
``` ```
   
%% Cell type:markdown id:a5935b5d tags: %% Cell type:markdown id:a5935b5d tags:
   
### Example 0: Classify English words as "short" ### Example 0: Classify English words as "short"
   
- TODO: discuss what number can be filled into the below blank - TODO: discuss what number can be filled into the below blank
- A word in English is "short" if it has \_\_\_\_\_ letters or less otherwise it is "long" - A word in English is "short" if it has \_\_\_\_\_ letters or less otherwise it is "long"
   
%% Cell type:code id:99f93d73 tags: %% Cell type:code id:99f93d73 tags:
   
``` python ``` python
# TODO: initialize word with some short word # TODO: initialize word with some short word
word = "" word = ""
   
# TODO: compute length of word # TODO: compute length of word
   
# Now let's write our first conditional for short words # Now let's write our first conditional for short words
``` ```
   
%% Cell type:code id:97a0e006 tags: %% Cell type:code id:97a0e006 tags:
   
``` python ``` python
# TODO: initialize word with some long word # TODO: initialize word with some long word
word = "" word = ""
   
# TODO: compute length of word # TODO: compute length of word
word_length = len(word) word_length = len(word)
   
# TODO: write another conditional for long words # TODO: write another conditional for long words
if ???: if ???:
print(word, "is long") print(word, "is long")
print("long words are interesting") print("long words are interesting")
``` ```
   
%% Cell type:markdown id:28d15336 tags: %% Cell type:markdown id:28d15336 tags:
   
## Example 0 (version 2): Classify English words as "short" or "long" ## Example 0 (version 2): Classify English words as "short" or "long"
   
- `if` block conditional execution - `if` block conditional execution
- `else` block alternate execution - `else` block alternate execution
   
%% Cell type:code id:dafc0074 tags: %% Cell type:code id:dafc0074 tags:
   
``` python ``` python
# TODO: initialize word with some short word # TODO: initialize word with some short word
word = "" word = ""
   
# TODO: compute length of word # TODO: compute length of word
word_length = len(word) word_length = len(word)
   
# Now let's write our first conditional for short words # Now let's write our first conditional for short words
   
   
# TODO: go back to line 2 and change word's initialization to a long word # TODO: go back to line 2 and change word's initialization to a long word
``` ```
   
%% Cell type:markdown id:b14628c6 tags: %% Cell type:markdown id:b14628c6 tags:
   
## PythonTutor visualization ## PythonTutor visualization
   
- copy and paste the final version of example 0 into PythonTutor and step through the code, to solidify understanding of control flow - copy and paste the final version of example 0 into PythonTutor and step through the code, to solidify understanding of control flow
   
%% Cell type:markdown id:3dced4fd tags: %% Cell type:markdown id:3dced4fd tags:
   
<div> <div>
<img src="attachment:code_blocks.png" width="600"/> <img src="attachment:code_blocks.png" width="600"/>
</div> </div>
   
%% Cell type:markdown id:be10dae4 tags: %% Cell type:markdown id:be10dae4 tags:
   
### Identifying code blocks ### Identifying code blocks
   
- Step 1: look for a colon at end of a line - Step 1: look for a colon at end of a line
- Step 2: start drawing a line on next code line that is indented in - Step 2: start drawing a line on next code line that is indented in
- Step 3: continue down until you hit code that is less indented - Step 3: continue down until you hit code that is less indented
- Step 4: box off the code - Step 4: box off the code
- Step 5: look for the next colon to find more boxes and then repeat steps 1 to 4 - Step 5: look for the next colon to find more boxes and then repeat steps 1 to 4
   
<div> <div>
<img src="attachment:identified_code_blocks.png" width="400"/> <img src="attachment:identified_code_blocks.png" width="400"/>
</div> </div>
   
%% Cell type:markdown id:99706f6e tags: %% Cell type:markdown id:99706f6e tags:
   
## Worksheet problem 1 ## Worksheet problem 1
- let's do problem 1 in today's lecture worksheet - let's do problem 1 in today's lecture worksheet
   
%% Cell type:markdown id:97da9526 tags: %% Cell type:markdown id:97da9526 tags:
   
## Example 1: Classifying Children by Age ## Example 1: Classifying Children by Age
- does anyone know what is the age bound for "baby"? - does anyone know what is the age bound for "baby"?
- what about a "toddler"? - what about a "toddler"?
- Chained conditionals: - Chained conditionals:
- multiple branch within the same conditional - multiple branch within the same conditional
- connected conditions - connected conditions
- if conditional branch - if conditional branch
- elif subjective conditional branch(es) - elif subjective conditional branch(es)
- elif conditions are subjective to the if condition - elif conditions are subjective to the if condition
- that is, only when if condition evaluates to `False`, the next elif condition is evaluated - 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 - only when the first elif condition evaluates to `False`, the second elif condition is evaluated
- and so on ... - and so on ...
- else alternate branch - else alternate branch
   
%% Cell type:code id:b969d76d tags: %% Cell type:code id:b969d76d tags:
   
``` python ``` python
# TODO: get age as user input # TODO: get age as user input
# TODO: what is the default return type of input function call? # TODO: what is the default return type of input function call?
age = int(input("Enter your age: ")) age = int(input("Enter your age: "))
   
def categorize_age(age): def categorize_age(age):
pass pass
   
print("You are a:", categorize_age(age)) print("You are a:", categorize_age(age))
``` ```
   
%% Cell type:markdown id:172ace46 tags: %% Cell type:markdown id:172ace46 tags:
   
## Example 2: Date Printer ## Example 2: Date Printer
- converts 2/11/2022 to "Feb 11th of ‘22" - converts 2/11/2022 to "Feb 11th of ‘22"
   
%% Cell type:code id:96709e36 tags: %% Cell type:code id:96709e36 tags:
   
``` python ``` python
def format_month(month): def format_month(month):
"""Convert a month (as an integer) into a string. """Convert a month (as an integer) into a string.
1 is Jan, 2 is Feb, etc.""" 1 is Jan, 2 is Feb, etc."""
pass pass
``` ```
   
%% Cell type:code id:528f10f6 tags: %% Cell type:code id:528f10f6 tags:
   
``` python ``` python
def format_day(day): def format_day(day):
"""Covert a day into a date string with proper ending. """Covert a day into a date string with proper ending.
16 --> '16th', 23 --> '23rd', """ 16 --> '16th', 23 --> '23rd', """
suffix = "" suffix = ""
   
# TODO: write the conditional here # TODO: write the conditional here
   
return suffix return suffix
   
print(format_day(1)) print(format_day(1))
print(format_day(2)) print(format_day(2))
print(format_day(3)) print(format_day(3))
print(format_day(11)) print(format_day(11))
print(format_day(21)) print(format_day(21))
# print(format_day(111)) # print(format_day(111))
# print(format_day(-1)) # print(format_day(-1))
``` ```
   
%% Cell type:code id:fd3a653d tags: %% Cell type:code id:fd3a653d tags:
   
``` python ``` python
def format_date(month, day, year): def format_date(month, day, year):
"""returns a string representing the date, such as Feb 11th of ‘22""" """returns a string representing the date, such as Feb 11th of ‘22"""
pass pass
``` ```
   
%% Cell type:code id:8ecd4d9d tags: %% Cell type:code id:8ecd4d9d tags:
   
``` python ``` python
format_date(9, 23, 2022) format_date(9, 23, 2022)
``` ```
   
%% Cell type:markdown id:cb4e6eb9 tags: %% Cell type:markdown id:cb4e6eb9 tags:
   
### Worksheet problem 2 ### Worksheet problem 2
- let's do problem 2 in today's lecture worksheet - let's do problem 2 in today's lecture worksheet
......
%% Cell type:markdown id:7dba8f50 tags:
# Announcements - Friday
* Get a worksheet
* Q2 due Today
%% Cell type:markdown id:309ae71d tags: %% Cell type:markdown id:309ae71d tags:
   
# Conditionals 1 # Conditionals 1
   
## Readings ## Readings
- Parts of Chapter 5 of Think Python - Parts of Chapter 5 of Think Python
- Chapter 5.5 to 5.8 of Python for Everybody - Chapter 5.5 to 5.8 of Python for Everybody
   
%% Cell type:markdown id:1e0a09a9 tags: %% Cell type:markdown id:1e0a09a9 tags:
   
### Review 1: `return` statement is final in a function execution ### Review 1: `return` statement is final in a function execution
   
When you call the below `rect_area` function, how many times does # line 3 get executed? When you call the below `rect_area` function, how many times does # line 3 get executed?
   
%% Cell type:code id:691c702a tags: %% Cell type:code id:691c702a tags:
   
``` python ``` python
def rect_area(length, breadth = 2): # line 1 def rect_area(length, breadth = 2): # line 1
return length * breadth # line 2 return length * breadth # line 2
print("Area of rectangle is: " + length * breadth) # line 3 print("Area of rectangle is: " + length * breadth) # line 3
   
rect_area(10) rect_area(10)
``` ```
   
%% Output %% Output
   
20 20
   
%% Cell type:markdown id:1ba9eb50 tags: %% Cell type:markdown id:1ba9eb50 tags:
   
### Review 2: Indentation ### Review 2: Indentation
   
What is the output of the below code? What is the output of the below code?
- vertical blank space does not matter - vertical blank space does not matter
- Python only cares about indentation to identify function definition lines of code - Python only cares about indentation to identify function definition lines of code
   
%% Cell type:code id:19e9fbf6 tags: %% Cell type:code id:19e9fbf6 tags:
   
``` python ``` python
print("A") print("A")
print("B") print("B")
   
def print_letters(): def print_letters():
print("C") print("C")
   
   
print("D") print("D")
   
print("E") print("E")
print("F") print("F")
   
print_letters() print_letters()
``` ```
   
%% Output %% Output
   
A A
B B
E E
F F
C C
D D
   
%% Cell type:markdown id:45be75af tags: %% Cell type:markdown id:45be75af tags:
   
### Review 3: Argument passing ### Review 3: Argument passing
   
What is the output of the below code? What is the output of the below code?
   
%% Cell type:code id:55244dd8 tags: %% Cell type:code id:55244dd8 tags:
   
``` python ``` python
def h(x=1, y=2): def h(x=1, y=2):
print(x, y) # what is printed? print(x, y) # what is printed?
   
def g(x, y): def g(x, y):
print(x, y) # what is printed? print(x, y) # what is printed?
h(y) h(y)
   
def f(x, y): def f(x, y):
print(x, y) # what is printed? print(x, y) # what is printed?
g(x=x, y=y+1) g(x=x, y=y+1)
   
x = 10 x = 10
y = 20 y = 20
f(y, x) f(y, x)
``` ```
   
%% Output %% Output
   
20 10 20 10
20 11 20 11
11 2 11 2
   
%% Cell type:markdown id:9f23b102 tags: %% Cell type:markdown id:9f23b102 tags:
   
## Learing Objectives ## Learing Objectives
   
- Write conditional statements - Write conditional statements
- using conditional execution (if) - using conditional execution (if)
- using alternate execution (if/else) - using alternate execution (if/else)
- using chained conditionals (if/elif/elif/…/else) - using chained conditionals (if/elif/elif/…/else)
   
- Identify code blocks (indentation layers) in a program - Identify code blocks (indentation layers) in a program
- count the number of blocks in a segment of code - count the number of blocks in a segment of code
   
- Determine the output of code with conditional statements - Determine the output of code with conditional statements
   
%% Cell type:markdown id:424fa9f4 tags: %% Cell type:markdown id:424fa9f4 tags:
   
<div> <div>
<img src="attachment:Condition_flow_chart.png" width="600"/> <img src="attachment:Condition_flow_chart.png" width="600"/>
</div> </div>
   
%% Cell type:markdown id:7f821152 tags: %% Cell type:markdown id:7f821152 tags:
   
### Terminology ### Terminology
   
- conditional - conditional
- condition - condition
- conditional execution - conditional execution
- alternate execution - alternate execution
- branches (also known as "Paths of execution") - branches (also known as "Paths of execution")
   
<div> <div>
<img src="attachment:Conditional_terminology.png" width="600"/> <img src="attachment:Conditional_terminology.png" width="600"/>
</div> </div>
   
%% Cell type:markdown id:2035b7e1 tags: %% Cell type:markdown id:2035b7e1 tags:
   
<div> <div>
<img src="attachment:Branch1.png" width="600"/> <img src="attachment:Branch1.png" width="600"/>
</div> </div>
   
%% Cell type:markdown id:7b0116a8 tags: %% Cell type:markdown id:7b0116a8 tags:
   
<div> <div>
<img src="attachment:Branch2.png" width="600"/> <img src="attachment:Branch2.png" width="600"/>
</div> </div>
   
%% Cell type:markdown id:927debdc tags: %% Cell type:markdown id:927debdc tags:
   
### Python code for the below flowchart ### Python code for the below flowchart
   
<div> <div>
<img src="attachment:updated_flowchart.png" width="400"/> <img src="attachment:updated_flowchart.png" width="400"/>
</div> </div>
   
%% Cell type:code id:774ea61f tags: %% Cell type:code id:774ea61f tags:
   
``` python ``` python
x = input("enter x: ") x = input("enter x: ")
x = int(x) x = int(x)
   
if x % 2 == 0: # condition if x % 2 == 0: # condition
# conditional execution # conditional execution
print("it’s even") print("it’s even")
print("we wanted odd") print("we wanted odd")
else: else:
# alternate execution # alternate execution
print("it’s odd") print("it’s odd")
print("good!") print("good!")
   
print("thank you") print("thank you")
print("all done") print("all done")
``` ```
   
%% Output %% Output
   
enter x: 12 enter x: 12
it’s even it’s even
we wanted odd we wanted odd
thank you thank you
all done all done
   
%% Cell type:markdown id:a5935b5d tags: %% Cell type:markdown id:a5935b5d tags:
   
### Example 0: Classify English words as "short" ### Example 0: Classify English words as "short"
   
- TODO: discuss what number can be filled into the below blank - TODO: discuss what number can be filled into the below blank
- A word in English is "short" if it has \_\_\_5_\_\_ letters or less otherwise it is "long" - A word in English is "short" if it has \_\_\_5_\_\_ letters or less otherwise it is "long"
   
%% Cell type:code id:99f93d73 tags: %% Cell type:code id:99f93d73 tags:
   
``` python ``` python
# TODO: initialize word with some short word # TODO: initialize word with some short word
word = "snow" word = "snow"
   
# TODO: compute length of word # TODO: compute length of word
word_length = len(word) word_length = len(word)
   
# Now let's write our first conditional for short words # Now let's write our first conditional for short words
if word_length <= 5: if word_length <= 5:
print(word, "is short") print(word, "is short")
print("short words are fun") print("short words are fun")
``` ```
   
%% Output %% Output
   
snow is short snow is short
short words are fun short words are fun
   
%% Cell type:code id:97a0e006 tags: %% Cell type:code id:97a0e006 tags:
   
``` python ``` python
# TODO: initialize word with some long word # TODO: initialize word with some long word
word = "spectacular" word = "spectacular"
   
# TODO: compute length of word # TODO: compute length of word
word_length = len(word) word_length = len(word)
   
# TODO: write another conditional for long words # TODO: write another conditional for long words
if word_length > 5: if word_length > 5:
print(word, "is long") print(word, "is long")
print("long words are interesting") print("long words are interesting")
``` ```
   
%% Output %% Output
   
spectacular is long spectacular is long
long words are interesting long words are interesting
   
%% Cell type:markdown id:28d15336 tags: %% Cell type:markdown id:28d15336 tags:
   
## Example 0 (version 2): Classify English words as "short" or "long" ## Example 0 (version 2): Classify English words as "short" or "long"
   
- `if` block conditional execution - `if` block conditional execution
- `else` block alternate execution - `else` block alternate execution
   
%% Cell type:code id:dafc0074 tags: %% Cell type:code id:dafc0074 tags:
   
``` python ``` python
# TODO: initialize word with some short word # TODO: initialize word with some short word
word = "edify" word = "edify"
   
# TODO: compute length of word # TODO: compute length of word
word_length = len(word) word_length = len(word)
   
# Now let's write our first conditional for short / long words # Now let's write our first conditional for short / long words
if word_length <= 5: if word_length <= 5:
# conditional execution # conditional execution
print(word, "is short") print(word, "is short")
print("short words are fun") print("short words are fun")
else: else:
# alternate execution # alternate execution
print(word, "is long") print(word, "is long")
print("long words are interesting") print("long words are interesting")
   
# TODO: go back to line 2 and change word's initialization to a long word # TODO: go back to line 2 and change word's initialization to a long word
``` ```
   
%% Output %% Output
   
edify is short edify is short
short words are fun short words are fun
   
%% Cell type:markdown id:b14628c6 tags: %% Cell type:markdown id:b14628c6 tags:
   
## PythonTutor visualization ## PythonTutor visualization
   
- copy and paste the final version of example 0 into PythonTutor and step through the code, to solidify understanding of control flow - copy and paste the final version of example 0 into PythonTutor and step through the code, to solidify understanding of control flow
   
%% Cell type:markdown id:3dced4fd tags: %% Cell type:markdown id:3dced4fd tags:
   
<div> <div>
<img src="attachment:code_blocks.png" width="600"/> <img src="attachment:code_blocks.png" width="600"/>
</div> </div>
   
%% Cell type:markdown id:be10dae4 tags: %% Cell type:markdown id:be10dae4 tags:
   
### Identifying code blocks ### Identifying code blocks
   
- Step 1: look for a colon at end of a line - Step 1: look for a colon at end of a line
- Step 2: start drawing a line on next code line that is indented in - Step 2: start drawing a line on next code line that is indented in
- Step 3: continue down until you hit code that is less indented - Step 3: continue down until you hit code that is less indented
- Step 4: box off the code - Step 4: box off the code
- Step 5: look for the next colon to find more boxes and then repeat steps 1 to 4 - Step 5: look for the next colon to find more boxes and then repeat steps 1 to 4
   
<div> <div>
<img src="attachment:identified_code_blocks.png" width="400"/> <img src="attachment:identified_code_blocks.png" width="400"/>
</div> </div>
   
%% Cell type:markdown id:99706f6e tags: %% Cell type:markdown id:99706f6e tags:
   
## Worksheet problem 1 ## Worksheet problem 1
- let's do problem 1 in today's lecture worksheet - let's do problem 1 in today's lecture worksheet
   
%% Cell type:markdown id:97da9526 tags: %% Cell type:markdown id:97da9526 tags:
   
## Example 1: Classifying Children by Age ## Example 1: Classifying Children by Age
- does anyone know what is the age bound for "baby"? - does anyone know what is the age bound for "baby"?
- what about a "toddler"? - what about a "toddler"?
- Chained conditionals: - Chained conditionals:
- multiple branch within the same conditional - multiple branch within the same conditional
- connected conditions - connected conditions
- if conditional branch - if conditional branch
- elif subjective conditional branch(es) - elif subjective conditional branch(es)
- elif conditions are subjective to the if condition - elif conditions are subjective to the if condition
- that is, only when if condition evaluates to `False`, the next elif condition is evaluated - 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 - only when the first elif condition evaluates to `False`, the second elif condition is evaluated
- and so on ... - and so on ...
- else alternate branch - else alternate branch
   
%% Cell type:code id:b969d76d tags: %% Cell type:code id:b969d76d tags:
   
``` python ``` python
# TODO: get age as user input # TODO: get age as user input
# TODO: what is the default return type of input function call? # TODO: what is the default return type of input function call?
age = int(input("Enter your age: ")) age = int(input("Enter your age: "))
   
def categorize_age(age): def categorize_age(age):
if 0 <= age <= 1: if 0 <= age <= 1:
return "baby" return "baby"
elif 2 <= age <= 3: elif 2 <= age <= 3:
return "toddler" return "toddler"
elif 4 <= age <= 10: elif 4 <= age <= 10:
return "kid" return "kid"
elif 11 <= age <= 12: elif 11 <= age <= 12:
return "tween" return "tween"
elif 13 <= age <= 17: elif 13 <= age <= 17:
return "teen" return "teen"
else: else:
return "adult" return "adult"
   
print("You are a:", categorize_age(age)) print("You are a:", categorize_age(age))
``` ```
   
%% Output %% Output
   
Enter your age: 3 Enter your age: 3
You are a: toddler You are a: toddler
   
%% Cell type:markdown id:172ace46 tags: %% Cell type:markdown id:172ace46 tags:
   
## Example 2: Date Printer ## Example 2: Date Printer
- converts 2/11/2022 to "Feb 11th of ‘22" - converts 2/11/2022 to "Feb 11th of ‘22"
   
%% Cell type:code id:96709e36 tags: %% Cell type:code id:96709e36 tags:
   
``` python ``` python
def format_month(month): def format_month(month):
"""Convert a month (as an integer) into a string. """Convert a month (as an integer) into a string.
1 is Jan, 2 is Feb, etc.""" 1 is Jan, 2 is Feb, etc."""
if month == 1: if month == 1:
return "Jan" return "Jan"
elif month == 2: elif month == 2:
return "Feb" return "Feb"
elif month == 3: elif month == 3:
return "Mar" return "Mar"
elif month == 4: elif month == 4:
return "Apr" return "Apr"
elif month == 5: elif month == 5:
return "May" return "May"
elif month == 6: elif month == 6:
return "Jun" return "Jun"
elif month == 7: elif month == 7:
return "Jul" return "Jul"
elif month == 8: elif month == 8:
return "Aug" return "Aug"
elif month == 9: elif month == 9:
return "Sep" return "Sep"
elif month == 10: elif month == 10:
return "Oct" return "Oct"
elif month == 11: elif month == 11:
return "Nov" return "Nov"
elif month == 12: elif month == 12:
return "Dec" return "Dec"
else: else:
return "Invalid month!" return "Invalid month!"
``` ```
   
%% Cell type:code id:528f10f6 tags: %% Cell type:code id:528f10f6 tags:
   
``` python ``` python
def format_day(day): def format_day(day):
"""Covert a day into a date string with proper ending. """Covert a day into a date string with proper ending.
16 --> '16th', 23 --> '23rd', """ 16 --> '16th', 23 --> '23rd', """
suffix = "" suffix = ""
if day < 1: if day < 1:
suffix = "error" suffix = "error"
elif 11 <= day % 100 <= 20: elif 11 <= day % 100 <= 20:
suffix = str(day) + "th" suffix = str(day) + "th"
elif day % 10 == 1: elif day % 10 == 1:
suffix = str(day) + "st" suffix = str(day) + "st"
elif day % 10 == 2: elif day % 10 == 2:
suffix = str(day) + "nd" suffix = str(day) + "nd"
elif day % 10 == 3: elif day % 10 == 3:
suffix = str(day) + "rd" suffix = str(day) + "rd"
else: else:
suffix = str(day) + "th" suffix = str(day) + "th"
   
return suffix return suffix
   
print(format_day(1)) print(format_day(1))
print(format_day(2)) print(format_day(2))
print(format_day(3)) print(format_day(3))
print(format_day(11)) print(format_day(11))
print(format_day(21)) print(format_day(21))
print(format_day(111)) print(format_day(111))
print(format_day(-1)) print(format_day(-1))
``` ```
   
%% Output %% Output
   
1st 1st
2nd 2nd
3rd 3rd
11th 11th
21st 21st
111th 111th
error error
   
%% Cell type:code id:fd3a653d tags: %% Cell type:code id:fd3a653d tags:
   
``` python ``` python
def format_date(month, day, year): def format_date(month, day, year):
"""returns a string representing the date, such as Feb 11th of ‘22""" """returns a string representing the date, such as Feb 11th of ‘22"""
result_str = "" result_str = ""
result_str += format_month(month) result_str += format_month(month)
result_str += " " + format_day(day) result_str += " " + format_day(day)
result_str += " of '" + str(year % 100) result_str += " of '" + str(year % 100)
   
return result_str return result_str
``` ```
   
%% Cell type:code id:8ecd4d9d tags: %% Cell type:code id:8ecd4d9d tags:
   
``` python ``` python
format_date(9, 23, 2022) format_date(9, 23, 2022)
``` ```
   
%% Output %% Output
   
"Sep 23rd of '22" "Sep 23rd of '22"
   
%% Cell type:markdown id:cb4e6eb9 tags: %% Cell type:markdown id:cb4e6eb9 tags:
   
### Worksheet problem 2 ### Worksheet problem 2
- let's do problem 2 in today's lecture worksheet - let's do problem 2 in today's lecture worksheet
......
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