Writing Four Functions to Perform Different Arithmetic Operations in Python

2 hours
  • 4 Learning Objectives

About this Hands-on Lab

In this hands-on lab, we will attempt to write four functions that will perform different arithmetic operations: addition, subtraction, multiplication, and division.

Learning Objectives

Successfully complete this lab by achieving the following learning objectives:

Create a File and Make It Executable
  1. Create the file:

    touch myFile.py
  2. Make it executable:

    chmod +x myFile.py
Write Three Functions That Are Able to Add, Subtract, and Multiply Two Numbers
  1. Open the file:

    vim myFile.py
  2. Add the following to the file:

    #!/usr/bin/python
    
    def add(n1, n2):
        return n1+n2
    def sub(n1, n2):
        return n1-n2
    def multi(n1, n2):
        return n1*n2
Write a Function to Divide Two Numbers and Implement a Check for Division by 0
  1. Add the following to the file:

    def div(n1, n2):
        if n2 == 0:
            return "ERROR: Cannot divide by 0. Second parameter cannot be a 0!"
        else:
          return n1/n2
Run Tests and Call All Four Functions
  1. Add the following to the file:

    n1 = 10
    n2 = 11
    
    print(add(n1, n2))
    print(sub(n1, n2))
    print(multi(n1, n2))
    print(div(n1, n2))
    n2 = 0
    print(div(n1, n2))
  2. Save and exit the file by pressing Escape followed by :wq.

  3. Call all four functions:

    ./myFile.py

Additional Resources

There are multiple ways of performing this lab. You can use the Python interactive console or write your code to a file.

In case you decide to write your code to the file, you will need to do the following.

  1. Create your file (you can change the file name if you wish):

    touch myFile.py
  2. Change file permission to make it executable:

    chmod +x myFile.py
  3. When you populate the file with your code, execute it with:

    ./myFile.py

In case you decide to use the Python interactive console, run the following:

python3

From there, you can continue writing your code.

The Python path is:

/usr/bin/python3

What are Hands-on Labs

Hands-on Labs are real environments created by industry experts to help you learn. These environments help you gain knowledge and experience, practice without compromising your system, test without risk, destroy without fear, and let you learn from your mistakes. Hands-on Labs: practice your skills before delivering in the real world.

Sign In
Welcome Back!

Psst…this one if you’ve been moved to ACG!

Get Started
Who’s going to be learning?