Defining a function

We can define our own functions in Python and reuse them throughout the program.


Syntax

def functionName(parameters): code detailing what the function should do

    return [expression]



def tells the program that the indented code from the next line onwards is part of the function. return is the keyword that we use to return an answer from the function. There can be more than one return statements in a function. However, once it executes a return statement, it will exit. If it does not need to return any value, we can omit the return statement. Alternatively, we can write return or return None.


Let's now define our first function. Suppose we want to know if a number is a prime number. Here is how we define the function using the modulus and the for loop and the if statement.


Example

def checkIfPrime(numberToCheck):

    for x in range(2, numberToCheck):

        if (numberToCheck%x == 0):

            return False

        return True

In the function above, lines 2 and 3 uses a for loop to divide the given parameter numberToCheck by all numbers from 2 to numberToCheck - 1 to determine if the remainder is zero. If the remainder is zero, numberToCheck is not a prime number. Line 4 will return False and the function will exit.

If by last iteration of the for loop, none of the division gives a remainder of zero, the function will reach Line 5, and return True. The function will then exit.

This is how we will use the function:

answer = checkIfPrime(numberToCheck = 7)

Here we are passing 7 as the parameter. We can then print the answer by typing print(answer). The output will give True.

No comments:

Post a Comment