Introduction of Python Function

Functions are some statement inside a block. Which complete one or more specific task given by our direction. The concept of functions is the same in every programming, just the syntax different.

We can think of it as a machine. It gives us a result based on our input and what we tell to do, as a machine does. For example, we can think about a blender machine. When we put apples in it and run the blender machine, we get apple juice. We can also think about our phone’s music player app. When we click on the play button, it’s play song for us. Under the hood, it’s run a function that plays songs for us.

Below is a basic function is written in Python.

def func():
  pass

The above function would not do anything. That is a very minimal python function. In Python for declaring a function, we have to use def keyword. then we have to write the function name with space and then parenthesis and colon. If the function receives any parameter then we have to pass those inside the parenthesis. The first line is the declaration of the function. Then start function block from the next line. We have to write our function code inside the block. Remember one thing, python strictly follow indentation rule. To write the function code inside the function block, you have to indent your code after declaring a function. For now, we used the pass keyword. It’s a special python keyword. We used pass keyword when a program demands a statement but we don’t want to return or execute anything.

A simple function below which only prints a string. The function didn’t receive anything as a parameter.

def func():
  print('I am function!')

func() # call the function

Function with parameter

def add(a, b):
  return a + b

res = add(5, 5)
print(res) # Output = 10

Here is an add function above. It’s received two arguments as a parameter and returns the sum of those two parameters. We can take arguments as per our requirements. Each argument must be separated by commas, otherwise we will get syntax errors. In our second example, we print inside the function. As a result, we can see the output just by calling function. But in this function, to see the output we have to print it. Another important thing is that when we calling a function, we must pass the arguments as well. Otherwise, we get an error. However, we can also set the default argument value.

Consider:

def add_three_val(a = 3, b = 3, c = 4):
  return a + b + c

res1 = add_three_val()
res2 = add_three_val(3, 3, 3)

print(res1) # Output = 10
print(res2) # Output = 9

If the function does not pass the value while calling, then the default value will be taken.

This article gives a very minimal amount of idea about python function. There are lots of advanced features of python function. I will try to cover those features in one of my next articles.