Lesson 2: Functions and Modules

Functions

  1. Block of organized, reusable code that is used to perform a single, related action
  2. Provide better modularity for your application and a high degree of code reusing
  3. Python gives you many built-in functions like print(), len() etc..
  4. It is also possible to define user-defined functions
  5. Global vs. local variables

Write a small function that checks if the number entered by the user is 5


In [1]:
# FUNCTION DEFINITION
def check_if_5(user_number):
    """This function just checks if the number passed to it is equal
    to 5. It returns 1 if the number is 5 and returns 0 if the number is not 5 """
    if user_number == 5:
        return 1
    else:
        return 0

#FUNCTION CALL
return_val = check_if_5(5)

if return_val == 1:
    print("It is 5")
else:
    print("It is not 5")


It is 5

Modules

  1. A set of related functions can be grouped together as module
  2. A module is nothing but a python file
  3. The open source community continuosly builds modules and makes it available for us
  4. To access these modules we need to use the "import command"

Let us import a commonly used module and access one of its functions.


In [2]:
import random
print('A random number between 1 and 6 is: ',random.randint(1,6))


A random number between 1 and 6 is:  6

It is also possible to import specific functions from within the module directly. When you do this make sure you have not used the same name for your function.


In [3]:
from random import randint
print('A random number between 1 and 6 is: ',randint(1,6))


A random number between 1 and 6 is:  3