how to make a calculator in python
gatorade322 (96)

This is going to be a tutorial for beginners who know the basics of python. That is floats, and input and print. So, were going to start with two lines of code:

import math
while True:
    math = input()

This will get the computer the information for it to know if we are going to do multiplication, division, addition, or subtraction. We will start with addition:

    if d == “plus”:
        digit_1 = input()
        digit_2 = input()

This will get us all the inputs we need. If you want, you can add a + or plus in there, but I just just put nothing. This is what it would look like if there was a plus:

    if d == “plus”:
         digit_1 = input()
         digit_2 = input(“plus or +”)

Next we need to add it together. We can’t do answer = digit_1 + digit_2, or that would be monkey math (which would be funny, but we don’t want it in our calculator). You can do that if you want. So we will just add float(digit_1) + float(digit_2) instead:

answer = float(digit_1) + float(digit_2)
print(answer)

The rest of the code is basically the same, but with -, *, and /. So just copy and paste this all in to your repl:

    elif d == "minus":
        a = input()
        b = input()
        c = float(a) - float(b)
        print(c)

    elif d == "square":
        a = input()
        b = float(a) * float(a)
        print(b)

    elif d == "divide":
        a = input()
        b = input()
        if b == "0":
            print("infinity")
        else:
             c = float(a) / float(b)
             print(c)
    
    elif d == "times":
        a = input()
        b = input()
        c = float(a) * float(b)
        print(c)

It’s pretty simple. I’ll just explain the infinity filter. If you divide anything by zero it’s infinity. If you don’t add the filter, there will be a divide by zero error. So we just check if it’s zero, and if it is, it will print infinity. Also simple!

I hope you liked this tutorial. It was really fun to make. I also hope this influences future coding, and I hope you have fun coding!
Goodbye.

You are viewing a single comment. View All
gatorade322 (96)

I'll try that. I might not be able to post the new version though. Upvote for the seggustion! :D