Learning Python: Programming and Data Structures- Tutorial 7- Functions and Recursion; Multiple Function Arguments and Partial Functions

An Example of Functions in Python

This program demonstrates simple functions in Python. 
One function returns the cube of a number.
Another function performs operations on Strings.

def cube(n):
    a ** b means a^b.
    eg : 2**3 = 2 x 2 x 2 = 8
    return n ** 3

def string_operation(s):
    String is an immutable object. So whatever operations we perform on strings
    a new string is generated and the original string stays the same.
    # Capitalize makes the first letter of the string capital
    print('Capitalized String :', s.capitalize())

    # To find a substring in a given string, python has a function called find(). 
    # If the substring is present in the string, it returns index of its first entry, otherwise -1.     
    print('To find whether the string has the phrase "oper" in it', s.find('oper'))

    # The index function returns the first index location where the substring is contained.
    # It raises a ValueError if the substring is not there. That's why we use find().
    if (s.find('oper') != -1):
        print('Index of "oper"', s.index('oper'))

    print('True if all the characters are alphanumeric and the string is not empty', s.isalpha())

    print('True if all the characters are digits otherwise false', s.isdigit())

    print('Generates a new string with characters capitalized', s.upper())

def volume(length=10, breadth=10, height=10):
    In the function header we have assigned default values of length, breadth and height
    that is to say if the function is called with only 2 parameters given, then the 
    value of height will be taken as 10.
    return(length * breadth * height)

def main():
    # Print the cube of a number
    num = int(input("Enter a number : "))
    print("The cube of the number is :", cube(num))
    # String Operations
    n = input("Enter a string : ")

    # Volume of a cuboid
    l = int(input("Enter length : "))
    b = int(input("Enter Breadth : "))
    h = int(input("Enter Height : "))
    print("Volume of cuboid :", volume(l, b, h))

if (__name__ == '__main__'): main()

Fibonacci Series in Python : An Example of a Recursive Function

The Fibonacci series is a popular example of a recursive function, i.e. a function which calls itself.
A fibonacci series term is equal to the sum of the two preceding terms before it.

# encoding:UTF-8 ''' Fibonacci series is one in which a new number is generated by adding the previous two numbers. Eg : 0 1 1 2 3 5 8 13 21 34 55 89 Algorithm for finding Fibonacci number less than a certain number n Take base case f = 0 and l = 1. Then t = f + l is the new number. Then replace the first number f = l and l = t. Perform this operation recursively. ''' # f is the first number, l is the second number and n is the upper limit # of the series
def fibonacci(f, l, n): t = f + l if (t < n): print(t) return fibonacci(l, t, n) else: return t n = int(input("Enter the upper limit of the series : ")) fibonacci(0, 1, n)

The Output of the program code above:

~/hackerrank/nlp/spelling$ python ~/Desktop/Downloads/fibonacci.py 
Enter the upper limit of the series : 10

Computing GCD in Python using the Euclidean Algorithm: An Example of a Recursive Function

# encoding:UTF-8 ''' To find the GCD of two numbers is Euclid’s algorithm, which is based on the observation that if r is the remainder when a is divided by b, then gcd(a, b) = gcd(b, r). As a base case, we can use gcd(a, 0) = a. '''
def gcd(a, b): # Finding the remainder r = a % b if (r == 0): return b else : return gcd(b, r) print(gcd(3, 8)) print(gcd(1277, 154)) print(gcd(77, 140))

The Output of the Program Code Above:

:~/hackerrank/nlp/spelling$ python ~/Desktop/Downloads/gcd.py 

Multiple Function Arguments

Generally whenever we call a function, we specify a few parameters which are passed to the function.
In the function signature, we specify the number of variables which are received from the function call.
But say we don't know how many parameters are sent when the function is called ?
For this we use multiple function arguments which specify some variables and at the end includes a 
list variable which contains the rest of the variables passed to the function.

def f1(a, b, c):
    print(a, b, c)

def f2(a, *b):
	print (a, list(b))
f1(5, 6, 7)
f2(5, 6, 7)

# In order to go through each element passed to a function, we traverse the list.
def f3(a, *b):
    print (a)
    for i in b:
        print (i)

f3(5, 6, 7)
Source code: