10  Functions and Recursion

10.1 Function

A function is a group of related statements that performs a specific task.

Functions help break our program into smaller and modular chunks. As our program grows larger and larger, functions make it more organized and manageable. Furthermore, it avoids repetition and makes the code reusable any number of time.

10.1.1 Syntax

Above shown is a function definition that consists of the following components.

  • Keyword def that marks the start of the function header.

  • A function name to uniquely identify the function. Function naming follows the same rules of writing identifiers in Python.

  • Parameters (arguments) through which we pass values to a function. They are optional.

  • A colon (:) to mark the end of the function header.

  • Optional documentation string (doc string) to describe what the function does.

  • One or more valid python statements that make up the function body. Statements must have the same indentation level (usually 4 spaces).

  • The statement return exits a function, optionally passing back a value..

10.1.2 Example

Welcome to the World of Python, Raja

10.1.3 Quick Quiz

  1. Define a function to return the absolute value of the entered number.

  2. Define a function to day Hello, good morning “name”, if the person in your contact list, otherwise ask “Who are You”

10.2 Type of functions

Basically, we can divide functions into the following two types:

  1. Built-in functions - Functions that are built into Python.

  2. User-defined functions - Functions defined by the users themselves.

For example, len( ), range ( ) and print( ) are built-in functions, and the greet function defined above is a user-defined function.

10.3 Functions with arguments

Hello ahmad, how are you

Here, the function greet1() has two parameters.

Since we have called this function with two arguments, it runs smoothly and we do not get any error.

If we call it with a different number of arguments, the interpreter will show an error message. Below is a call to this function with one and no arguments along with their respective error messages.

TypeError: greet1() missing 1 required positional argument: 'msg'

10.4 Default argument or parameter value

Function arguments can have default values in Python. We can provide a default value to an argument by using the assignment operator (=). Here is an example.

Hello Ahmad, How do you do

The input to a function is called a formal parameter.

A variable that is declared inside a function is called a local variable. The parameter only exists within the function (i.e. the point where the function starts and stops).

A variable that is declared outside a function definition is a global variable, and its value is accessible and modifiable throughout the program.

5

10.5 Recursive function

Recursion is the process of defining something in terms of itself. That is, a function that calls itself. For example:

factorial(n)=n * factorial(n-1)

10.5.1 Example:

6

10.5.2 Return Values

The Python return statement is a special statement that you can use inside a function or method to send the function’s result back to the caller. To let a function return a value, use the return statement:

above example can be wrapped in a function as:

6

Using Recursion

6

10.6 Pre-defined Functions

There are many pre-defined functions in Python, so let’s start with the simple ones.

The print() function:

[10.0, 8.5, 9.5, 7.0, 7.0, 9.5, 9.0, 9.5]

The sum() function adds all the elements in a list or tuple: try pease

The len() function show the length a list or tuple: try please

10.7 Exceptions

An exception is an error that occurs during the execution of code. This error causes the code to raise an exception and if not prepared to handle it will halt the execution of the code.

10.7.1 Exampls

Run each piece of code and observe the exception raised

ZeroDivisionError: division by zero

10.8 Exercise_Functions

  1. Create a function con that add two number .

  2. Can the con function we defined before be used to concatenate lists or tuples?

  3. Write a function named odd_or_zero which takes one parameter, a number, and returns that number if it is odd or returns 0 if the number is even. Then using a list comprehension which iterates over a_list and calls your odd or zero function for each value, print a list like the following: [ 1, 0, 3, 0, 5, 0, 7, 0, 9, 0 ]

  4. Define a function to find the greatest of three numbers using.

  5. How do you prevent python print( ) function to print a new line at the end.

  6. Write a recursive function to calculate the sum of first n natural numbers.

  7. Write a function to print first n lines of the following pattern.
    *****
    ***

    *

  8. Write a function which converts inches in cm

  9. Write a function to remove a given word from a string and strip it at the same time.

  10. Write a Python function that takes a list and returns a new list with unique elements of the first list. Sample List : [1,2,3,3,3,3,4,5], Unique List :[1, 2, 3, 4, 5]