Python Basics: Functions. After reading this article you’ll know: | by Ventsislav Yordanov | Towards Data Science

After reading this article you’ll know:
What are functions and how to define them
What are the parameters and arguments
How to return values from functions
How to define a function documentation
What represents the scope in Python
What are keyword arguments
Flexible and Default arguments
What are the Python exceptions and how to handle and how to raise them
Assert Statements
A function is an organized reusable piece of code solving a specific task. Functions help us to keep our code clean and provide us with the power of code reusability.
Python has several built-into functions which are always available. Some of these functions are print and max. Let’s see some examples of how we can use them.
The print function accepts objects and prints them
Output:
Pythonchess backgammon
The max function accepts an iterable and returns the largest item
Output:
49
We can see that we simply call the function by writing its name and pass the required inputs.
As a programmer or data scientist, sometimes we need functionality specific to our needs. In these cases, we can define our own functions.
To define a function we need to follow these rules:
Use the keyword def to introduce a function definitionWrite the function name followed by parentheses () and a colon:Define a list of parameters inside these parentheses (optional)Write the function body. The statements that form the function body, start at the next line and must be intended. When the function is called the code in the function body is run.The first statement of the function body can be a string literal which represents the function documentation (optional)Use the return keyword to pass back a result to the caller (optional)
Use the keyword def to introduce a function definition
Write the function name followed by parentheses () and a colon:
Define a list of parameters inside these parentheses (optional)
Write the function body. The statements that form the function body, start at the next line and must be intended. When the function is called the code in the function body is run.
The first statement of the function body can be a string literal which represents the function documentation (optional)
Use the return keyword to pass back a result to the caller (optional)
Don’t worry if you think that there are many steps. We’ll see many examples and the concepts will become pretty straightforward.
Let’s see a simple example of a function definition without the optional parts. We can call the function by typing its name followed by parentheses (). When we call this function, it will print the current date.
Output:
2019-02-19
Note that, this output can be different for you. The output will be the date in which you call the function.
We need function parameters almost always. They’re used when we want to pass data into our function. When we call a function we pass arguments (values for the parameters) to the function.
One Parameter Example
Output:
Forgive yourself for your faults and your mistakes and move on. - Les Brown
When we’re defining parameter like that it’s required. If we don’t pass an argument value for this parameter, this will give us an error.
Output:
--------------------------------------------------------------------TypeError                          Traceback (most recent call last)<ipython-input-48-f2f093834d71> in <module>()      2     print(text)      3 ----> 4 print_message()TypeError: print_message() missing 1 required positional argument: 'text'
Later, in this blog post, we’ll see how to define optional arguments (arguments with a default value).
Multiple Parameters ExampleWe can add as many parameters as we want, we just need to separate them with commas. In many cases, we need more than just one parameter.
The order in which the arguments are passed corresponds to the order of the parameters in our function definition. In the example below, we pass 10 as value for the number1 parameter and 5 as a value for the number2 parameter.
Output:
15
However, if we want to save the result in a variable, we cannot do that using the above function definition, because our function is simply printing the result and we don’t use a return statement. Let’s see what will happen if we try to save the result.
Output:
15None
We can see that the sum is printed (because our function was called), but the result variable has a value of None instead of 15. In the next section let’s see how we can return values.
We can use the return keyword to leave the current function call and to return a wanted result. Let’s see how we can re-define our function sum_numbers to return the sum instead of printing it.
Output:
15
We can clearly see that this time the result variable has a value of 15.
We can also define a function that returns multiple values. We can do that by constructing objects called tuples in your function. The tuples data type in Python is an immutable sequence. This means that they can contain multiple values like lists.
Output:
2019-02-1908:23:38.030659
In the example above we use sequence unpacking. We just “unpack” the values from the tuple into date and time variables.
In the last example, we defined a function that returns the current date and current time as a tuple. Maybe it’s easy to understand what the function does. However, wouldn’t be nice if there is a documentation for this function?
Output:
2019-02-1908:26:49.538434
In many cases, our functions are more complex than the above example. In these cases, it’s always preferable to have documentation for your function. The function documentation can include information about:
function arguments
function computations
returned value/s
Not all objects (including the functions) we have defined are accessible everywhere in our Python code. The scope of the program represents where a variable name or function name may be accessed. Python has 3 types of scopes: local, global and built-in scope.
When our object or function is defined inside a function this means that it has a local scope. We can use this object or function only inside the function where it’s defined.
When our object or function is defined in the main body of our Python code this means that is has a global scope. We have access to this object or function everywhere because it’s global.
In Python, we have a number of functions and types built into that are always available.
If we’re using variable name or function name inside a function, Python will search for that name first in the local, then in the global, and finally in the built-in scope.
If we’re using a variable or a name in the main body of the script, Python will search for that name first in the global, and then in the built-in scope.
It’s time to see a couple of examples.
Output:
15--------------------------------------------------------------------NameError                          Traceback (most recent call last)<ipython-input-2-faf6ee9da5b3> in <module>()      4       5 print(sum_numbers(10, 5))----> 6 print(result)NameError: name 'result' is not defined
In this example, we can see that we have access to the result variable in our function, but we don’t have access to it outside the function. That’s because of the result variable has local scope and can be accessed only inside the sum_numbers function.
Output:
Hi, Ventsi the sum is 15--------------------------------------------------------------------NameError                          Traceback (most recent call last)<ipython-input-1-747761fcaa8f> in <module>()      7       8 print(sum_numbers(10, 5))----> 9 print(result)NameError: name 'result' is not defined
In this example, we can see that we have access to the global variable name in our function. Also, we have used the str() built-in function. However, the result variable has a local scope again and it cannot be accessed outside of the sum_numbers function.
Output:
15100
Here, we defined a result variable globally, then we defined another variable in our function with the same name. We can see that we get a value of 100 for the global scope because our global variable has this value. Also, we get 15 for the sum_numbers(10, 5) because the value of the local variable result is calculated inside the function.
Output:
programmingmachine learning
We can use the global keyword in cases when we want to change the value of a global variable inside some function.
Keyword arguments are related to the function calls. When you use keyword arguments in a function call, the caller identifies the arguments by the parameter name.
This allows you to skip arguments or place them out of order because the Python interpreter is able to use the keywords provided to match the values with parameters.
Source: https://www.tutorialspoint.com/python/python_functions.htm
We can use the keyword arguments using the argument name and the = sign.
Output:
889
In some cases, we have a function with multiple parameters and we have a common value for some of them. We can specify default arguments for some of the function parameters. In these cases, we can call our function without specifying the values for the parameters with default arguments. To do this in Python, we can use the = sign followed by the default value.
Output:
8148
From the example above, we can see that the power parameter have a default value of 2. When we don’t specify the value for it, the default value is used. However, as we can see, we can pass a different value.
Output:
The number 2 raised to the power 2 is: 489
Sometimes, we want more flexible functions. For example, we may want to define a function which accepts more arguments than we have specified in the function. In other words, we may need to pass any number of arguments to our function. We can use the special syntax *args and **kwargs in our function definitions to achieve that.
These arguments are called non-named variable-length arguments.
Output:
<class 'tuple'>(1, 23, 4, 52, 2, 123)
We can see that the *args syntax passed all arguments to the function as a tuple called args. So, we can do everything that we can do with the tuples data type.
Output:
51015
Output:
10.018.015.75
These arguments are called named variable-length arguments.
Output:
<class 'dict'>{'age': 24, 'position': 'data analyst'}<class 'dict'>{'name': 'Jake', 'email': 'jake@gmail.com', 'position': 'machine learning engineer'}
We can see that the **kwargs syntax passed all arguments to the function as a dictionary called kwargs. So, we can do everything that we can do with the dictionary data type.
Output:
age 24position data analystname Jakeemail jake@gmail.composition machine learning engineer
Actually, the variable name can be whatever, we just need to insert one asterisk * or two asterisks ** before it.
Output:
10.0age 24position data analyst
We have seen that we can use this special syntax in our function definitions. However, we can use it when we’re calling functions, too.
Output:
name: Jakeposition: data analystemail: jake@gmail.com
Output:
name: Jakeposition: data analystemail: jake@gmail.com
In many cases, when we’re using a function incorrectly it raises an exception (error).
For example, we can see part from the documentation for the int() built-in function: “Return an integer object constructed from a number or string x, or return 0 if no arguments are given.”
Output:
67--------------------------------------------------------------------ValueError                         Traceback (most recent call last)<ipython-input-1-dea319bbd9d9> in <module>()      1 print(int(6.99))      2 print(int("7"))----> 3 print(int("Hi"))ValueError: invalid literal for int() with base 10: 'Hi'
We can see that a ValueError is raised when we have passed the “Hello” string as input.
When a Python script raises an exception, our code must handle the exception immediately otherwise the program execution will be stopped.
Sometimes, we may want to handle the raised exceptions without stopping the program execution. In Python, we can do that using the try-except clause.
the try block lets us test a block of code for errors
the except block lets us handle an error
Output:
An exception occured
The code above raises a NameError because the name numbers is not defined. When we don’t specify what exception type we’re looking for, the except will handle all the exception types.
Of course, we can write an except block that is looking for a specific kind of exception.
Output:
An NameError occured
We can define as many as we want except blocks when we want to execute a different piece of code for each of the handled exceptions.
Output:
A ValueError occured
Also, when we want more information about the exception we can save it to a variable using as syntax. For example, we may wish to log the error message.
We can also add an else block which will be executed if no errors were raised.
Output:
Something went wrong'int' object is not iterable
Output:
[1, 2, 3]Nothing went wrong
Also, we can use a finally block instead of else block if we want to execute some code regardless if the try block raised an error or not.
Imagine that we have a file filename.txt in your working directory and you’re trying to write some text in it.
Output:
An error occured when writing to the file
An error occurred because by default the open built-in function is using the “read” mode. However, the finally block is closing the file connection in both cases (if there was an error or not). In this case, we use this block to be sure that our file is closed.
When we’re defining our own functions we may want to raise errors and write more meaningful error messages. Let’s define a function that returns if two words are anagrams.
Output:
True--------------------------------------------------------------------TypeError                          Traceback (most recent call last)<ipython-input-61-f1a30da1d38d> in <module>()      7       8 print(check_anagrams("silent", "listen"))----> 9 print(check_anagrams("silent", 5))<ipython-input-61-f1a30da1d38d> in check_anagrams(word1, word2)      4     Returns True if the word1 and word2 are anagrams, otherwise returns False      5     """----> 6     return sorted(word1) == sorted(word2)      7       8 print(check_anagrams("silent", "listen"))TypeError: 'int' object is not iterable
With the second call of the function, we used it incorrectly with passing the integer 5 for the word2. A TypeError was thrown in this situation. We can see that the message is a little bit confusing. So, we can try to check that the two words are passed as strings and thrown an error with a more descriptive message. We can use the raise keyword to throw an error.
Output:
True--------------------------------------------------------------------TypeError                          Traceback (most recent call last)<ipython-input-3-afb475aa2f4f> in <module>()     10      11 print(check_anagrams("silent", "listen"))---> 12 print(check_anagrams("silent", 5))<ipython-input-3-afb475aa2f4f> in check_anagrams(word1, word2)      5     """      6     if type(word1) != str or type(word2) != str:----> 7         raise TypeError("The word1 and word2 must be strings")      8       9     return sorted(word1) == sorted(word2)TypeError: The word1 and word2 must be strings
Now, the message is much specific about the problem. Try to catch more specific exceptions and to write specific and clear error messages. You can check all the exception types from the docs.
Assert statements are a convenient way to sanity-check our code. They’re boolean expressions that check if the conditions return True or False. If a condition returns True, the program moves to the next line of code. Otherwise, an error is raised and the program execution is stopped.
We can think of the assert statements as “raise-if-not” statements.
In the current implementation, the built-in variable __debug__ is True under normal circumstances,False when optimization is requested
Source: https://docs.python.org/3/reference/simple_stmts.html#the-assert-statement
Output:
True--------------------------------------------------------------------AssertionError                     Traceback (most recent call last)<ipython-input-68-e5a7f4b2ffc2> in <module>()     10      11 print(check_anagrams("silent", "listen"))---> 12 print(check_anagrams("silent", 5))<ipython-input-68-e5a7f4b2ffc2> in check_anagrams(word1, word2)      5     """      6     assert type(word1) == str----> 7     assert type(word2) == str      8       9     return sorted(word1) == sorted(word2)AssertionError:
Hmmm, but there is no error message. What if we want to add a message to this AssertionError? We can pass it separated with a comma, right after our expression.
Output:
True--------------------------------------------------------------------AssertionError                     Traceback (most recent call last)<ipython-input-66-5f2e42abf116> in <module>()     10      11 print(check_anagrams("silent", "listen"))---> 12 print(check_anagrams("silent", 5))<ipython-input-66-5f2e42abf116> in check_anagrams(word1, word2)      5     """      6     assert type(word1) == str, "The word1 must be a string"----> 7     assert type(word2) == str, "The word2 must be a string"      8       9     return sorted(word1) == sorted(word2)AssertionError: The word2 must be a string
Python is a dynamically-typed language. When we’re defining your variables, functions, classes, etc. we don’t need to specify data types. This allows us to write code faster.
However, from Python version 3.5 we have the ability to add type hints in our function definitions. We can say what are the expected data types for the arguments and what data type the function returns.
Output:
Hello Ventsi--------------------------------------------------------------------TypeError                          Traceback (most recent call last)<ipython-input-28-b1c33d5121c9> in <module>()      1 print(greeting("Ventsi"))----> 2 print(greeting(42))<ipython-input-1-311aff60a9bd> in greeting(name)      1 def greeting(name: str) -> str:----> 2     return 'Hello ' + nameTypeError: must be str, not int
We can also define type aliases.
Output:
[2.0, -8.4, 10.8]
You can find more information here.
We have to be careful when we’re passing mutable objects to our functions. The arguments passed in a function call are using the object reference, not the value of the object. So, keep in mind that some functions can change the value of the passed objects.
The value of some objects can change. Objects whose value can change are said to be mutable; objects whose value is unchangeable once they are created are called immutable.
Output:
Before calling the function: ['this is test sentence', 'I love Python', 'positive thinking is nice!']After calling the function: ['This is test sentence', 'I love python', 'Positive thinking is nice!']
We can see that after we called our function, we have changed the contents of the sentences list.
If we want to save the result in a different variable, we can copy the sentences list in our function, do the capitalization for the copy version and return it. This way, we won’t change the sentences list itself (which is what you want in some cases).
Output:
Before calling the function: ['this is test sentence', 'I love Python', 'positive thinking is nice!']After calling the function: ['this is test sentence', 'I love Python', 'positive thinking is nice!']Capitalized sentences (result of the function): ['This is test sentence', 'I love python', 'Positive thinking is nice!']
A function is an organized reusable piece of code solving a specific task.
We can add as many parameters as we want, we just need to separate them with a comma.
When we call a function we pass arguments (values for the parameters) to the function.
We can use the return keyword to return a result from a function
We can define a function that returns multiple values constructing objects called tuples
The first statement of the function body can be a string literal which represents the function documentation (optional)
Python has 3 types of scopes: local, global and built-in scope.
When we use keyword arguments in a function call, the caller identifies the arguments by the parameter name. This allows you to skip arguments or place them out of order.
We can specify default arguments for some of the function parameters
We can use the special syntax *args and **kwargs when we want to have flexible arguments.
We can handle the raised exceptions using the try-except clause.
We can use the raise keyword to raise an error.
Assert statements are a convenient way to sanity-check our code.
We have to be careful when we’re passing mutable objects to our functions, their value can be changed.
Additional note: when we’re writing own function, we have to be careful to not overwrite some package name or built-in function name.
If you want to be notified when I post a new blog post you can subscribe to my newsletter.
Here is my LinkedIn profile in case you want to connect with me. I’ll be happy to be connected with you.
Thank you for the read. I hope that you have enjoyed the article. If you like it, please hold the clap button and share it with your friends. I’ll be happy to hear your feedback. Let me know if you want a blog post about lambda functions. If you have some questions, feel free to ask them. 😉