âš™ī¸ Day 4: Functions

Writing Reusable Code

📚 What You'll Learn Today

Functions are one of the most powerful concepts in programming:

âš™ī¸ What is a Function?

A function is a reusable block of code that does a specific task. Instead of writing the same code over and over, you can put it in a function and call it when needed.

💡 Analogy: Think of a function like a recipe. You write the recipe once (define the function), and then you can follow it anytime you need it (call the function).

Why Use Functions?

📝 Defining a Function

Use the def keyword to create a function:

Basic Syntax:

def function_name(): # Code inside the function print("Hello!")

Calling a Function:

def greet(): print("Hello!") # Call the function greet() greet() greet()
Hello! Hello! Hello!

đŸ“Ĩ Parameters and Arguments

Functions can accept input values called parameters:

Function with Parameter:

def greet(name): print("Hello, " + name + "!") greet("Alex") greet("Jordan") greet("Taylor")
Hello, Alex! Hello, Jordan! Hello, Taylor!

Multiple Parameters:

def add(a, b): print(a + b) add(5, 3) add(10, 20) add(-1, 1)
8 30 0

â†Šī¸ Return Values

Functions can send back a value using return:

Basic Return:

def add(a, b): return a + b result = add(5, 3) print(result)
8

Using Return in Conditionals:

def is_adult(age): if age >= 18: return True else: return False if is_adult(25): print("Can vote!") if is_adult(16): print("Can vote!") else: print("Cannot vote yet.")
Can vote! Cannot vote yet.

📋 Default Parameters

Give parameters default values that get used if no argument is provided:

With Default Values:

def greet(name, greeting="Hello"): print(greeting + ", " + name + "!") greet("Alex") # Uses default greeting greet("Jordan", "Hi") # Uses custom greeting greet("Taylor", "Welcome") # Uses custom greeting
Hello, Alex! Hi, Jordan! Welcome, Taylor!
âš ī¸ Important: Parameters with default values must come AFTER parameters without defaults.

🔄 Scope

Variables inside a function are local - they don't affect variables outside:

def double(x): x = x * 2 print("Inside function:", x) number = 5 double(number) print("Outside function:", number)
Inside function: 10 Outside function: 5

đŸ‹ī¸ Exercise: Calculator Function

Create a calculator function that performs basic operations:

# Create a function called calculate # It should take three parameters: num1, operation, num2 # operation can be: "+", "-", "*", "/" # Return the result # Example: # calculate(10, "+", 5) should return 15 # calculate(10, "*", 5) should return 50

Bonus Challenge:

Handle division by zero and return "Cannot divide by zero!"

# Example solution: def calculate(num1, operation, num2): if operation == "+": return num1 + num2 elif operation == "-": return num1 - num2 elif operation == "*": return num1 * num2 elif operation == "/": if num2 == 0: return "Cannot divide by zero!" return num1 / num2 else: return "Invalid operation" print(calculate(10, "+", 5)) # 15 print(calculate(10, "/", 0)) # Error message

✅ Key Takeaways

🎉 Ready for Day 5?

Tomorrow you'll learn about Lists and Dictionaries - storing collections of data!

Marking complete will unlock Day 5!