Flat_Eric Contemplating Data Type Conversions

Functions

Functions

So far we have used a number of built in functions that Python provides out of the box. Functions like print(), range(), enumerate(), len() and list(). Every time you have typed one of these and added parentheses you have been calling a function.

Now comes the exciting part. You are going to learn how to create your own functions. This is one of the most important concepts in all of programming and once you understand it your code will become dramatically more powerful, reusable and organized.

All programming languages use functions although the syntax is different in every language. In Python we use the keyword def to define a function.

Defining a Function

To create a function in Python you start with def followed by the name of your function, a pair of parentheses, and a colon. The same naming conventions that apply to variables apply to functions. Lowercase letters, words separated by underscores, and a name that describes what the function does.

Try running the code below exactly as it is:

Nothing happened. No output, no error. Why?

Because defining a function and calling a function are two completely different things. When you write def hello_world(): you are telling Python "this function exists and here is what it does." Python reads it, stores it in memory and waits. It will not run until you explicitly tell it to.

To run the function you need to call it by typing its name followed by parentheses. Add hello_world() below the function definition and run it again.

Now you can see hi printed to the output. And here is where functions become powerful. You can call the same function as many times as you want without rewriting the code inside it. Add hello_world() five more times and run it again.

Why Functions Matter

Think about how many times you have used print() throughout this course. Every single time you typed print() you were calling a function that someone else defined. Imagine if every time you wanted to display something in the terminal you had to write all of this from scratch:

def print(*values: object, sep: str | None = " ", end: str | None = "\n", file: SupportsWrite[str] | None = None, flush: Literal[False] = False) -> None

That is the actual definition of Python's built in print() function. It is complex, it handles many different situations, and it was written once by the people who built Python so that you never have to think about it again. You just type print() and it works.

This is the entire point of functions. Write the logic once, use it anywhere, as many times as you need. As your programs grow in complexity, functions will become the primary tool you use to keep your code clean, readable and maintainable.

Define Before You Call

The real advantage of functions is that you can create the logic for any task once and then use that function anywhere in your code simply by calling it. Need to validate a password? Write the logic once in a function and call it whenever you need it. Need to format a username? Same idea. One definition, unlimited calls.

However there is one important rule you must always keep in mind. A function must be defined before it is called.

Python reads your code line by line from top to bottom. If you define a function on line 100 but try to call it on line 50, Python will reach line 50, look for the function and find nothing. It has not read line 100 yet. The result is a NameError because as far as Python is concerned at that point in the file, the function does not exist.

Try it below. Run the code as it is and observe the error. Then move the function definition above the call and run it again.

This is why you will almost always see function definitions at the top of a file. It is a widely adopted convention that keeps your code organised and guarantees that every function is defined and ready before any code tries to use it.

Time to experiment!

Coding Exercises (VS Code) Instructions:

Exercise 1: Your First Function

Exercise 2: Function with Logic

Exercise 3: The Christmas Tree Function

Exercise 4: Function with a Loop

Exercise 5: Find the Duplicates Function

Don't Forget to commit and Push!

This course was built by DevSTEM - we turn teaching materials into interactive web courses like this one.

Build your own course