"- Found an error on a quiz? -- Create a private post on Piazza to the instructors. We will review and may correct and regrade the quiz:\n",
"- **Extra Credit** -- Early Submission working, Lab Attendance -- all setup for p4 onward. The system is fragile -- will need to run manually about once a week. If lab attendance EC is missed, please let me know. Processed lab attendance for lab-p1. Still need to run for lab-p2. \n",
"- **Found an error on a quiz?** -- Create a private post on Piazza to the instructors. We will review and may correct and regrade the quiz:\n",
- Found an error on a quiz? -- Create a private post on Piazza to the instructors. We will review and may correct and regrade the quiz:
-**Extra Credit** -- Early Submission working, Lab Attendance -- all setup for p4 onward. The system is fragile -- will need to run manually about once a week. If lab attendance EC is missed, please let me know. Processed lab attendance for lab-p1. Still need to run for lab-p2.
-**Found an error on a quiz?** -- Create a private post on Piazza to the instructors. We will review and may correct and regrade the quiz:
# Create a function that works with the calls to the function at the bottom of this cell.
# Note: To calculate an interest-only payment, multiply the loan balance by the annual interest rate,
# and divide by the number of payments in a year.
# TODO: Create Function Here
# Function Calls that should work:
# passing arguments by position
print(interest_only_payment(50000,0.04,12))# should return approx. $166.66
# passing arguments by keyword
print(interest_only_payment(rate=0.04,num_payments=12,balance=50000))# should also return approx. $166.66
# Using default values
print(interest_only_payment())# should also return approx. $166.66
```
%% Cell type:code id: tags:
``` python
# Warmup 2 -- Calling Functions
deftriangle_number(n=1):
"""
Calculates and returns the n-th triangle number.
The formula for the n-th triangle number is (n^2+n)/2
A triangle number is a value where you can organize that number of items into a triangle
starting with a row with 1 item and each successive row has one more than the previous.
The first 5 triangle numbers are 1, 3, 6, 10, 15
"""
n=int(n)
ans=int(n*(n+1)/2)
returnans
deftriangle_sum(n=1,m=2):
"""
Calculates and returns the sum of two triangle numbers.
"""
ans=triangle_number(n)+triangle_number(m)
returnans
# TODO: Write and print the output of function calls to the triangle_sum function
# print out sum of call to triangle_sum using only default arguments
# print out sum of call to triangle_sum using only positional arguments
# print out sum of call to triangle_sum using only keyword arguments
# print out sum of call to triangle_sum using a mix of default, positional and/or keyword arguments
```
%% Cell type:markdown id: tags:
Warmup 3 --Trace the following code Using the debugger or Python Tutor. At any point as the program executes, you should be able to state what line of code will execute next and what the output will be.
Warmup 4 -- Let's make some changes to it! [link](https://pythontutor.com/visualize.html#code=x%20%3D%20100%0A%0Adef%20f%28%29%3A%0A%20%20%20%20x%20%3D%201%0A%20%20%20%20print%28x%29%0A%20%20%20%20g%28%29%0A%0Adef%20g%28%29%3A%0A%20%20%20%20x%20%3D%202%0A%20%20%20%20print%28x%29%0A%20%20%20%20h%28%29%0A%0Adef%20h%28%29%3A%0A%20%20%20%20print%28x%29%0A%0Af%28%29&cumulative=false&curInstr=0&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=3&rawInputLstJSON=%5B%5D&textReferences=false)
Python has two scopes -- global and local. The callstack stores variables in frames. When executing a line of code, the variables in the current local scope and global scope are accessible.
Some Lessons on executing Functions:
1. Functions don't execute unless they are called
2. Variables created in a function die after function returns
3. Variables start fresh every time a function is called again
4. You can't see the variables of other function invocations, even those that call you
5. You can generally just use global variables inside a function
6. If you do an assignment to a variable in a function, Python assumes you want it local
7. Assignment to a variable should be before its use in a function, even if there's a a global variable with the same name
8. Use a global declaration to prevent Python from creating a local variable when you want a global variable
9. In Python, arguments are "passed by value", meaning reassignments to a parameter don't change the argument outside
10. It's irrelevant whether the argument (outside) and parameter (inside) have the same variable name
%% Cell type:markdown id: tags:
# Conditionals 1
## Reading
*[Downey Ch 5 ("Floor Division and Modulus" to "Nested Conditionals" and "Keyboard Input" to end)](https://greenteapress.com/thinkpython2/html/thinkpython2006.html)
*[Downey Ch 6 ("Return Values" to "Boolean Functions")](https://greenteapress.com/thinkpython2/html/thinkpython2007.html)
*[Python for Everybody, 4.1 - 4.5](https://runestone.academy/ns/books/published//py4e-int/conditional/toctree.html)
## Learning Objectives
After this lecture you will be able to...
- write conditional statements
- using conditional execution ( if )
- using alternate execution (if/else)
- using chained conditionals (if/elif/elif/…/else)
- identify code blocks (indentation layers) in a program
- count the number of blocks in a segment of code
- determine the output of code with conditional statements
%% Cell type:markdown id: tags:
## if statement Syntax:
An if statement has the form:
```python
ifcondition:
#block of code to run if condition is true
```
The `condition` portion is an expression that evaluates to `True` or `False`. If the condition evaluates to True
then the indented block of code is executed. If it is false then the indented block of code is skipped.
### Example usage
%% Cell type:code id: tags:
``` python
# Determine if a word is short or not.
# If it is short, say "Word is short" <= 5 characters
# If it is long, say "Word is long"
word="hello"
word_length=len(word)
ifword_length<=5:
print("Word is short")
ifword_length>5:
print("Word is long")
```
%% Output
Word is short
%% Cell type:markdown id: tags:
### You Try
In the cell below print "even" if the inputed value is even
%% Cell type:code id: tags:
``` python
num=int(input("Enter an integer number"))
##TODO write an if statement that prints "even" if num is holding an even value
```
%% Cell type:markdown id: tags:
## if-else statement Syntax
An if-else statement has the form:
```python
ifcondition:
# block of code to run if condition is true
else:
# block of code to run if condition is false
```
The `condition` portion is an expression that evaluates to `True` or `False`. If the condition evaluates to True then the first indented block of code is executed. If it is false then the indented block of code after the `else:` is executed.
### Example usage
Bob runs a community bakery. Every day, he recieves a shipment of dough balls, each of which bakes 4 loaves of bread, and he evenly splits the bread among his customers. Some days he may recieve 10 customers, some days 20 customers, and some days none at all!
Below is the code that tells Bob how much bread he gave to each customer.
%% Cell type:code id: tags:
``` python
balls_of_dough=int(input("How many balls of dough did we recieve? "))
num_customers=int(input("How many customers were there? "))
bread_baked=balls_of_dough*4
# If statement to avoid the zero division runtime error
ifnum_customers==0:
print("Sorry! No one showed up. All the bread went to waste.")
else:
bread_per_customer=bread_baked/num_customers
print("Each customer gets",round(bread_per_customer,2),"loaves of bread.")
```
%% Output
How many balls of dough did we recieve? 4
How many customers were there? 4
Each customer gets 4.0 loaves of bread.
%% Cell type:markdown id: tags:
### You Try
In the cell below write an if-else statement that prints "you may enter" or "entry denied" depending
on the value in the `password` variable. The correct value for entry is **CatNipFOREVER**.
%% Cell type:code id: tags:
``` python
fromgetpassimportgetpass
password=getpass("Enter Password:")
##TODO write an if-else statement that prints "you may enter" or "entry denied" if they entered
# the proper password (i.e. if password refers to the value "CatNipFOREVER")
```
%% Output
Enter Password: ········
hello
%% Cell type:markdown id: tags:
## if-elif statement syntax
An if-elif statment has the form:
```python
ifcondition1:
# code block 1
elifcondition2:
# code block 2
elifcondition3:
# code block 3
...
elifconditionN:
# code block N
else:(thisfinalelseportionisoptional)
# code block N+1
```
If `condition 1` evaluates to `True` then code block 1 is executed. If it is false then `condition2` is evaluated. If it is `True` then code block 2 is executed. If it is false then `condition3` is evaluated. If it is true then code block 3 is executed. This process continues until the final condition (`conditionN`). If it is true then code block N is executed. If it is false then code block N+1 is executed (if present).
Notice that <u>**only one** code block will be executed and if the final else portion is included then **exactly one** code block will be executed.</u>
### Example Usage
**Age Categorizer**
Assume `age` is an int parameter of the `categorize_age()` function, which categorizes the person's age.
All the following bounds are inclusive (meaning you should include both ends)
- Return "Baby" if between ages of 0 and 1
- Return "Toddler" if between ages of 2 and 4
- Return "Child" if between ages of 5 and 17
- Return "Adult" if between ages of 18 and 64
- Return "Senior" if between ages of 65 and 125
- Return "Not a valid age" for all other ages.
%% Cell type:code id: tags:
``` python
defcategorize_age(age):
ifage<0:
return"N/A"
elifage<=1:
return"Baby"
elifage<=4:
return"Toddler"
elifage<=17:
return"Child"
elifage<=64:
return"Adult"
elifage<=125:
return"Senior"
elifage>125:
return"N/A"
# This is a lot of tests! Let's try them incrementally.
print(categorize_age(-2))
```
%% Output
N/A
%% Cell type:markdown id: tags:
Watch the code run in the [PythonTutor](https://pythontutor.com/visualize.html#code=def%20categorize_age%28age%29%3A%0A%20%20%20%20if%20age%20%3C%200%3A%0A%20%20%20%20%20%20%20%20return%20%22N/A%22%0A%20%20%20%20elif%20age%20%3C%3D%201%3A%0A%20%20%20%20%20%20%20%20return%20%22Baby%22%0A%20%20%20%20elif%20age%20%3C%3D%204%3A%0A%20%20%20%20%20%20%20%20return%20%22Toddler%22%0A%20%20%20%20elif%20age%20%3C%3D%2017%3A%0A%20%20%20%20%20%20%20%20return%20%22Child%22%0A%20%20%20%20elif%20age%20%3C%3D%2064%3A%0A%20%20%20%20%20%20%20%20return%20%22Adult%22%0A%20%20%20%20elif%20age%20%3C%3D%20125%3A%0A%20%20%20%20%20%20%20%20return%20%22Senior%22%0A%20%20%20%20elif%20age%20%3E%20125%3A%0A%20%20%20%20%20%20%20%20return%20%22N/A%22%0A%0Aprint%28categorize_age%28-2%29%29&cumulative=false&heapPrimitives=nevernest&mode=edit&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false). Notice that the conditions are evaulated one after the other until a condition is found which is true and then that code block is the one that is executed.
%% Cell type:markdown id: tags:
### You Try
In the cell below finish writing the `calculate_letter_grade()` function. The input to the function is a percentage (float) and the return value should be a letter grade following these rules:
-\>= 93 - A
-\>= 88 - AB
-\>= 80 - B
-\>= 75 - BC
-\>= 70 - C
-\>= 60 - D
- anything else - F
%% Cell type:code id: tags:
``` python
##TODO finish the calculate_letter_grade() function
defcalculate_letter_grade(percentage):
"""returns the letter grade for the provided course percentage"""
pass
# Should work with the following function call. Try different values
print(calculate_letter_grade(86.5))
```
%% Cell type:markdown id: tags:
## Practice
Let's work through computing a string representation of a date given the year, month, and day.
### Date Printer
See the requirements below. We will first break down the problem into smaller problems and right a function for each.