Kahibaro
Discord Login Register

Defining functions

Understanding Function Definitions

In this chapter, you’ll focus on how to define functions in Python: the exact syntax, where to put things, and what happens when Python reads a function definition.

You already know what functions are and why they matter from the parent chapter. Here, you’ll learn how to write your own.


The Basic Function Definition Syntax

A function definition in Python has this general form:

def function_name(parameters):
    # function body
    # do something

Let’s break that down:

A very simple function with no parameters and no return yet:

def say_hello():
    print("Hello!")

This code defines the function. It does not run print("Hello!") until you call:

say_hello()

Function Names

Function names follow the same rules as variable names:

Common style (PEP 8):

Examples of good names:

Examples of invalid names:

Indentation Inside Functions

The function body must be indented consistently. Everything that is part of the function goes one level in (usually 4 spaces):

def greet():
    print("Hello")
    print("Welcome to the program")
print("This is outside the function.")

Here:

If you forget indentation, you’ll get an IndentationError:

def greet():
print("Hello")  # ❌ wrong: not indented

When the Function Body Runs

Defining a function sets it up in memory. The body runs only when you call the function.

def show_message():
    print("I am inside the function")
# At this point, nothing has been printed yet
show_message()  # Now the function body runs
show_message()  # It runs again

Output:

I am inside the function
I am inside the function

Remember:

Functions with and without Parameters (Overview Only)

The detailed meaning of parameters and arguments is in the next chapter. For now, just see how they appear in definitions.

No parameters:

def say_hi():
    print("Hi!")

One parameter:

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

Multiple parameters:

def add(a, b):
    print(a + b)

We’ll explore what these parameters really are and how arguments work in the next section of the course. Here, focus on recognizing them as part of the function definition syntax.


Functions That Do Nothing (Yet): `pass`

Sometimes you want to declare a function now and fill it in later. Python does not allow an empty function body, but you can use pass as a placeholder:

def todo_feature():
    pass  # I will implement this later

pass tells Python: “There’s no code here yet, but this is valid.”


Docstrings: Adding Basic Documentation

You can add a short description inside your function using a docstring. This is a string placed immediately after the function header:

def greet():
    """Prints a friendly greeting."""
    print("Hello there!")

Key points:

Another example with parameters:

def add(a, b):
    """Print the sum of a and b."""
    print(a + b)

Calling a Function vs Defining It

It’s important to see the difference between defining and calling.

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

If you only define a function and never call it, it will never run.

Example:

def example():
    print("This is the example function")
# No call here, so no output

If you add a call:

def example():
    print("This is the example function")
example()

Now it prints the message.


Order of Code: Define Before You Call

Python reads your file from top to bottom. A function must be defined before the first time it is called.

This is wrong:

say_hello()  # ❌ NameError: function not defined yet
def say_hello():
    print("Hello")

This is correct:

def say_hello():
    print("Hello")
say_hello()  # ✅ works

So in a script:

  1. Put your function definitions near the top (or in a separate file).
  2. Call them after they are defined.

Common Beginner Mistakes When Defining Functions

Here are some typical syntax mistakes specific to function definitions:

1. Forgetting the Colon

def greet()  # ❌ missing colon
    print("Hi")

Correct:

def greet():
    print("Hi")

2. Missing Parentheses (Even with No Parameters)

def greet:  # ❌ missing parentheses
    print("Hi")

Correct:

def greet():
    print("Hi")

3. Inconsistent Indentation

def greet():
  print("Hi")
    print("Welcome")  # ❌ mixed indentation

Stick to one indentation style (commonly 4 spaces):

def greet():
    print("Hi")
    print("Welcome")

4. Putting Code Before the Function Body Starts

Anything that is part of the function must be indented:

def greet():
print("Hi")  # ❌ not indented, not part of the function

Correct:

def greet():
    print("Hi")

Simple Practice Ideas

Here are a few ideas to practice just defining and calling functions (without worrying yet about return values or complex parameters):

  1. Define a function say_name() that prints your name, then call it.
  2. Define a function print_line() that prints a line of dashes like ----------, then call it several times.
  3. Define a function intro() that prints two or three lines introducing yourself, then call it once.
  4. Define a function blank() that does nothing for now, using pass.

Try to:

You’ll build on this foundation in the upcoming chapters, where you’ll learn more about parameters, arguments, and return values.

Views: 17

Comments

Please login to add a comment.

Don't have an account? Register now!