Functions

Learn everything about functions in Python, including how to define, call, and use different types of arguments like default, keyword, required, and variable-length.

Loading...
Functions

A function is a block of reusable code that performs a specific task.

Functions help in organizing code, making it easier to maintain. They allow you to break down a complex problem into smaller, more manageable tasks, and you can call these functions whenever you need to execute the associated code.

Types of Functions

There are two types of functions:

  1. Built-in functions: Predefined in Python, such as len(), max(), print(), sum(), etc.
  2. User-defined functions: Functions created by the user to perform custom tasks.

Creating a Function

The def keyword is used to define a function in Python.

Syntax:

def function_name(parameters):
  # Code block

For example:

def greet():
    print("Hello!")

Calling a Function

You can call a function by giving the function name, followed by parameters (if any) in the parenthesis.

For example:

def add(a, b):
  print(a + b)
 
add(5, 3) #output: 8

If you want to declare a function and don’t want to give any code statements at that time, then you can use the pass statement to avoid any errors.

For example:

def add(a, b): #This gives a syntax error

You can use the pass statement to avoid this as follows:

def add(a, b):
  pass

Function Arguments

Functions can accept inputs, called arguments. There are four types of arguments that you can provide in a function:

  • Default Arguments
  • Keyword Arguments
  • Required Arguments
  • Variable length Arguments

Default arguments

You can provide a default value for parameters while creating a function. This way if you don’t provide any value at the time of function call then the function will take the default values.

For example:

def greet(name="Mark"):
  print("Hello", name)
 
greet("John") # output: Hello John
greet() # output: Hello Mark

Keyword arguments

You can provide arguments in key = value syntax. This way, the interpreter identifies the arguments based on their parameter names, so the order in which the arguments are passed becomes unimportant.

For example:

def greet(firstName, lastName):
  print("Hello", firstName, lastName)
 
greet(lastName = "Phillips", firstName="Mark") 
# output: Hello Mark Phillips

Required arguments

In case you don’t pass the arguments with a key = value syntax, then it is necessary to pass the arguments in the correct positional order and the number of arguments passed should match with actual function definition.

For example:

def greet(firstName, lastName):
  print("Hello", firstName, lastName)
 
greet("Mark", "Phillips") # output: Hello Mark Phillips

Variable-length arguments

Sometimes you may need to pass more arguments than those defined in the actual function. This can be done using variable-length arguments.

You can achieve this in the following two ways:

Arbitrary Arguments:

While creating a function, pass a * (args) before the parameter name. The function accesses the arguments by processing them in the form of tuple.

For example:

def greet(*names):
    print("Hello,", names[0], names[1])
 
greet("Mark", "John")
#output: Hello, Mark John

Keyword Arbitrary Arguments:

While creating a function, pass a ** (kwargs) before the parameter name. The function accesses the arguments by processing them in the form of dictionary.

def greet(**names):
    print("Hello,", names["firstName"], names["lastName"])
 
greet(firstName = "John", lastName = "Doe")
#output: Hello, John Doe

Return Statement

The return statement is used to return a value back to the caller.

For example:

def add(a, b):
  return a + b
  
result = add(5, 3)
print(result)  # Output: 8

Why Use Functions?

  • Functions avoid rewriting the same code and makes your code reusable.
  • Break large programs into smaller, manageable pieces.
  • Functions clearly define their purpose, so it improves readability.
  • Debug and update specific parts without affecting the rest.

Support my work!