Functions in Python

Functions in Python

ยท

1 min read

What are Functions in Python?

Functions allow us to give a name to a block of code then invoke(call) that block of code using the name whenever we want.

Basic Example

def say_hello():
    print('hello')

Example

When we define a function we can write some help text within it which explains what the function does.

def greet():
    '''
    within these quotes, we can write the help text 
    this function simply prints hello
    '''
    print('hello')
    #We can look up the help text of any function using the built-in help method help(greet)

Example

The function can also take in parameters and use them inside the function.

def add(x,y)
    """
    this function adds parameters x and y and prints their sum.
    """
    print(x+y)

Example

The function can also return values to the caller.

def add(x,y)
    """
    parameters x and y and returns their sum.
    """
    return x+y
    #here we call add and assign itsreturn valueto variable sum
    sum=add(3,4)
    print(sum)  

Example

Functions can also return multiple values to the caller by returning a tuple.

def sum_and_diff(x,y)
    """
    this function returns the sum and the difference of x and y as a tuple.
    """
    return(x+y,x-y)
    result=sum_and_diff(10,5)            
    #(15,5)
    print(result)        
ย