Functions in Python

A function is a collection of connected statements that accomplishes a single purpose. Functions assist in segmenting our program into manageable, modular portions. Our program becomes more organized and controlled as it gets bigger and bigger. It also makes the code reusable and prevents repetition.

name = " Anisha"
print(len(name))
7

Defining Function

In Python a function is defined using the def keyword.

def add_two(a,b):
    return a+b
print(add_two(3,4))
7

Calling a Function

To call a function, we have to use the function name followed by parenthesis.

def called():
  print("Hello anisha")

called()
Hello anisha

Arguments

Functions accept arguments that can contain data.The function name is followed by parenthesis that list the arguments. Simply separate each argument with a comma to add as many as you like.

def three(a,b,c):
    return (a+b+c)

print(three(2,3,4))
9

Odd / Even

def odd_even(num):
    if num % 2 == 0:
        return "even"
    else:
        return "odd"
print(odd_even(9))
odd

Fibonacci series

def fibo(n):
    a = 0
    b = 1
    if n == 1:
        print (a)
    elif n == 2:
        print (a,b)
    else:
        print (a,b,end = " ")
        for i in range(n - 2):
            c = a+b
            a=b
            b=c
            print(b, end = " ")
fibo(10)
0 1 1 2 3 5 8 13 21 34