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:
- Create a file named functions.py in your part50 folder.
- Complete the tasks and use # comments to explain your answers.
Exercise 1: Your First Function
-
Task: Define a function called
greet()that prints"Hello, welcome to Python!". - Goal: Call the function 3 times. Then try calling the function before the definition and observe the error. Write a comment explaining why the error occurs and how you fixed it.
Exercise 2: Function with Logic
-
Task: Define a function called
even_or_odd()that contains a listnumbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]. -
Goal: Inside the function write a loop that prints
whether each number is even or odd in the following format:
2 is even. Call the function and verify the output. Write a comment explaining the advantage of wrapping this logic inside a function.
Exercise 3: The Christmas Tree Function
-
Task: Take the Christmas tree code from the
previous lesson and wrap it inside a function called
draw_tree(). - Goal: Call the function 3 times and observe how the tree is drawn 3 times without having to rewrite any of the logic. Write a comment explaining why wrapping repetitive code in a function is better than copying and pasting it.
Exercise 4: Function with a Loop
-
Task: Define a function called
countdown()that uses a while loop to count down from 10 to 1 and prints each number. When the loop finishes print"Blast off!". - Goal: Call the function twice. Write a comment explaining what would have been required to produce the same output without a function.
Exercise 5: Find the Duplicates Function
-
Task: Take the duplicate finder code from the
previous lesson and wrap it inside a function called
find_duplicates(). - Goal: Call the function and verify the output matches what you got in the previous lesson. Then create a second list with different duplicates and call the function again. Write a comment explaining the problem you notice and why it occurs.
Don't Forget to commit and Push!