A Simple Calculator: Revisted — #LearnPythonthroughProjects Series 9

Wow! Look how far we have come. Thumbs up👍🏼. Let’s keep the fire burning.

Remember we built a simple calculator earlier(Link here), and I mentioned we will be revisiting the project to improve its functionality, whilst also learning and exploring more concepts in Python? Well, in this project, we will build a calculator using the concepts of modules and functions in Python. The concept of Modular programming was introduced in the previous project. We explored how modules can be used to improve code efficiency and execution. Recall, I mentioned that modules can be made of variables(which could also be data structures), functions, and/or classes. In this project, we will take a step further by learning how to create and use functions in Python. We will also learn how to create and work with user-defined modules.

Let’s get into building the project.

PROJECT STEPS:

  1. Create a python file and save it as “mod.py”. This will be the module file.
  2. Create another python file, and save it as ‘calc.py’. This is the main program file. Make sure to save both files in the same folder
  3. In ‘mod.py’, type the following, and save:

Great!

4. In ‘calc.py’, type the following.

calc.py

Great!

Let’s test the program.

Save and Run ‘calc.py’

Call out the program using “calc_run()” in the Python Shell(This will be explained soon).

program run

Great job!

CODE EXPLANATION

In the previous project, we explored the use of built-in python modules. In this project, we created a user-defined module using ‘Functions’ in python.

So what are Functions?

Source: Here

As a programmer, there will be times when you want to be able to run certain lines of code in sequence and repeatedly. When you need a single block(or blocks) of code multiple times in a program, should you write it every single time, over and over again? Absolutely not! That sounds so tiring😮😥. This is where functions come into play. They represent a part of programming called ‘Do Not Repeat Yourself(D.R.Y)’. Functions allow code Reusability without the need for repetition.

Fun fact: You use functions everyday. Think about an action you do daily/fequently which automatically works at specific times , like an Alarm clock for example.

Just like Flow control statements, Functions are organized blocks of code defined in a set of steps/sequences for some specific task/action. They are however different concepts in Python.

There are two types of functions in Python

  • Built-in functions
  • User-defined Functions

So far, we have already explored some of Python’s built-in functions:

Such as range(), input(), round(), int(), float(), print() et cetera.

Do some research and explore more built-in python functions

For user-defined functions, as we already know, these are functions created outside the default python functions for specific purposes.

To declare/create a function in Python, three key things are needed:

  • def keyword
  • Function name and parentheses (e.g calc_run())
  • Function Statements
Function Syntax: Image Source: Real Python

Other things could be:

  • Function arguments, parameters
  • Docstrings to explain the purpose of the function to an external viewer/user.
  • Function exit or closing statement( return, pass, exit, quit, print et cetera)

Once defined/declared, functions can be called from anywhere in the program using the function name.

Did you notice that after saving the ‘calc.py’ program earlier, nothing was displayed? This is because since the program was enclosed in functions, nothing would work until the function name is called. So once a function has been declared, in other to get it running, the name has to be called, i.e the name with which it was defined/declared.

For example, to get the program running earlier, we had to call out the function name, ‘calc_run()’. The function name goes along with the parentheses and if arguments have been added while defining the functions, these arguments have to be included as well.

Let’s explain that.

What better way than with code example

Open a new file and save as test.py

Type the following lines of code.

Notice that while declaring the function name ‘add’, two arguments were added ‘x,y’.

Curious what difference it makes? Run the code and call out the function.

Save, run the program, and call the function using the name ‘add()’.

Oops! Did you get an error?

So why did that happen? When an argument is declared alongside a function name, it has to be accounted for as well when calling the function. There different types of function arguments in Python.

  • Required Arguments — These are also called Positional arguments. They could be in the form of any data types or data structures and must be included when calling out a function. Just as seen above. By default, if not specified, python assumes this argument.
  • Keyword Arguments (identifiers, *args , **kwargs): These are special ways of using arguments in python. We will explore this as we proceed in the future.
  • Default arguments — arguments that take a default value if no argument value is passed during the function call. Can be assigned with the ‘=’ sign in python.

So to fix the previous error, since it’s a required argument, we simply call the function and include the required arguments, as follows:

Did you see that? This type of argument plays an important role when creating a program for the required fields.

What difference will it make if it was a default argument?

Repeat the above example as follows:

The default argument works in such a way that if a user forgets to input a parameter, the program automatically assumes a default parameter and runs without errors. This could work in a way such that if a user does not enter a name when launching a program, assign the name ‘Guest’ to the user. Awesome right!.

So when the function add(), is called, if two parameters are included, it sums them up if not, it assumes a default value of ‘5’ and returns the sum.

Values can be passed as parameters to a function and values can be returned from a function as well. Earlier, after declaring the function ‘cal_run()’, two parameters (num1 and num2) were defined, then the values were returned based on whatever operation was selected by the user.

For the returned values, we called out functions from the module we had created ‘mod.py’. In mod.py, operations were created using functions as well(add, sub, mult and div).

CREATING A USER DEFINED MODULE

Remember that Modules can consist of functions, classes, and variables, saved with a default file extension(.py), which can be used repeatedly. So creating a module in python is very simple, it only involves saving a file with .py file extension and calling out a variable, function, or class for use in other programs. Just as implemented earlier. However, the created module has to be saved in the same directory as the program where it will be used.

As explored in the previous project, to use a module, it has to be imported. There are several ways of doing so.

  • Importing the just the module name

Examples:

import random

import mod

import math

  • Importing the module using an alias

Examples;

import random as rd

import mod as md

import mod as mod

import math as mt

  • Importing the module and all its functions using ‘ *

Example;

from random import *

from math import *

from mod import *

This simply importing all the functions from a module for use. This might not always be efficient though, you might just want to import what is required for a particular purpose.

Earlier, for use, the mod.py module was imported using an alias. Although I used an alias similar to the name of the module, you can change the name to anything desired(md, me, etc).

Let’s see the difference with using the * rather than an alias.

Modify ‘ calc.py’ as follows.

code input
code output

Works fine!

So the usage depends on the individual and the purpose.

We will draw the curtain here for this series!

Stay tuned for the exciting things functions can be used for in Python.

Did you notice after executing an operation, the program exits? What do you think can be done here? Why don’t you try adding a loop? Explore which of the loops would work best here. HAPPY CODING!

Find the link to the Github repository below.

THANK YOU FOR READING! SEE YOU IN THE NEXT SERIES!!

SOCIAL MEDIA CONNECT

LinkedIn: https://www.linkedin.com/in/aminah-mardiyyah-rufa-i

Twitter: @diyyah92

Data Scientist/Machine learning/AI enthusiast