Featured

    Featured Posts

How to write a very simple calculator in Python as a complete beginner programmer


As I progress with my journey as a computer coder, I have realized that for one to master the art of writing scripts and applications, hours of practice matter more than months of study being spent on How To Program books. Reading theory about computer programming matters, but it does not make one a code writer. Based on such conclusion, I have decided to share real world scenarios materialized in computer code, mostly Python.

Through this article you're going to learn how to put in practice basic concepts in Python with the main purpose of pushing your skills to the next level as a doer, instead of just a thinker.

Although once finished you will end up with a simple calculator which supports basic maths, at least you will know how to properly make use of builtin utilities such as input, def statements and the while True loop.

The logic behind the calculator 

The calculator should display information on the supported operations during its initial execution, ask the user for custom input, perform the specified task and print the result on the console. Being more concrete, the following should appear on the console once the program is executed for the first time.
The 'add' option activates addition.
The 'divide' option activates division.
The 'multiply' option activates multiplication
The 'subtract' option activates subtraction.
The 'powers' option raises a number to the power of another.
The 'sqrt' option finds the square root of a number.
Input your command:
The above should be stored inside a function so the program can call it constantly inside the while True loop. The following is the pseudocode which helps to create a visual idea on your mind on how the above output should be materialized as part of the Python program.
def calc_info():
    print("The 'add' option activates addition.")
The name of the function is calc_info, but it does not really matter as long as it is readable and describes itself properly.

Since the calculator is supposed to constantly ask the user for an option, the above function should be placed inside the while True statement which helps to run the program forever.

Being concrete, the following pseudocode should be useful to you.
while True:
    calc_info()
As you may have guessed, once the information on the supported operations is displayed on the console, the program should ask the user for custom input. Fortunately for us, Python has a builtin utility called input, which prompts the user for input.

The input utility should be placed inside the while True loop, just like the calc_info().
while True:
    calc_info()
    command = input("Input your command:")
As for now, just focus on the logic behind the application, the algorithm which is going to give life to our calculator.

The operation which the calculator is going to perform depends directly on the custom input provided by the user, input which is stored to the variable command as a string. Once the program has managed to store the user's input data, the program should perform checks on it through conditional statements.
if user_input == 'add':
    # do addition
elif user_input == 'multiply':
    # do multiplication
else:
    print("Your command should be in supported operations")
Another function is required to store the while True loop and the conditional statements.
def calc():
    while True :
        calc_info() 
        command = input("Input your command:")
        if user_input == 'add':
            # do addition
        elif user_input == 'multiply':
            # do multiplication
        else:
            print("Your command should be in supported operations")

Implementation of the calculator in pure Python code

Note: Before going any further, make sure to create a file called mycalc.py so you can save the code being shared through this article.

The function calc_info should be composed of multiple print statements which inform the user on the supported operations by our simple calculator. Once the above function is executed it runs the multiple print statements and displays information on the console. With the main purpose of demonstrating the role of the above function, run a Python interactive shell and type the following.
from mycalc import calc_info
calc_info()
The result of the above code's execution should be similar to the output shown below.
The 'add' option activates addition.
The 'divide' option activates division.
The 'multiply' option activates multiplication
The 'subtract' option activates subtraction.
The 'powers' option raises a number to the power of another.
The 'sqrt' option finds the square root of a number.
The 'cos' option finds the cosine of a number.
With the help of a new function, we implement the main logic behind the calculator.
The custom function calculator activates the while True statement, a Python's builtin which runs the program forever. As you can see from the piece of code shown above, the program asks the user for custom input, checks it through a conditional statement and performs the requested operation. With the main purpose of demonstrating the above code in action, run the following in the Python's interactive shell.
from mycalc import calculator
calculator()
Once the above has been finished executing in the Python's interactive shell the following should be displayed on the console.
The 'add' option activates addition.
The 'divide' option activates division.
The 'multiply' option activates multiplication.
The 'subtract' option activates subtraction.
The 'powers' option raises a number to the power of another.
The 'sqrt' option finds the square root of a number.
The 'cos' option finds the cosine of a number.
Enter your command:
Type the following when the program prompts your for input.
'add'
If everything works like it should, the program will prompt you again for input.
Enter the first number: 5
Make sure to enter the first number. Once done, the program will prompt you again for the second number.
Enter the second number: 10
Same thing as with the first number here. Just type the second number which you want to add to the first one. Once done, the program will display the result on the console and start again from the beginning.
The result is 15.0
The 'add' option activates addition.
The 'divide' option activates division.
The 'multiply' option activates multiplication.
The 'subtract' option activates subtraction.
The 'powers' option raises a number to the power of another.
The 'sqrt' option finds the square root of a number.
The 'cos' option finds the cosine of a number.
Enter your command:
Theoretically the program should run forever since the logic behind the application is placed under the while True statement. Hit CTRL + C on your keyboard to interrupt the program.

For the calculator to support other operations such as multiplication, division and all the rest; other input checks should be performed.
Keep in mind to always test the code as you write it. As for now restart the Python's interactive shell and experiment with the rest of the operations supported by the calculator.
from mycalc import calculator
calculator()
Let's test if the operation division works properly.
The 'add' option activates addition.
The 'divide' option activates division.
The 'multiply' option activates multiplication.
The 'subtract' option activates subtraction.
The 'powers' option raises a number to the power of another.
The 'sqrt' option finds the square root of a number.
The 'cos' option finds the cosine of a number.
Enter your command:'divide'
The program is going to prompt again, asking for the numbers.
Enter the first number:4
Enter the second number:2
As shown earlier, the program will display the result on the console and later ask the user for another command.
The result is 2.0
The 'add' option activates addition.
The 'divide' option activates division.
The 'multiply' option activates multiplication.
The 'subtract' option activates subtraction.
The 'powers' option raises a number to the power of another.
The 'sqrt' option finds the square root of a number.
The 'cos' option finds the cosine of a number.
Enter your command:
The only thing left is to code the sqrt and cos operations. As you may be aware, the operation sqrt finds the square of a given number, the operation cos finds the cosine of a given number. Fortunately for us, Python has a builtin library which has implemented solutions for such operations.

Type the following command on your Python's interactive shell.
import math
Then find the square root of a number through the following method.
math.sqrt(64)
8.0
As for the cosine of a number, the following method can be used.
math.cos(20)
0.40808206181339196
The final code is being shown below. The following command can be used to run the calculator.
python mycalc.py
Copyright hackermilk.blogspot.com
author

janoroot

I fight for justice, righteousness and divine order on mother Earth. My main objective is to become a true man. As a soul who felt connected with Russia since a little kid, orthodox kozaks is my main definition of manhood.

Always curious on how stuff works under the hood, computer hacking has always been my way of materializing the true essence of my soul in the third dimension. My life as a hacker got really interesting when I discovered Python and Ubuntu Linux. Thirsty for knowledge, open source technologies are my main toys.

With the main purpose of adding joy on my journey as a computer nerd, I have decided to connect with hackers and aspiring ones through the content I do publish on this website. Being published on well established computer technology websites such as sitepoint and digitalocean, I produce high-quality content for anyone who is interested in improving their hacking skills further.

As a Python coder who spends most of his time creating projects from scratch and hacking various libraries, I am the savior to the beginner and the intermediate programmer.

Get Free Email Updates to your Inbox!

Post a Comment

www.CodeNirvana.in

Blog Archive

Recent Posts

Translate

Total Pageviews