KAHIBARO Bookshelves
Discord Login Register

9.2. 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:

  • def — a keyword that tells Python you’re defining a function.
  • function_name — the name you choose for your function.
  • parameters — zero or more names inside parentheses, separated by commas (can be empty).
  • : — a colon that ends the function header.
  • Indented block — the function body: all the code that runs when you call the function.

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:

  • Can include letters, numbers, and underscores.
  • Cannot start with a number.
  • No spaces.
  • Case-sensitive (greet and Greet are different).

Common style (PEP 8):

  • Use all lowercase letters.
  • Use underscores to separate words (snake_case).

Examples of good names:

  • greet_user
  • calculate_area
  • show_menu

Examples of invalid names:

  • 2nd_function (starts with a number)
  • my-function (contains -)
  • print (this is actually the name of a built-in function; avoid using built-in 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:

  • The two print lines inside the function are indented: they belong to greet.
  • The last print is not indented: it runs immediately when the script runs, not when greet() is called.

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:

  • def show_message(): tells Python what to do later.
  • show_message() actually does it.

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:

  • The docstring goes as the very first line inside the function body.
  • It’s usually written with triple quotes """ ... """.
  • Tools and IDEs can show this docstring when you hover over the function or ask for help.

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.

  • Definition: uses the def keyword and a colon.
  def say_hello():
      print("Hello")
  • Call: uses the function name followed by parentheses.
  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:

  • Use clear, descriptive function names.
  • Keep your indentation consistent.
  • Put definitions above where they are called.

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

Views: 0

Comments

Please login to add a comment.

Don't have an account? Register now!

Where to Move

Move chapter:

  • ☰ 1. Chapter 1: What Is Programming?
    • ☰ 1.1. What is a computer program?
      • ☰ 1.2. What is Python?
        • ☰ 1.3. Where is Python used?
          • ☰ 1.4. How programming helps solve problems
            • ☰ 1.5. Your first Python program
            • ☰ 2. Chapter 2: Setting Up Python
              • ☰ 2.1. Installing Python (Windows / macOS / Linux)
                • ☰ 2.2. Using Python in the terminal
                  • ☰ 2.3. Using an IDE (IDLE / VS Code)
                    • ☰ 2.4. Running Python scripts
                      • ☰ 2.5. Python interactive mode
                      • ☰ 3. Chapter 3: Variables and Data Types
                        • ☰ 3.1. What is a variable?
                          • ☰ 3.2. Creating variables
                            • ☰ 3.3. Numbers
                              • ☰ 3.4. Test
                                • ☰ 3.5. Boolean values
                                  • ☰ 3.6. Type checking
                                  • ☰ 4. Chapter 4: Basic Operations
                                    • ☰ 4.1. Arithmetic operations
                                      • ☰ 4.2. Working with numbers
                                        • ☰ 4.3. String operations
                                          • ☰ 4.4. Combining text and variables
                                            • ☰ 4.5. Comments in Python
                                            • ☰ 5. Chapter 5: User Input and Output
                                              • ☰ 5.1. Getting input from the user
                                                • ☰ 5.2. Converting input to numbers
                                                  • ☰ 5.3. Formatting output
                                                    • ☰ 5.4. Writing interactive programs
                                                    • ☰ 6. Chapter 6: Conditions
                                                      • ☰ 6.1. Comparison operators
                                                        • ☰ 6.2. Logical operators
                                                          • ☰ 6.3. if, elif, else
                                                            • ☰ 6.4. Nested conditions
                                                              • ☰ 6.5. Common beginner mistakes
                                                              • ☰ 7. Chapter 7: Loops
                                                                • ☰ 7.1. Why loops are useful
                                                                  • ☰ 7.2. for loops
                                                                    • ☰ 7.3. while loops
                                                                      • ☰ 7.4. Loop counters
                                                                        • ☰ 7.5. break and continue
                                                                          • ☰ 7.6. Loop exercises
                                                                          • ☰ 8. Chapter 8: Data Collections
                                                                            • ☰ 8.1. Lists
                                                                              • ☰ 8.2. Tuples
                                                                                • ☰ 8.3. Dictionaries
                                                                                  • ☰ 8.4. Sets (basics)
                                                                                    • ☰ 8.5. Choosing the right data structure
                                                                                    • ☰ 9. Chapter 9: Functions
                                                                                      • ☰ 9.1. Why functions matter
                                                                                        • ☰ 9.2. Defining functions
                                                                                          • ☰ 9.3. Parameters and arguments
                                                                                            • ☰ 9.4. Return values
                                                                                              • ☰ 9.5. Scope (local vs global)
                                                                                                • ☰ 9.6. Reusing code
                                                                                                • ☰ 10. Chapter 10: Working with Files
                                                                                                  • ☰ 10.1. What is a file?
                                                                                                    • ☰ 10.2. Reading text files
                                                                                                      • ☰ 10.3. Writing and appending files
                                                                                                        • ☰ 10.4. File paths
                                                                                                          • ☰ 10.5. Simple file-based programs
                                                                                                          • ☰ 11. Chapter 11: Errors and Debugging
                                                                                                            • ☰ 11.1. Types of errors
                                                                                                              • ☰ 11.2. Reading error messages
                                                                                                                • ☰ 11.3. Common beginner errors
                                                                                                                  • ☰ 11.4. try and except
                                                                                                                    • ☰ 11.5. Debugging strategies
                                                                                                                    • ☰ 12. Chapter 12: Using Python Libraries
                                                                                                                      • ☰ 12.1. What is a library?
                                                                                                                        • ☰ 12.2. Importing modules
                                                                                                                          • ☰ 12.3. Standard libraries
                                                                                                                            • ☰ 12.3.1. math
                                                                                                                              • ☰ 12.3.2. random
                                                                                                                                • ☰ 12.3.3. datetime
                                                                                                                                • ☰ 12.4. Installing external libraries with pip
                                                                                                                                • ☰ 13. Chapter 13: Object-Oriented Programming
                                                                                                                                  • ☰ 13.1. What is object-oriented programming?
                                                                                                                                    • ☰ 13.2. Classes and objects
                                                                                                                                      • ☰ 13.3. The `__init__` method
                                                                                                                                        • ☰ 13.4. Attributes and methods
                                                                                                                                          • ☰ 13.5. Encapsulation
                                                                                                                                            • ☰ 13.6. Inheritance (basics)
                                                                                                                                              • ☰ 13.7. Simple OOP examples
                                                                                                                                              • ☰ 14. Chapter 14: Automation with Python
                                                                                                                                                • ☰ 14.1. What is automation?
                                                                                                                                                  • ☰ 14.2. Automating simple tasks
                                                                                                                                                    • ☰ 14.3. Working with files and folders
                                                                                                                                                      • ☰ 14.4. Automating text processing
                                                                                                                                                        • ☰ 14.5. Scheduling scripts
                                                                                                                                                          • ☰ 14.6. Practical automation examples
                                                                                                                                                          • ☰ 15. Chapter 15: Web Development with Python
                                                                                                                                                            • ☰ 15.1. How the web works (basic overview)
                                                                                                                                                              • ☰ 15.2. Introduction to Flask
                                                                                                                                                                • ☰ 15.3. Creating a simple web server
                                                                                                                                                                  • ☰ 15.4. Routing and templates
                                                                                                                                                                    • ☰ 15.5. Handling user input (forms)
                                                                                                                                                                      • ☰ 15.6. Very basic APIs
                                                                                                                                                                      • ☰ 16. Chapter 16: Data Science with Python
                                                                                                                                                                        • ☰ 16.1. What is data science?
                                                                                                                                                                          • ☰ 16.2. Working with data
                                                                                                                                                                            • ☰ 16.3. Introduction to NumPy
                                                                                                                                                                              • ☰ 16.4. Introduction to pandas
                                                                                                                                                                                • ☰ 16.5. Data visualization with matplotlib
                                                                                                                                                                                  • ☰ 16.6. Simple data analysis examples
                                                                                                                                                                                  • ☰ 17. Chapter 17: Mini Projects
                                                                                                                                                                                    • ☰ 17.1. Number guessing game
                                                                                                                                                                                      • ☰ 17.2. Simple calculator
                                                                                                                                                                                        • ☰ 17.3. To-do list
                                                                                                                                                                                          • ☰ 17.4. Password generator
                                                                                                                                                                                            • ☰ 17.5. Quiz application
                                                                                                                                                                                              • ☰ 17.6. Small web or data project
                                                                                                                                                                                              • ☰ 18. Chapter 18: Next Steps
                                                                                                                                                                                                • ☰ 18.1. How to practice Python
                                                                                                                                                                                                  • ☰ 18.2. Writing clean and readable code
                                                                                                                                                                                                    • ☰ 18.3. Choosing a specialization
                                                                                                                                                                                                      • ☰ 18.3.1. Web development
                                                                                                                                                                                                        • ☰ 18.3.2. Data science
                                                                                                                                                                                                          • ☰ 18.3.3. Automation
                                                                                                                                                                                                            • ☰ 18.3.4. Software development
                                                                                                                                                                                                            • ☰ 18.4. Learning resources and communities
                                                                                                                                                                                                            • ☰ 19. Appendix
                                                                                                                                                                                                              • ☰ 19.1. Python syntax cheat sheet
                                                                                                                                                                                                                • ☰ 19.2. Common errors and solutions
                                                                                                                                                                                                                  • ☰ 19.3. Glossary of terms