← Back to Blog

Your first function

The problem...

You've written the same block of code more than once. Same logic. Different place. Copy. Paste. Repeat.

Every time something changes — you update it in one place and forget to update it in the others.

There's a better way.

The idea!

A function is a named block of code. You define it once. You call it by name whenever you need it. The code runs — without you writing it again.

The syntax

def function_name():
    # code goes here

def tells Python you're defining a function. The name is yours to choose. The colon and indentation — same rules as always.

Your first function

def greet():
    print("Hello, Bull.")
    print("Welcome to TheRedHorn.")

This defines the function. Nothing runs yet. You've just given the block a name.

Calling a function

greet()

That's it. The function name followed by parentheses. Python finds the function, runs everything inside it, and returns.

Define once. Call many times.

def greet():
    print("Hello, Bull.")
    print("Welcome to TheRedHorn.")

greet()
greet()
greet()
# Hello, Bull.
# Welcome to TheRedHorn.
# Hello, Bull.
# Welcome to TheRedHorn.
# Hello, Bull.
# Welcome to TheRedHorn.

Three calls. Six lines of output. One function definition. That's the power.

Functions can use everything you know

def count_vowels():
    word = input("Enter a word: ")
    count = 0
    for letter in word:
        if letter.lower() in "aeiou":
            count += 1
    print(f"Vowels found: {count}")

A loop. A counter. An if. All inside a function. Call it once — it does everything.

Heads up!

  • Define the function before you call it — Python reads top to bottom
  • def line ends with : — same rule as always
  • The function body is indented — 4 spaces
  • Parentheses are required — both when defining and when calling
  • Defining a function doesn't run it — calling it does

The mindset shift

Stop thinking: "I'll write this code where I need it."

Start thinking: "I'll write this code once, give it a name, and call it wherever I need it."

What you should understand now

  • def defines a function — it doesn't run it
  • Call a function by writing its name followed by ()
  • A function runs every time it's called — as many times as you need
  • Everything you've learned works inside a function
[ login to bookmark ] // copied! 25 views · 1 min
// resources
Code Example def_function.py
← prev This is where it all starts to make sense next → DEF Mini Project — Banner
// 0 comments
// No comments yet. Be the first.
// leave a comment

// Your comment will appear after approval.