Warmup

Create a string and then print the last letter of the string using negative indexing

Agenda

  • Unit 3 Exam
  • Lesson 4.1

Notes on exam

  • 2 questions have 0 points: one on list.extend(), and the other on list.copy()

Lesson 4.1 – Why Functions?

What is a Function?

  • A reusable block of code
  • Performs a specific task
  • Can be called many times

Why Use Functions?

  • Avoid repeating code
  • Make programs easier to read
  • Easier to debug and test
  • Organize big problems into smaller steps

Example: Without Functions

print("Hello, Alice!")
print("Hello, Bob!")
print("Hello, Charlie!")

Example: With a Function

def say_hello(name):
    print("Hello,", name)

say_hello("Alice")
say_hello("Bob")
say_hello("Charlie")

Question: Which version is easier to extend?

Function Basics

  • Defined with def
  • Has a name
  • May take parameters
  • May return a value

Defining a Function

def greet():
    print("Hello, world!")
  • def starts the function
  • greet is the function name
  • No parameters in this example

Calling a Function

greet()
greet()

Output:

Hello, world!
Hello, world!

"Pure" functions

  • Ideally, you want functions that don't have side effects and will always have the same return value for any given value passed in
  • This is called "idempotency" and functions that have this property are called "pure" functions
  • In reality, not always practical, but the key is you want to be careful about documenting behavior that isn't "pure".

Example

def greet(name):
	return "Hello " + name "!"

Testing your functions

We can use the assert statement to test functions.

def greet(name):
	return "Hello " + name "!"

res = greet("Bob")
expected = "Hello Bob!"
assert res == expected, res

Practice Question

What happens if you define a function but never call it?

Real-Life Analogy

  • Function = A recipe
  • Defining = Writing the recipe down
  • Calling = Actually cooking the meal

Key Takeaways

  • Functions let us reuse code
  • def keyword defines a function
  • Call functions by writing their name + ()
  • Functions make programs simpler and cleaner

Tips

  • "Pure" functions preferred over those with "side effects"
    • For example, instead of printing in the function, return a string
  • Think about the functions required inputs (parameters) and outputs (return values) first, then worry about the implementation