Lesson 6: Defining Your Own Functions

In Python, def is a keyword used to define a function. Like in loops, code blocks start with a colon : following the indentation.

Python

1def my_function(arg1, arg2):
2 # code block
3 return result

In PHP, we use function and curly braces {}.

PHP

1function my_function($arg1, $arg2) {
2 // code block
3 return $result;
4}

A bit more real-life example:

1def laravel_daily_search(query, courses, num, popular):
2 print(query, courses, num, popular)
3 
4# Call the function
5laravel_daily_search('python', True, 20, True)

Keyword Arguments

Look at the code example above.

We can only guess that the first argument is a query; other arguments are unclear.

So, you can pass keyword arguments to make function calls more readable.

1laravel_daily_search('python', courses=True, num=20, popular=True)

They must match the place of the positional arguments; order still matters.


Default Arguments

When defining a function, you can specify default arguments.

1def laravel_daily_search(query, courses=False, num=10, popular=True):
2 print(query, courses, num, popular)
3 
4# Call the function with only one required parameter
5laravel_daily_search('python')

You can override any default argument by providing a keyword argument in any order after all positional arguments are matched:

1laravel_daily_search('python', num=20, courses=True)

Defining Functions At A Runtime

Python allows you to define functions at a runtime that can be called inside a code block.

1def my_func():
2 def another_func():
3 print('Hello')
4 
5 another_func()
6 
7 
8my_func()
9# Hell0

But you cannot call such "internal" functions outside of the code block.

1def my_func():
2 def another_func():
3 print('Hello')
4 
5 another_func()
6 
7 
8another_func()
9# NameError: name 'another_func' is not defined

Mutable Objects Are Passed By Reference

There's one Python behavior that is fundamentally different from PHP, so you should know about it: mutable objects are passed by reference in Python.

In other words, if you change the variable inside the function, it changes the value outside of it, too.

Python

1def add_to_list(lst):
2 lst.append(1)
3 
4 
5my_list = []
6 
7add_to_list(my_list)
8add_to_list(my_list)
9 
10# [1, 1]

PHP

1function add_to_array($arr)
2{
3 $arr[] = 1;
4}
5 
6$my_array = [];
7 
8add_to_array($my_array);
9add_to_array($my_array);
10 
11// []

You must use ampersand & in PHP to specify the reference.

1function append($n, array &$l)
2{
3 $l[] = $n;
4 
5 return $l;
6}
7 
8$l = [];
9 
10$l1 = append(0, $l); // [0]
11$l2 = append(1, $l); // [0, 1]

If you do not want this behavior in Python, you can pass a copy of a list using the copy() method.

1add_to_list(my_list.copy())

Declare In Any Order, Use After Declaration

In Python, the order of function declarations generally does not matter.

Functions can be declared and defined in any order, and Python will resolve the names at runtime.

1def func_a():
2 return func_b()
3 
4 
5def func_b():
6 return "Hello from func_b!"
7 
8 
9func_a()

Notice: as you can see, there are usually two empty lines between the functions, according to Python code standard.

Unlike other programming languages like JavaScript, Python does not have function hoisting in the same sense.

In Python, the entire script or module is compiled and executed from top to bottom. That means that names (including functions) must be defined before use.

1def func_a():
2 return func_b()
3 
4 
5func_a()
6 
7 
8def func_b():
9 return "Hello from func_b!"

Calling functions before they're declared would result in a NameError.

1NameError: name 'func_b' is not defined.

No comments or questions yet...