Modules and Function

Functions

Previously, we discussed the basic idea of a function. In this blog, we will learn in-depth about functions and how to create them.

FACT: We have been using a function consistently since the first blog, and that is the ‘print()’ function which to be specific is one of Python’s built-in functions.

Functions are a way to call a block of code without having to write them repeatedly, this drastically reduces the amount of code we have to write. Consider a scenario where I wish to print a pattern of stars twice, there are two ways to approach this, we print the pattern twice or we can call a function twice to print it.

# Printing the pattern for the first time
print("*")
print("**")
print("***")
print("****")
print("*****")
print("")

# Printing the pattern for the second time
print("*")
print("**")
print("***")
print("****")
print("*****")

As we execute the above, we get:

With functions, we can simplify our code but still display the same output.

def print_pattern():
print("")
print("*")
print("**")
print("***")
print("****")
print("*****")

# Calling the function twice to print the pattern twice

print_pattern() # Prints the pattern for the first time
print_pattern() # Prints the pattern for the second time

Try this yourself and you will see that using a function drastically reduces how much code we write. I am sure you are excited to begin writing your own functions, so let’s look at how we can create a function.
The syntax for creating a function is the following:

def <function_name>():
…. -code-

“def” is a keyword in Python that is reserved to define (or create) a function. More on keywords in a later blog.

NOTE: The four dots represent the 4 spaces inside a block of code and that space must be maintained throughout. Python, as we first discussed, has a strong emphasis on code readability and uses indentation as one of the means to achieve it.
Following the syntax let’s create a function named “print_text” with two print statements.

def print_text():
  print("Welcome to Verification Master!")
  print("Hope you’re enjoying this tutorial")

Earlier we had also used arguments, so let’s see how we can create our function with arguments. Consider the code below:

def print_name(student_name): # student_name is the parameter
print("Welcome to", student_name,"Verification Master, so glad you are here!")

# Robert, Zoey, Jeffrey are the arguments
print_name("Robert")
print_name("Zoey")
print_name("Jeffrey")

In this example, we have created a function that has a print statement and has a parameter called ‘student_name’. Whenever we call this function, we must now add a student’s name (as an argument) which is then used by the function.

NOTE: Often used interchangeably, parameters and arguments are not the same. Parameters represent the value required by the function at function definition {creation}, whereas arguments represent the value given to the function at function call {usage}.

We can also design functions to return a value that we can use in our code. This becomes useful when we want to repeat a computation ‘n’ times.

def add_function(number):
return number + 15

variable_1 = add_function(5)
print("Variable 1 now holds:", variable_1)

Modules

A module is a Python file that has code that is related to each other, i.e., functions, variables, and other declarations/definitions that are interrelated. Consider the module called “student”.

# class teacher
class_teacher = "Mrs. Johnson"

# class course
class_course = "Science"

def course_name(name):
'''Display course details'''

print(name, "is part of the", class_course, "course, which is taught by", class_teacher)

The code stored in student.py
We will access the contents of this file from another Python file called “main”.

import student

student.course_name("Physics")The code stored in main.py
As we run “main.py” we get :

Overwhelmed? Let’s analyze it. In our “student.py” file we created a function that has a parameter “name”; then in our “main.py” file the first line says import student, and we discussed imports when we talked about the math module. If you want to work with a module that you created all you need to do is add that file to your current directory and then import it by typing import, followed by the name of your module. (e.g., import student)

Importing a Function

If we wish to access a function in our module, we need to follow this syntax:
<module_name>.<function_name> (e.g., student.course_name)
An alternative way to call a specific function is:

from student import course_name

course_name("Physics")

This might seem tedious with a small amount of code, but with larger codebases, it has 2 benefits:
Importing an entire module can lead to larger file size and can slow down your program.
When we have to call a specific function from another module frequently, this way makes it less repetitious, as we can just call the function directly instead of specifying its module name first.

List all functions in a module

When working with modules we can check all of the available functions within a module, using “dir()”.

import student

print(dir(student))

This lists everything from our “student” module.

Pip

If you wish to see which all modules you have installed (excluding the pre-built modules), type the following on your command prompt:
pip list

NOTE: If you face a warning to update your pip run:

pip install --upgrade pip

If you wish to install a module, from the plethora of modules out there follow this syntax:
pip install <module_name>
Pandas is a popular module used in Python for Data Analysis, and so if I wish to install Pandas all I need to do is run:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments