September 19: Functions
Learning Objectives
After today's class, you should be able to:
- Explain the flow of execution from one function to another.
- Describe the syntax of function definitions and function calls.
- Write short functions that have parameters and return values.
Lesson Outline¶
Class Activity: 20 min
Mini Lecture: 20 min
Recap of Return Examples 5min
# Example 1: No return statement
def greeting():
print("Have a nice day!\n")
# Example 2: One return statement
def time_str(hour, minute):
if hour < 12:
ampm = "AM"
else:
ampm = "PM"
hour -= 12
if hour == 0:
hour = 12
return f"{hour}:{minute:02d} {ampm}"
# Example 3: Multiple return statements
def analyze(number):
if number == 0:
return "Zero!"
if number > 0:
return "Positive"
return "Negative"
# Example 4: Multiple return values
def stats(grades):
avg = sum(grades) / len(grades)
return min(grades), avg, max(grades)
if __name__ == "__main__":
print("1:", greeting())
print("2:", time_str(12, 5))
print("3:", analyze(-1))
print("4:", stats([95, 71, 100, 88]))
Your To-Do List¶
Due Wednesday September 20th at 11pm
Prepare for Quiz 2A
- Thursday, beginning of class, 25 minutes, in EnGeo 2204.
- Two parts: concepts and programming (will use lab machine account, canvas and gradescope)
- Study chapters 3 and 4: both reading and activities
- Review class activities
- Review homework programming assignments