Python Functions

In simple terms, a function is a block of statements that can be used repeatedly in a program.

Python provides many built-in functions and allows programmers to define their own functions.

Syntax

Here’s the syntax of a function in python:

Name: An identifier by which the function is called

Arguments: contains a list of values passed to the function

Function body: is executed each time the function is called

Return: Ends the function call and sends data back to the program

Python Function Syntax

Create a Function

Use def keyword to define a function in Python.

Example:

def hello():
  print('Hello, World!')

Call a Function

You can call (run) the function by adding parentheses after the function’s name.

Example:

def hello():
  print('Hello, World!')
  
hello()		# Hello, World!

Pass Arguments

You can send information to a function through arguments.

Arguments are declared after the function name in parentheses.

Example: Pass single argument to a function

def hello(name):
  print('Hello, ' + name)

hello('Bob')	# Hello, Bob
hello('Sam')	# Hello, Sam

You can send as many arguments as you like, separated by commas ,.

Example: Pass multiple arguments

def func(name, job):
  print(name+' is a '+job)

func('Bob', 'developer')	# Bob is a developer

Default Argument Value

You can assign a default value to an argument.

So, when you call the function without argument, it uses the default value.

Example: Set default value ‘there’ to an argument

def hello(name='there'):
  print('Hello ' + name)

hello('Bob')  # Hello Bob
hello()       # Hello there

Keyword Argument

If you pass arguments to a function by name, you can put those arguments in any order.

Example: Keyword arguments can be put in any order

def func(name, job):
  print(name+' is a '+job)

func(name='Bob', job='developer')	# Bob is a developer

func(job='developer', name='Bob')	# Bob is a developer

Return Value

To return a value from a function, simply use a return statement.

If you do not include any return statement, it automatically returns None.

Example: Return sum of two values

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

x = sum(3, 4)
print(x)  # 7

Return Multiple Values

You can return multiple values by separating them with a comma.

Example:

def addSubtract(a, b):
  return a+b, a-b

T = addSubtract(3, 2)
print(T)	# (5, 1)

When you return multiple values, Python actually packs them in a single tuple and returns it.

You can then use multiple assignment to unpack the parts of the returned tuple.

Example:

def addSubtract(a, b):
  return a+b, a-b

x, y = addSubtract(3, 2)
print(x)	# 5
print(y)	# 1

Nested Functions

A Nested function is a function defined within other function.

Example:

def outer():
  print('Hello, Universe!')
  def inner():
    print('Hello, World!')
  inner()

outer()

Output:

Hello, Universe!
Hello, World!

Recursion

A recursive function is a function that calls itself and repeats its behavior until some condition is met to return a result.

In below example, findSum() is a recursive function that calls itself (recurse). We use the variable num as the data, which decrements (-1) every time we recurse. The recursion ends when it becomes 0.

Example: Find sum of numbers from 0 to 5, using recursive function

def findSum(num):
  if num:
    return num + findSum(num-1)
  else:
    return 0

x = findSum(5)
print(x)  # 15

Variable Length Argument (*args and **kwargs)

*args

When defining a function, the * operator can be used to capture an unlimited number of positional arguments passed to the function.

These arguments are captured into a tuple.

It captures unlimited number of arguments in the sense that you do not know beforehand how many arguments can be passed to your function by the user.

Example:

def func(*args):
  print(args)

func(1, 54, 60, 8, 98, 12)

Output:

(1, 54, 60, 8, 98, 12)

**kwargs

Similarly, the ** operator is used to capture an unlimited number of keyword arguments passed to the function.

These arguments are captured into a dictionary.

Example:

def func(**kwargs):
  print(kwargs)

func(name='Bob', job='developer')

Output:

{'job': 'developer', 'name': 'Bob'}

Both *args and **kwargs

By default, Python captures all unmatched positional arguments into a tuple and keyword arguments into a dictionary.

Example:

def func(name, *args, **kwargs):
  print(name+' is a '+args[0]+'.')
  print('He earns $'+args[1]+' a year.')
  print('He works for '+kwargs['company']+'.')
  print('He lives in '+kwargs['city']+'.')

func('Bob', 'developer', '40,000', company='ABC', city='Seattle')

Output:

Bob is a developer.
He earns $40,000 a year.
He works for ABC.
He lives in Seattle.