DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Cover image for Functions in Python
Isah Jacob
Isah Jacob

Posted on

Functions in Python

When creating a program, there will be thousands of lines of code that cannot be stored in a single file. It is always a good idea to break it down into smaller, more maintainable, and reusable pieces of code. This is where functions come in. In this article, I will look at the following Python functions, arguments, and key word arguments.

What is a Function?

A function is a piece of code that only executes when called. A function can accept data in a form of parameters. As a result, a function can return data.

Built-in Functions in Python

Python includes a built-in function that can help you solve problems quickly. The following are a few, but not lengthy, examples of built-in functions.

  • dir() Returns a list of the specified object's properties and methods
  • float() Returns a floating point number
  • input() Allowing user input
  • int() Returns an integer number
  • min() Returns the smallest item in an iterable

Creating a Function

A function is defined in Python by using the 'def' keyword, followed by parentheses and indentation.

def greet():
    print('Hi there')
    print('How are you doing today')
Enter fullscreen mode Exit fullscreen mode

A function can be called by using the function name followed by parenthesis.

def greet():
    print('Hi there')
    print('How are you doing today?')
greet()
#returns:
Hi there
How are you doing today?
Enter fullscreen mode Exit fullscreen mode

Arguments

We defined a greet function here and in between the parentheses we pass in our parameters first_name and last_name

def greet(first_name, last_name):
    print(f'Hi {first_name} {last_name}')
    print('How are you doing today?')
greet("John", "Emmanuel")
Enter fullscreen mode Exit fullscreen mode

As you can see, we add first_name and last_name as parameters. We called the function with John and Emmanuel as the argument.

Hi John Emmanuel
How are you doing today?
You can reuse it and supply different arguments.
Enter fullscreen mode Exit fullscreen mode
greet("Mike", "Joy")
Hi Mike Joy
Enter fullscreen mode Exit fullscreen mode

How are you doing today?

A parameter is the input for your functions that you define, such as first name and last name. John Emmanuel is the actual value you assigned to your functions in this case.
By default, the parameters you define in a function are required. You cannot provide only first_name in the argument; you must provide both the first_name and last_name.

Types of Functions

We have two types of functions

A Function That Returns A Value

The greet function in the following code prints 'Hello John' on the terminal because it returns a value.

def greet(name):
    print(f'Hello {name}')
greet(β€œJohn” )
Enter fullscreen mode Exit fullscreen mode

Functions That Perform A Task

The sum function below is a built-in function. It is an examples of a function that computes and returns a value.

scores = [30, 10, 56, 60, 70]
scores = sum(scores)
print(scores)
Enter fullscreen mode Exit fullscreen mode

Function that returns a value.

def greet(name):
    return f'Hi {name}'
email_message = greet("John Ibrahim")
print(email_message)
Enter fullscreen mode Exit fullscreen mode

We gave the parameter a name and used a return statement to return a string, as shown above (name). We invoke the greet() function and provide the name "John Ibrahim." We pass that value to a variable and print the variable email message because it returns a value.

When it comes to customizing your functions, the return value function is the best option because it allows you to do almost anything. You can print it, save it to a file, or send it as an email message.

Keyword Arguments

Functions can take information as arguments.
Arguments are enclosed in parentheses after the function name. You may enter as many arguments as you want, separated by a comma.

def multiplication(number, by):
    return number * by
result = multiplication(4, by=5)
print(result)
Enter fullscreen mode Exit fullscreen mode

In this case, we define our function with multiplication and the parameters number and by, and it returns number * by. We store the value it returns in a variable called result and print it to the terminal because it returns a value. However, in order for other engineers to understand our code, we use a keyword argument with the value of 5. It's as simple as multiplying 4 by 5. In this case, the keyword is by=5.

Default Arguments

Remember what I said earlier about the parameters you define in a function being required by default? Assume we want to multiply a value by 5 using the multiplication function. We'll do something similar.

def multiplication(number, by=5):
    return number * by
result1 = multiplication(4)
result2 = multiplication(4, 2)
Enter fullscreen mode Exit fullscreen mode

As you can see, we gave our parameter by a default values and set it to 5. The variables result1 and result2 were assigned to the multiplication function call.

The result1 will print 20 because the function will multiply the default value which is 5 by 4
Enter fullscreen mode Exit fullscreen mode

the result2 variable will print 8 because you have provided a value 2. therefore 4 * 2

Please note that all optional parameters must come after the required parameters. This means that nothing else can be added after the default parameter by=5. Any additional parameters added after that will result in an error.

Arbitrary Arguments, shortened as *args

There are times when multiple arguments are required in your functions. If we want to multiply five numbers (1, 2, 3, 4, 5), we can do so as shown below.

def multiplication(*numbers):
    result = 1
    for number in numbers:
        result = result * number
    return result
answer = multiplication(1, 2, 3, 4, 5)
print(answer)
Enter fullscreen mode Exit fullscreen mode

We provided a single argument number denoted by an asterisk *. The asterisk indicates that numbers can have multiple arguments. To compute the product of this number, we define a variable result and set it to 1. Then, in a loop, we multiply each numbers by the current number. The result is then returned, and the answer is printed.
The product is 120.

Arbitrary Arguments, shortened as **args

Assume you want a function that saves user information. A user's detail is more than just his or her name; a user can have many details. In this case, we use Arbitrary Arguments. We can do something similar down below.

def user_details(**user):
    print(user)
user_details(id=1, name="James", age="25", marital_status="single", location="lagos", job="software Engineer")
Enter fullscreen mode Exit fullscreen mode

To save user information, we named our parameter user with a double asterisk **. The user argument is then printed. This is then called user_datails, and key value such as id, name, age, marital_status, location and jobare passed in. We can bring in as many as we want. We were then have

{'id': 1, 'name': 'James', 'ages': '25', 'marital_status': 'single', 'location': 'lagos', 'job': 'software Engineer'}
Enter fullscreen mode Exit fullscreen mode

What you are seeing is called a dictionary. A dictionary is a data structure in Python. As you can see, we have multiple key value pairs. The key id is 1, the key name is James, and so on. When we use double asterisk, we can pass in different arguments and Python will package them into a dictionary. Click here to learn more about dictionary.

Function scope

"Scope" refers to the area of code where a variable is defined.

Local Variables

A local variable has a short life time. It cannot be accessed outside of the function scope.

def greetings():
     message = 'Good Morning'
print(message)
Enter fullscreen mode Exit fullscreen mode

We have the message variable which is in the scope of the greet function. It only exists within this function. If we try to print the message, it will fail because the print function is not within the scope. The same thing happens if we pass in a parameter that is not within the scope. This is referred to as a local variable.

Global Variable

message = 'Good Morning'
def greetings():
    print(message)
greetings()
Enter fullscreen mode Exit fullscreen mode

We moved the message variable outside of the functions, making it accessible anywhere in the function, outside of the functions, and in the file.

It is not always advisable to use global variables because if you have many functions that use the global variable and make changes in one of them, the rest of the functions are affected. If you're going to use global scope, avoid modification. There should always be a function with parameters and local variables.

Wrapping-up

In this article, I have been able to explain what a function is in python, how to create your own custom function, I explained arguments, keyword arguments and fuctions scope. I hope you have been able to learn something new.

Your feedback is highly appreciated.
you can follow me on twitter and linkedIn

Top comments (1)

Collapse
 
olalekan01 profile image
Ola Lekan

Nice writeup, I learnt a whole lot from this article...

Super Useful CSS Resources

A collection of 70 hand-picked, web-based tools which are actually useful.
Each will generate pure CSS without the need for JS or any external libraries.