Python Basics: Functions (2022)

Python Basics: Functions (1)

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:

Python
chess 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:

  1. Use the keyword def to introduce a function definition
  2. Write the function name followed by parentheses () and a colon:
  3. Define a list of parameters inside these parentheses (optional)
  4. 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.
  5. The first statement of the function body can be a string literal which represents the function documentation (optional)
  6. 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.

Defining a Function Without Parameters

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.

Defining a Function With Parameters

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 Example
We 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:

15
None

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.

(Video) Python Functions | Python Tutorial for Absolute Beginners #1

Defining a Function That Returns a Result

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.

Defining a Function That Returns Multiple Values

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-19
08:23:38.030659

In the example above we use sequence unpacking. We just “unpack” the values from the tuple into date and time variables.

Defining a Function with Documentation

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-19
08: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.

Local 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.

Global Scope

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.

Bult-In Scope

In Python, we have a number of functions and types built into that are always available.

Additional Notes

  • 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:

15
100

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:

programming
machine 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.

(Video) How To Use Functions In Python (Python Tutorial #3)

Output:

8
8
9

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:

81
4
8

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: 4
8
9

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.

*args

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:

5
10
15

Output:

10.0
18.0
15.75

**kwargs

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 24
position data analyst

name Jake
email jake@gmail.com
position machine learning engineer

Actually, the variable name can be whatever, we just need to insert one asterisk * or two asterisks ** before it.

Output:

10.0

age 24
position data analyst

Using * and ** When Calling a Function

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: Jake
position: data analyst
email: jake@gmail.com

Output:

name: Jake
position: data analyst
email: 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:

6
7
--------------------------------------------------------------------
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.

Exception Handling

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.

(Video) Python Tutorial for Beginners 8: Functions

  • 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.

Throwing Errors

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.

Python Basics: Functions (2)

In the current implementation, the built-in variable __debug__ is True under normal circumstances,False when optimization is requested

(Video) Python Functions || Python Tutorial || Learn Python Programming

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.

Python Basics: Functions (3)

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 ' + name

TypeError: 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. 😉

FAQs

What are the main types of functions in Python? ›

There are two basic types of functions: built-in functions and user defined functions. The built-in functions are part of the Python language; for instance dir , len , or abs . The user defined functions are functions created with the def keyword.

What is loop in Python? ›

The for loop in Python is used to iterate over a sequence (list, tuple, string) or other iterable objects. Iterating over a sequence is called traversal.

What is tuple in Python? ›

Tuple. Tuples are used to store multiple items in a single variable. Tuple is one of 4 built-in data types in Python used to store collections of data, the other 3 are List, Set, and Dictionary, all with different qualities and usage. A tuple is a collection which is ordered and unchangeable.

What is __ init __ in Python? ›

The __init__ method is the Python equivalent of the C++ constructor in an object-oriented approach. The __init__ function is called every time an object is created from a class. The __init__ method lets the class initialize the object's attributes and serves no other purpose. It is only used within classes.

What is array in Python? ›

Array is a container which can hold a fix number of items and these items should be of the same type. Most of the data structures make use of arrays to implement their algorithms. Following are the important terms to understand the concept of Array. Element− Each item stored in an array is called an element.

What is data type in Python? ›

Data types are the classification or categorization of knowledge items. It represents the type useful that tells what operations are often performed on specific data. Since everything is an object in Python programming, data types are classes and variables are instances (object) of those classes.

How many functions are there in Python? ›

The built-in Python functions are pre-defined by the python interpreter. There are 68 built-in python functions. These functions perform a specific task and can be used in any program, depending on the requirement of the user.

What is return in Python? ›

The return keyword is to exit a function and return a value.

What are modules in Python? ›

In Python, Modules are simply files with the “. py” extension containing Python code that can be imported inside another Python Program. In simple terms, we can consider a module to be the same as a code library or a file that contains a set of functions that you want to include in your application.

What are lists in Python? ›

A list is a data structure in Python that is a mutable, or changeable, ordered sequence of elements. Each element or value that is inside of a list is called an item. Just as strings are defined as characters between quotes, lists are defined by having values between square brackets [ ] .

Which keyword is used for function? ›

Definition and Usage

The def keyword is used to create, (or define) a function.

What are the 4 types of arguments in Python? ›

5 Types of Arguments in Python Function Definition:

positional arguments. arbitrary positional arguments. arbitrary keyword arguments.

How do you write a simple function in Python? ›

Basic Syntax for Defining a Function in Python

In Python, you define a function with the def keyword, then write the function identifier (name) followed by parentheses and a colon. The next thing you have to do is make sure you indent with a tab or 4 spaces, and then specify what you want the function to do for you.

What is __ init __ in Python? ›

The __init__ method is the Python equivalent of the C++ constructor in an object-oriented approach. The __init__ function is called every time an object is created from a class. The __init__ method lets the class initialize the object's attributes and serves no other purpose. It is only used within classes.

What are keywords in Python? ›

Keywords are the reserved words in Python. We cannot use a keyword as a variable name, function name or any other identifier. They are used to define the syntax and structure of the Python language. In Python, keywords are case sensitive. There are 33 keywords in Python 3.7.

What are lists in Python? ›

A list is a data structure in Python that is a mutable, or changeable, ordered sequence of elements. Each element or value that is inside of a list is called an item. Just as strings are defined as characters between quotes, lists are defined by having values between square brackets [ ] .

Videos

1. Python Functions (The Only Guide You'll Need) #12
(Programiz)
2. #32 Python Tutorial for Beginners | Functions in Python
(Telusko)
3. INTRODUCTION TO FUNCTIONS - PYTHON PROGRAMMING
(Sundeep Saradhi Kanthety)
4. Functions | Python | Tutorial 14
(Mike Dane)
5. Python Functions Tutorial | Working With Functions In Python | Python Training | Edureka
(edureka!)
6. Python Functions Tutorial - 18 | Working With Functions In Python | Python Tutorial | Simplilearn
(Simplilearn)

You might also like

Latest Posts

Article information

Author: Otha Schamberger

Last Updated: 10/12/2022

Views: 5926

Rating: 4.4 / 5 (55 voted)

Reviews: 86% of readers found this page helpful

Author information

Name: Otha Schamberger

Birthday: 1999-08-15

Address: Suite 490 606 Hammes Ferry, Carterhaven, IL 62290

Phone: +8557035444877

Job: Forward IT Agent

Hobby: Fishing, Flying, Jewelry making, Digital arts, Sand art, Parkour, tabletop games

Introduction: My name is Otha Schamberger, I am a vast, good, healthy, cheerful, energetic, gorgeous, magnificent person who loves writing and wants to share my knowledge and understanding with you.