Python What is Function? Using def Keyword

Sovary June 24, 2022 290
4 minutes read

Hey fresher, today we will look at what is functions? how to use functions? Also how to create function in Python? we will explain to each component and type of functions.

thumbnail python functions example

What is a Function in Python?

In term programming, function is a group or block of code statements that handle to a certain task. Function is usually break down into smaller algorithm to solve complicated job. Once you group the statements code into function, it will make your code more organized and reusable (no redundancy).

Syntax

def function_name(parameter):
	#body definition
    return "my result"

The syntax structure above you can change are function_name, parameter, my result and definition. There is optional to pass parameters and return result as a value. The functions mostly define in 4 types:

  1. A function have parameter with no return value
  2. A function have no parameter with no return value
  3. A function have parameter with return value
  4. A function have no parameter with return no value

Arguments or Parameters?

The information pass through the function it is definitely the same, but those information call differently base on where we see the function.

We call Parameter when the variable is listed inside parenthesis of definition function.

def Read(x,y,z):
    # print(x,y,z)

x,y,z are call parameters

We call Argument when the value is pass to the function when it is called.

Read(2,3,6)

2,3,6 are call arguments.

Examples

Example #1 - Creating a Function no Parameter & no Return value

def say_something():
  print("Hello! I am running in function")

This example #1 have no result to produce because we are not called the function to activate all statements inside it. The function is simple have no parameter and return value.

Example #2 - Calling a Function

To activated function body statement, use the function name followed by parenthesis

def say_something():
  print("Hello! I am running in function")

# Call function
say_something()

Output #2

Hello! I am running in function

Example #3 - Function with Argument

The argument (args) which placed between parentheses. We can add many arguments as we want, each arguments separated by a comma.

def combine(word):
  print(word+"ing")

# Call function
combine("learn")
combine("eat")
combine("sleep")

Output #3

learning
eating
sleeping

Example #4 - Function with Arguments

By default a function must be called with correct number of arguments and ordering. If you defined a function with 2 arguments you have to pass 2 parameters as well.

def combine(who, word):
  print(who+" is "+word+"ing")

# Call function
combine("Sok", "learn")
combine("He", "eat")
combine("Dara", "sleep")

Example #5 - Function with Unordered Arguments (keyword argument = kwargs )

In Python allow to send arguments with correct variable name in parameters, the ordering will be ignored. See the below example:

def combine(who, word):
  print(who+" is "+word+"ing")

# Call function
combine(word = "learn",who = "Sok")
combine(word = "eat", who = "He")
combine(word = "sleep", who =  "Dara")

Output #4, #5

Sok is learning
He is eating
Dara is sleeping

Example #6 - Function with Default Value

We can set default value to parameter, so that when we call function there is not required to pass argument. The parameter will take default value as below example:

def get_weather(weather = "cloudy"):
  print("Today is "+weather)

# Call function
get_weather()
get_weather("rainy")

Output #6

Today is cloudy
Today is rainy

Example #7 - Function with Return Value

In some case to solve algorithm in various parameters we can return the result out from the function.

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

# Call function
result = sum(3,5)
print(result)

Output #7

8

Example #8 - Function with Unknown Arguments

In case we do not know in advanced how many arguments should be passed into function, we can use arbitrary arguments as asterisk (*) before parameter name. The function will received as a tuple arguments and access item via index.

def get_month(*a):
  print("This month is " + a[1])

# Call function
get_month("May","June")

Output #8

This month is June

Example #9 - Function with Unknown Arguments Unordered (**kwargs)

This case is combine between example #5 and #8 which mean we do not know in advance arguments and access with key pair. We use double asterisk(**) before argument name. The function will received value as a dictionary and access item via key.

def tell_name(**name):
  print("My first name is " + name["f_name"])
  print("My last name is " + name["l_name"])

# Call function
tell_name(f_name="Sovary",l_name="K")

Output #9

My first name is Sovary
My last name is K

Example #10 - Recursive Function (Loop)

A function can call itself that mean it works as a loop. In some case for loop and while loop can do the thing, so recursion function is another option to loop through data until reach a result.

Be careful you might accidently writing a function which never terminates (infinite loop).
def minus_recursion(value):
  if value > 0 :
    new_value = value - 1
    print(new_value)
    # call itself 
    minus_recursion(new_value)
  else:
    print("Value is zero!")
    
minus_recursion(5)

Output #10

4
3
2
1
0
Value less zero!

 That's all for this article hope you learn how to defined different functions and use effectively. Have a nice day.

 

Python 
Author

Founder of CamboTutorial.com, I am happy to share my knowledge related to programming that can help other people. I love write tutorial related to PHP, Laravel, Python, Java, Android Developement, all published post are make simple and easy to understand for beginner. Follow him