top of page

Functions in Python

Updated: Apr 19, 2023

Functions are small units of code that carry out specific functionalities as defined by the user.




The syntax is def followed by the function name.


A function either returns a value or not.



def fun_1():
    print("Metric Coder")

fun_1()

A function can take any number of parameters as seen in this example.



def fun_2(a, b):
    print(a, b)

fun_2(10, 20)


If the number of parameters are unknown, we can use * before the variable name.



def fun_3(*a):
    for x in a:
        print(x)
        
fun_3(1, "a", 3)

If there are many keyword arguments and you do not know how many such arguments will be passed, then we can use ** before the variable name.



def fun_3(**a):
    for x in a:
        print(x, a[x])
        
fun_3(k = 1, l = "a", m = 3)


The default value of the variable can be defined in the function definition. As a result, when the function is called and if the parameter is not passed, then the default value is used.



def fun_4(a = 3):
    print(a)
    
    
fun_4()
fun_4(20)


def fun_5():
    return 10

x = fun_5()
print(x)

The link to the Github repository is here .

Subscribe to get all the updates

© 2025 Metric Coders. All Rights Reserved

bottom of page