Home
About Us Privacy Policy
 

FUNCTIONS IN PYTHON

ADVERTISEMENT

Intermediate Functions



What are functions, and why are they used?

Functions are a set of reusable statements that are called upon to execute a specific task. They can accept and return values. Before we delve into functions and their advantages while developing programs, let us understand their usage. Since the beginning of this tutorial, we've been writing our programs as individual statements to achieve the objective. Let us take an example of adding two numbers together and print their sum.

a = input("Enter a number:\n")
b = input("Enter another number:\n")
print(a+b)
# ....
# ....
# ....
# ....
# ....
x = input("Enter a number:\n")
y = input("Enter another number:\n")
print(x+y)
# ....
# ....
# ....
# ....
# ....
# ....
a = input("Enter a number:\n")
b = input("Enter another number:\n")
print(a+b)

Well, writing such a small program to print the sum only once is fine. However, What if we have to take input numbers from users and print their sum again at different stages in the program? We can write the same code again, but wouldn't that make our task repetitive, open opportunities for bugs to seep through, add to code duplication, cost more disk as well as RAM space, and be harder to maintain? It will be indeed. What if we could write our statements to perform a specific task only once and reuse the same code when required. In Python, functions allow us to do just that. Now, let's learn how to declare a function and understand its anatomy.


How to declare a function in Python?

In Python, to declare a function use the def keyword. Here is the syntax:

def <function_name>(args):
    statement 1
    statement 2
    ...
    ...
    ...
    statement N
    return value(s)
            

Now, let us break down each component.

def

We use the def keyword to inform Python that a function will be declared, followed by the function_name. Remember, while declaring a function name, we must follow the same rules when declaring a variable.

args

Arguments follow the function name enclosed in round brackets. Arguments are also known as parameters in other programming languages. Although we can use the term arguments or parameters interchangeably; however throughout this tutorial, we will be using the term argument(s) for consistency. Arguments make it possible for the statements to access information from outside the scope of the function. We can define multiple arguments by separating them with a comma(,). Arguments are optional; therefore, if no external information is required, we can omit them.

Below are a few examples.

# Function with no argument
def zoo():
    pass

# Calling the function
zoo()

# Passing one argument to a function
def foo(name):
    pass

# Calling and passing a single argument
foo("James Bond")

# Passing Two arguments
def bar(name, age):
    pass

# Calling and passing two arguments
bar("James Bond", 46)

# Passing more than two arguments
def moo(name, age, gender, weight):
    pass

moo("James Bond", 46, "M", 176)


As illustrated above, the value "James Bond" corresponds to the argument variable "name", 46 corresponds to "age", "M" corresponds to "gender", and 176 to "weight".

Once arguments are defined in the function definition, it becomes mandatory to pass the value.

statement(s)

These statements define the functionality of the program. They are standard Python code but inside of a function. Whenever we execute a function, these statements are executed.

def print_sum(a,b):
    print(a+b)

In the above example,

print(a+b)
is the statement we write to print the sum of two numbers. Every time the function print_sum is called, the statement
print(a+b)
will get executed.

return

We have learned about declaring and accepting values into a function. However, after executing our statement(s), we might also need to send values back to be used elsewhere. Python allows for sending values back by using the return statement. We can return multiple values as a tuple from a function. Return statements are optional and can be omitted. By default, any function, if not explicitly returning a value, will implicitly return the value of None. Below are a few examples.

# Sending no value, None by default(implicitly)
# When no argument is passed, leave the brackets empty.
def foo():
    print("Hello, World")

print(Foo())  # None

# Sending one value
def foo(a):
    return a * 10

# Pass the value 10
print(foo(10))

# Sending multiple values
def bar(a, b):
    m = a * b 
    s = a + b

    # Parentheses are optional and can be omitted.
    return (m, s)
    
# Pass multiple values
print(bar(1, 2))

Hello, World
None
100
(2, 3)


ADVERTISEMENT

What are the advantages of using functions?

Code Readability and Reusability are one of the main advantages of using functions to manage code. Writing statements inside a function makes the code more readable, as it becomes easier to understand the methodology precisely.


The pass statement

The pass statement is a placeholder statement used when a statement is required syntactically but does not do anything. It is used when a function or a block of code is declared but not implemented. For example, when defining the function later. The interpreter ignores this as if it does not exists.

Here are a few examples of pass statements:

# Will define this function later
def foo():
    pass


# Block of code
my_name = "Jamey Bond"
if my_name == "James Bond":
    print("Hello, James")
else:
    # Will define later
    pass


Default Arguments

Default Arguments are arguments whose predefined values are passed to the function by default. Here is an example:

def print_name(name="James Bond"):
    print(name)

In this example, the argument "name" has been assigned a "James Bond" default value. If any value is not passed to the function while executing it, the value "James Bond" is automatically given by Python.

# Will send "James Bond" automatically
print_name()

# Will send the value of "Mr. Kirk"
print_name("Mr. Kirk")

James Bond
Mr. Kirk

Do not confuse this with defining an argument and not sending any value. As we have informed Python, it will pass the default value specified if no argument is explicitly passed.


Caveats in Default Arguments

There are certain caveats when using default argument(s). Before we discuss it any further, let's go through an example.

def my_function(my_name="James Bond", age):
    print(my_name, age)

SyntaxError: non-default argument follows default argument

Doing so will generate a Syntax Error. But why so? Remember that arguments and values passed correspond to each other. Let's understand that with an example.

def my_function(my_name="James Bond", age):
    print(my_name, age)

my_function(46)

However, we have specified a default value for my_name when calling this function; however, not for the age. When calling a function like

my_function(46)
, it raises ambiguity for the Python interpreter and cannot correlate the value with the variable. Is the value passed for the argument my_name or the age? Now, we know that age is the apparent variable, but Python doesn't. Hence, it generates an error.

Let's go through another example.

def a_simple_function(age, my_name="James Bond"):
    print(my_name, age)

# This is callable
a_simple_function(46)

James Bond 46

Please copy the above Python code and execute it. As you can observe, this function is accepted. Take some time to contemplate. After you're done, click to reveal the answer.

No non-default argument can appear after a default argument.


ADVERTISEMENT

Keyword Arguments

Since Python is a high-level language, it allows for a handy feature; keyword arguments. Keyword arguments allow for the passing of values by specifying the name of the argument. Below is an example demonstrating the usage:

def print_detail(name, age):
    print(f"His name is {name} and his age is {age}.")

my_name = "James Bond"
my_age = 46

print_detail(name=my_name, age=my_age)

His name is James Bond and his age is 46.

As you can observe, we have passed the value to the argument by specifying its name. Another helpful feature is that the order of the argument does not matter when passing values through keyword arguments.

print_detail(name=my_name, age=my_age)
print_detail(age=my_age, name=my_name)

They both are valid statements.


Variable arguments

During development, there are situations when the exact number of arguments is hard to determine. For example, let us take the scenario where you might want to calculate the average scores in Physics of the top 10 students.

def calculate_avg(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10):
    summation = a1 + a2 + a3 + a4 + a5 + a6 + a7 + a8 + a9 + a10
    avg = summation / 10
    return avg

Doing so is okay for a beginner but makes the code harder to read, understand, opens opportunities for bugs to appear. Now, what if you might want to calculate the sum for top-20 students instead of 10? Would you write it again with 20 arguments? What about 300 students? To handle such uncertain scenarios, Python provides variable arguments, also known as variadic arguments.

To define a variadic argument, precede the name of the argument with an asterisk (*). Below is an example demonstrating the usage.

def calculate_average(*scores):
    pass

Now, to calculate the average, we have to know how many values were passed. We can add a second argument to tell our function precisely that, but Python provides a much more eloquent mechanism. To understand that, we must first understand how Python is passing variable arguments.

def print_type(*args):
    print(type(args))

print_type(1, 2, 3)
print_type(1)
print_type("Hello, World", 2)

<class 'tuple'>
<class 'tuple'>
<class 'tuple'>

We are passing multiple values defined in a tuple. As you might remember, we can find out the tuple length using the in-built len() method. Therefore, we can use the len() method to determine how many values have been passed. Let's rewrite the calculate_average function.

def calculate_average(*scores):

    # Will store sum of scores
    summation = 0

    # Add scores
    for score in scores:
        summation += score

    # Find out how many arguments were passed.
    no_of_args= len(scores)

    # Average
    avg = summation / no_of_args

    # Return average
    return avg

print(calculate_average(1, 2))
print(calculate_average(1, 2, 3, 4, 5, 6, 7, 87, 89))
print(calculate_average(1, 2, 30, 30, 39, 79, 19, 29, 64, 34, 86))

1.5
22.666666666666668
37.54545454545455


ADVERTISEMENT

Variable Keyword Arguments

We have been introduced to variable arguments, but Python also provides variable keyword arguments. They allow for a variable number of variables to be passed as keyword arguments that we learned earlier. Variable keyword arguments can are by prefixing double asterisk '**' to the argument name. You can access the variable by indexing its name.

def example(**args):
    print(type(args), args['my_name'], args['my_age'])

example(my_name="James Bond", my_age=46)

<class 'dict'> James Bond 46

Variables in keyword arguments are passed as Dictionary data types.


Recursion

In Programming, recursion is a concept where the function calls itself. Here is an example

def calling_itself(i):
    if i >= 5:
        return
    else:
        print(i)
        calling_itself(i+1)

calling_itself(0)

0
1
2
3
4

Let us go through the example.

We invoke the function "calling_itself" for the first time with the value 0, and it checks whether the value of "i", which now carries the value "0", is more than or equal to 5; if true, it quits. If not, it prints the value of "i" and calls itself, adding 1 to the current value of i.

You should avoid using Recursive functions as they are hard to understand, maintain, open opportunities for bugs to appear, and are memory intensive.


Conclusion

In this chapter, we learned about functions and their importance, declaring a function using the del keyword, the advantages of using a function, the pass statement, returning values from a function to be used externally.

Additionally, we also learned about passing different types of arguments, recursive functions, and their caveats.


ADVERTISEMENT



All product names, logos, and brands are property of their respective owners.