Back to Blog
Chief Idiot2 min read

Python 1.4: The Spells (Functions & Classes)

How to package your code so you can copy-paste it later. Intro to Functions ('def') and Classes.

Writing Your Grimoire

Up until now, you've been writing code script-style. Top to bottom. messy. But what if you want to use that "Smart Thermostat" logic again? Do you copy-paste it 50 times?

No. (Well, you could, but we can be lazier). You wrap it in a Function.

Python Functions Cookbook

1. The Function (def)

Think of this as a Magic Spell. You give it a name, and whenever you say that name, the magic happens.

def make_coffee(sugar_spoons):
    print("Grinding beans...")
    print("Adding water...")
    print("Adding " + str(sugar_spoons) + " spoons of sugar.")
    return "Delicious Coffee"

Now, whenever you want coffee:

my_cup = make_coffee(3)
# Output: Adding 3 spoons of sugar.

2. The Class (The Blueprint)

This is where people get scared. "Object Oriented Programming." Scary.

Forget that term. A Class is just a Blueprint. If you want to build a robot, you draw the blueprint once (The Class), and then you can build 100 robots from it (The Objects).

class IdiotRobot:
    def __init__(self, name):
        self.name = name
    
    def speak(self):
        print("Beep Boop. I am " + self.name)
 
# Building robots from the blueprint
robot_1 = IdiotRobot("Steve")
robot_2 = IdiotRobot("Karen")
 
robot_1.speak() # Beep Boop. I am Steve
robot_2.speak() # Beep Boop. I am Karen

When to use what?

  • Use a Function when you want to DO something (an action).
  • Use a Class when you want to MODEL something (a thing with state).

Graduation

Congratulations. You now know:

  1. Variables (Boxes)
  2. Loops (Chores)
  3. Functions (Spells)

You officially know more Python than 90% of LinkedIn "Thought Leaders." Go build something stupid.

Share this article