What Is Python Functions ? | Working With Python Functions

Here are simple rules to define a function in Python.

  • It begin with the keyword def followed by the function name and parentheses ( ( ) ).

  • Any input parameters or arguments should be placed within these parentheses. You can also define parameters inside these parentheses.

  • The first statement of a function can be an optional statement - the documentation string of the function or docstring.

  • The code block within every function starts with a colon (:) and is indented.

  • The statement return [expression] exits a function, optionally passing back an expression to the caller. A return statement with no arguments is the same as return None.


def functionname( parameters ):
   return [expression]

Practice Example:

In-build Functions: Import, Function

1. Import

  • import statement allow you to import a python module so that you can use functions defined in that module

# example import
import datetime as dt

# create a datetime object
now = dt.datetime.now()

# extract the hour
hour = now.hour
hour = 22
if hour<12: print("Good Morning!")
elif 12<=hour<21: print("Good Afternoon!")
else: print("Good Night!")

2. Function

  • defined using def keyword followed by identifier and a colon

  • the purpose is for modularity and reusability

# Simple function to add two numbers
def add_two_numbers(x,y):
    return x+y

print(add_two_numbers(10, -2))

# you can have a global variable in python
def add_to_default(x):
    return x+default

default = 7

# Variable Length Arguments
def accumulate(*args):
    for a in args:
    return x

print("The total is ", accumulate(*x,8,9))

# example function return multiple values
def f():
    x=5; y=6; z=7;
    return x, (y,z)

first, (a, b) = f()
print(first, a, b)

2.1 Lambda Function

  • anonymous function that allows us to perform certain computations quickly

# example of lambda function
res = lambda x: x*2

# example of lambda function
y = lambda a1, a2, a3: (a1+a2)*a3

def apply_to_list(a_list, func):
    return [func(x) for x in a_list]

seq = [5, 7, 0, -2]
print(apply_to_list(seq, lambda x: x*2))

# we can simply do
print([x*2 for x in seq])

Partial Function

It is useful when we want to call a function repeatedly, e.g., testing different ML algorithms, or testing different parameters for the same ML algorithm, but at the same time keeping some parameters the same

def fun_model(a, b,c):
    return 5*a + 3*b +c

# assume that we want to keep var a and b to be 10
# using lambda
weight_10 = lambda x: fun_model(10,10,x)

# using partial
from functools import partial
weight_10 = partial(fun_model, 10, 10)


  • Python documentation https://docs.python.org/3/

1 view0 comments