Python functions

  • A function is a block of code which only runs when it is called.

why to use function

  • Automate repetitive tasks
  • Allow code reuse
  • Improve code readability
  • Clean-up code
  • Allow easier refactoring

keywords

  • def - function start
  • return - return result of function
  • pass - do nothing

python function syntax

def <function_name>(<params>):
    # <statement>
    # <statement>
    return <value>

find factorial of a number

  • write a function to find the factorial of a given number
def factorial(number):
    result = 1
    for i in range(1, number+1):
        result = result * i
    return result
# call the function
print(factorial(4))
# Output: 24
print(factorial(5))
# Output: 120

one line function - lambda

  • we can write a one line function using keyword "lambda"
square = lambda x: x**2
print(square(5))
# output: 25

default params

  • we can pass default params to a function
def add(x=10, y=20):
    return x + y

# called func with no arguments
default = add()
print(default)
# output: 30
# call func with arguments
result = add(1, 2)
print(result)
# output: 3

positional argumets & keyword arguments

  • we call a function without keyword arguments then it considers the position and assigns values accordingly.
  • otherwise, we need to pass value with keyword.
  • check the below examples
def pow(x, y):
    return x ** y

# call by positional argument
result = add(3, 2)
print(result)
# output: 9

# call by keyword argument
result = add(y=3, x=2)
print(result)
# output: 8

number of params are unknown - *args, **kwargs

  • *args are used when number of params are unknown.
  • **kwargs are used when number of keyword params are unknown
  • chek the below examples
def sum(*args):
    total = 0
    for num in args:
        total += num
    return total

print(sum(1,2))
# output: 3
print(sum(1,2,3))
# output: 6
print(sum(1,2,3,4,5))
# output: 15
  • *args results in a tuple. hence, we can iterate over it.
def print_data(**kwargs):
    for k, v in kwargs.items():
        print(f'{k} = {v}')

print(print_data(first_name="Anji", last_name="B"))
# output: 
# first_name = Anji
# last_name = B

print(print_data(physics="PHY", maths="MAT", social="SOC"))
# output:
# physics = PHY
# maths = MAT
# social = SOC
  • **kwargs gives a dictionary. so, we can use dict methods and iterate over it.

References