Beginner Level • Lesson 4

📦 Functions and Organization

⏱️ 45 minutes 📚 Beginner 🎯 Code Organization
📦

Functions and Organization

Learn how to organize your code into reusable blocks called functions - this makes your programs cleaner and easier to understand!

What are Functions?

Functions are like recipes - they're blocks of code that do a specific job. Once you write a function, you can use it over and over again without rewriting the code!

💡 Real-World Example: Think of a function like a button on a remote control. You press "volume up" and it does the same thing every time. Functions work the same way - you call them and they do their job!

Creating Your First Function

To create a function in Python, you use the def keyword (short for "define"). Here's the basic structure:

Basic Function

def say_hello(): print("Hello!") print("Welcome to Python!") # Call the function say_hello()

What happens:

  • def say_hello(): - This defines (creates) a function named "say_hello"
  • The code inside is indented - this is the function's "body"
  • say_hello() - This calls (runs) the function

Functions with Parameters

Functions can take inputs called "parameters". This makes them more flexible and useful!

Function with Parameters

def greet(name): print("Hello,", name) print("Nice to meet you!") # Call the function with different names greet("Ali") greet("Siti") greet("Ahmad")

What happens: The function takes a name as input and uses it in the message. You can call it with different names!

Functions that Return Values

Functions can also give you back a result using the return keyword.

Function that Returns a Value

def add_numbers(a, b): result = a + b return result # Use the function sum = add_numbers(5, 3) print("The sum is:", sum)

Output: The sum is: 8

Why Use Functions?

♻️

Reusability

Write once, use many times

📖

Readability

Makes code easier to understand

🔧

Maintainability

Fix bugs in one place, not everywhere

🧩

Organization

Breaks big problems into small pieces

Project: Multi-Function LED Controller

Let's create a program with multiple functions to control LEDs in different ways!

Materials Needed:

  • Raspberry Pi
  • 3 LEDs (different colors)
  • 3 Resistors (220Ω each)
  • Breadboard and jumper wires

Wiring Instructions:

  1. Red LED: Connect to GPIO 18
  2. Green LED: Connect to GPIO 23
  3. Blue LED: Connect to GPIO 24
  4. Connect all short legs to GND via resistors

The Code with Functions:

import RPi.GPIO as GPIO import time # Set up GPIO GPIO.setmode(GPIO.BCM) GPIO.setup(18, GPIO.OUT) # Red LED GPIO.setup(23, GPIO.OUT) # Green LED GPIO.setup(24, GPIO.OUT) # Blue LED # Function to turn on a specific LED def turn_on_led(pin): GPIO.output(pin, GPIO.HIGH) print("LED on pin", pin, "is ON") # Function to turn off a specific LED def turn_off_led(pin): GPIO.output(pin, GPIO.LOW) print("LED on pin", pin, "is OFF") # Function to blink an LED def blink_led(pin, times, delay): for i in range(times): turn_on_led(pin) time.sleep(delay) turn_off_led(pin) time.sleep(delay) # Function to turn off all LEDs def all_off(): turn_off_led(18) turn_off_led(23) turn_off_led(24) try: # Use the functions print("Blinking red LED 3 times...") blink_led(18, 3, 0.5) time.sleep(1) print("Blinking green LED 5 times...") blink_led(23, 5, 0.3) time.sleep(1) print("Blinking blue LED 2 times...") blink_led(24, 2, 0.7) all_off() print("All LEDs off!") except KeyboardInterrupt: all_off() GPIO.cleanup()

Understanding the Code:

  • turn_on_led(pin): A function that turns on any LED by its pin number
  • turn_off_led(pin): A function that turns off any LED
  • blink_led(pin, times, delay): A function that blinks an LED a specific number of times with a specific delay
  • all_off(): A function that turns off all LEDs at once
  • By using functions, the code is much cleaner and easier to understand!

Organizing Your Code

Good code organization makes your programs easier to read and maintain. Here are some tips:

1️⃣

Group Related Functions

Put functions that do similar things together

2️⃣

Use Clear Names

Function names should describe what they do

3️⃣

Add Comments

Explain what your functions do

Common Mistakes to Avoid

⚠️ Watch Out For:

  • Missing Colon: Don't forget the colon (:) after def
  • Wrong Indentation: Code inside functions must be indented
  • Not Calling the Function: Defining a function doesn't run it - you must call it!
  • Wrong Parameter Count: Make sure you pass the right number of parameters
  • Forgetting Return: If you want a function to give back a value, use return

Summary

You've learned:

  • ✅ Functions are reusable blocks of code
  • ✅ Use def to define (create) a function
  • ✅ Functions can take parameters (inputs) to make them flexible
  • ✅ Functions can return values using return
  • ✅ Functions make code reusable, readable, and organized
  • ✅ Good code organization makes programs easier to understand and fix
🎉 Congratulations! You've completed the Beginner Level! You now know the fundamentals of programming: variables, conditionals, loops, and functions. In the next level, you'll learn to integrate sensors, displays, and motors!

🎮 Try It: Practice with Functions!

Practice writing functions. Try these challenges:

📝 Challenge 1: Simple Function

Write a function called say_goodbye() that prints "Goodbye!" and "See you later!":

📝 Challenge 2: Function with Parameter

Write a function called multiply() that takes two numbers and prints their product:

📝 Challenge 3: Function that Returns

Write a function called calculate_area() that takes length and width, and returns the area of a rectangle:

💡 Tip: Remember to use def to define functions, add parameters in parentheses, and use return if you want the function to give back a value!

🎯 Activity: Multi-Function LED Controller

What You'll Build:

Create a program with multiple functions to control LEDs in different ways!

Step-by-Step Instructions:

  1. Set Up Hardware: Connect 3 LEDs to GPIO pins 18, 23, and 24
  2. Create Functions: Write functions to turn LEDs on, off, and blink them
  3. Test Each Function: Call each function individually to make sure they work
  4. Combine Functions: Create a sequence that uses multiple functions together
  5. Add More Functions: Create a function that makes all LEDs blink in sequence

Function Ideas:

  • turn_on(pin) - Turn on a specific LED
  • turn_off(pin) - Turn off a specific LED
  • blink(pin, times) - Blink an LED a number of times
  • all_on() - Turn on all LEDs
  • all_off() - Turn off all LEDs
  • chase_effect() - Make LEDs light up in sequence
🏆 Bonus Challenge: Create a function called traffic_light() that simulates a traffic light: red on for 3 seconds, yellow for 1 second, green for 3 seconds, then repeats!

💪 Practice Challenges

Challenge 1: Calculator Functions

Create four functions: add(), subtract(), multiply(), and divide(). Each should take two numbers and return the result:

# Example: def add(a, b): return a + b def subtract(a, b): return a - b # Test them print(add(10, 5)) # Should print 15 print(subtract(10, 5)) # Should print 5

Challenge 2: LED Helper Functions

Create helper functions for LED control:

  • setup_leds() - Sets up all GPIO pins for LEDs
  • cleanup_leds() - Cleans up all GPIO pins
  • blink_all(times) - Blinks all LEDs together

Challenge 3: Function with Multiple Parameters

Write a function create_pattern() that takes LED pin, number of blinks, and delay time:

def create_pattern(pin, blinks, delay): for i in range(blinks): GPIO.output(pin, GPIO.HIGH) time.sleep(delay) GPIO.output(pin, GPIO.LOW) time.sleep(delay) # Use it create_pattern(18, 5, 0.3)

Challenge 4: Code Detective

What's wrong with this function? Find and fix the mistakes!

def greet name print("Hello", name) greet("Ali")
Click to see the answer
def greet(name): # Fixed: add parentheses and colon print("Hello", name) greet("Ali")

Challenge 5: Organize Your Code

Take your LED blinking code from previous lessons and reorganize it using functions:

  • Create a function for setup
  • Create functions for different blinking patterns
  • Create a function for cleanup
  • Call all functions in the main program