Software creation is challenging as it requires thousands of lines of code, and as the length of code increases, this challenge becomes tougher. Hence, software engineers separate their codes into numerous functions so that the code length gets reduced and tracking bugs becomes easy. Likewise other programming languages, Python also provides support for writing functions, and it has mainly two types: User-defined and In-built functions.
In Python, functions are required to follow specific syntaxes to ensure their validity inside any program. In this article, we will discuss more basics of Python functions.
After going through this blog, we will be able to understand the following things:
So let’s start by knowing more about python functions.
Python functions are a set of instructions grouped in a block, and this block gets executed only when it is called inside our program. Instead of writing the same code for different input variables over and over, programmers write separate functions and call them for different inputs.
Among many, here are some practical benefits that any Python function provides:
Now that we know about the functions, let’s learn how we can create them.
In any programming language, we need to follow some defined pattern in which code should be written, and Python is not an exception here. We need to follow the defined syntax in which we can write Python functions, so let’s first learn about this syntax itself.
def function_name(inputs): # Statements return
The structure of a Python function is shown in the above image. Major components that are part of it are:
Let’s create a function that calculates the square of any given number passed as an input to that function.
def calc_square(num): square = num**2 print("The square of %d is : "%num, square) return
There is another form of writing function where we explicitly mention the data type of input arguments and the return. Let’s see that also.
def function_name(var1 : int, var2: str, var3: float) -> int: # statements to be executed return variable
Now, as we have generated a function, let’s learn how to use it or call it inside our programs.
Once a Python function’s framework is complete, we can call it anywhere in our programs. For example, earlier, we designed a calc_square function, and now we will call it for multiple input values.
calc_square(7) # Output The square of 7 is : 49 calc_square(10) # Output The square of 10 is : 100
If a Python function return values instead of an empty return like what we saw in the calc_square function, then we need to store the return in some variable. Let’s see one example corresponding to that also.
def calc_square(num): square = num**2 return square num = 7 sqr = calc_square(num) print("The square of %d is : "%num, sqr) # Output The square of 7 is : 49
Now we know how these blocks of statements can be reused inside our programs. Let’s learn more about the types of these arguments using which we can call a Python function.
There are mainly three types of arguments:
These arguments are parameters already filled with some value in a Python function. For example:
def calc_multiply(var1, var2=7): multi = var1*var2 return multi
The above function calculates the multiplication between two variables, var1 and var2. But var2 has a default value of 7. Let’s see how two types of calls will affect the result
# Type 1 multi = calc_multiply(11) print(multi) ### Output 77 # Type 2 multi = calc_multiply(5, 9) print(multi) ### Output 45
Please note that in type 1 calling, if we do not mention the value of the default variable, it will automatically consider the default value. But we can overwrite these default values by passing additional arguments, as shown in Type 2 calling. We must think about what will happen if we do not give any input value for the parameters with no default value. Let’s see:
multi = calc_multiply() TypeError: calc_multiply() missing 1 required positional argument: 'var1'
Yes, it will throw a TypeError. It will suggest us fill the positional argument: ‘var1’ with some value. One interesting thing to note here is that the order of writing arguments should follow some basic rules per Python function syntax. One of those basic ones is the non-default arguments should be mentioned before the default arguments. So the example shown below will throw SyntaxError:
def calc_multiply(var1=7, var): SyntaxError: non-default argument follows default argument
If we pass two values inside calcmultiply, it will, by default, treat the first value as var1 and the second value as var2. Input arguments into a Python function are linked to its name, and we can pass arguments out of order as well. For example, we call the same calcmultiply function like this:
multi = calc_multiply(var2=9, var1=5) print(multi) # Output 45
In Python functions, we can also pass a variable length argument using two special symbols:
Let’s see their examples for a better understanding:
# *args example def cal_sum_of_arguments(**args): sum = 0 for arg in args: sum += arg return sum total_sum = cal_sum_of_arguments(1, 5, 7, 9, 11) print("Sum of all arguments is : ",total_sum) # Output Sum of all arguments is : 33 # **kwargs example def print_paired_arguments(**kwargs): for key, value in kwargs.items(): print("Key = ", key, " value = ", value) return print_paired_arguments(var1='Enjoy',var2='Algorithms', var3='ml') # Output Key = var1 value = Enjoy Key = var2 value = Algorithms Key = var3 value = ml
The return statement exits the function and brings code execution to the line where that function was called. Using the return statement, we can extract specified values from a function. In Python, we have the flexibility to return multiple values of varying data_types from a function. For example:
def print_paired_arguments(**kwargs): keys =  values =  for key, value in kwargs.items(): keys.append(key) values.append(value) return keys, values keys, values = print_paired_arguments(var1='Enjoy',var2='Algorithms', var3=3) # Output keys = ['var1', 'var2', 'var3'] values = ['Enjoy', 'Algorithms', 3]
In Python programming, everything is an object, and variables are the reference to these objects. But when we pass these variables as input arguments, a new reference to that object is created. This can be tricky to understand but let’s see this via an example.
def referencing(var1): var1 = 7 return var = [1, 0, 3, 4, 7, 9, 11] referencing(var1=var) # here var1 is a new reference to the same var print(var) # Output [7, 0, 3, 4, 7, 9, 11] ## Please note that the var got changed as we are modifying the object present at the same reference.
But when we try to modify the var1 to something else altogether, it will start referencing some other object, and the link between previous and current referencing will break. Let’s see that with an example.
def referencing(var1): var1 = [7, 9, 11, 12, 3, 4, 5] return var = [1, 0, 3, 4, 7, 9, 11] referencing(var1=var) print(var) # Output [1, 0, 3, 4, 7, 9, 11] ## Please note that the var did not change as we are modifying the reference itself.
In Python, we have functions that exist without a name. We use the def keyword for functions with a name, but for anonymous functions, we use the lambda keyword. A lambda function can take any number of input arguments but always returns one value resulting from that function. So we can say that a lambda function needs one expression, so a print statement can not be passed as it will not output anything.
lambda_ = lambda var1, var2, var3: var1 + var2*var3 lambda_(1,2,3) # Output 7
As we said, there can be mainly two types of Python functions,
This function gives us the length of the variable passed as an argument of this function. For example:
var1 = "This is a pen" print(len(var1)) # Output 13 ## Because there are 13 characters in the variable var1 var2 = [1, 3, 5] print(len(var2)) # Output 3
1. type([1, 2, 3]) # Type function shows the data type of the var # <class 'list'> 2. tuple([1, 2, 3]) # Converts valid input into a tuple # (1, 2, 3) 3. str(7) # Converts valid input into a string # '7' 4. round(6.6) # Round off the valid input variable # 7 5. list(reversed([1, 2, 3])) # reverse the list # [3, 2, 1] 6. range(0,7) # We discussed this function in detail already 7. print() # prints the input passed 8. int() # converts the input into int 9. sorted() # sorts the list in ascending order 10. list() converts the input into a list
In this article, we discussed one of the basic concepts In Python programming, i.e., Python Function. We learned how to create a function and call it into our program. We also discussed the input arguments in greater detail with examples. Last, we saw some in-built python functions frequently used in Python programming. We hope you enjoyed the article.
Next Blog: Introduction to OOPS in Python
Previous Blog: Introduction to loop in Python
Subscribe to get weekly content on data structure and algorithms, machine learning, system design and oops.