DEV Community

Cover image for Build A Calculator Using Python
Faith
Faith

Posted on

Build A Calculator Using Python

Using Loops

This has to be the easiest way to apply your python skills after learning the basics. The best and only way to learn anything is through rolling your sleeves and practicing, python for this case is no exception. Just like any other rookie, I did really struggle with what to start with given some projects online are quoted "beginner" but ended up not being beginner friendly to me.
Yeah, I know this project is not all that, but it helps retain the concepts learnt and keeps the spark alive, at least it does for me.

Lines of Code

print("===== Advanced Calculator =====")
print("Basic: +, -, *, /")
print("Adv: power (^) and Modulus (%)")
print("Sci: sqrt, log")
print("Trig: sin, cos, tan")

# get the operator
op = input("\nEnter Operator: ")

# Binary operations
if op in ['+', '-', '*', '/', '^', '%']:
    num1 = float(input("Enter 1st num: "))
    num2 = float(input("Enter 2nd num: "))

    if op == '+':
        print(f"result: {num1 + num2}")
    elif op == '-':
        print(f"result: {num1 - num2}")
    elif op == '*':
        print(f"result: {num1 * num2}")
    elif op == '/':
        print(f"result: {num1 / num2}")
    elif op == '^':
        print(f"result: {math.pow(num1 , num2)}")
    elif op == '%':
        print(f"result: {num1 % num2}")
Enter fullscreen mode Exit fullscreen mode

This are lines of code that can be used to explore loops in python because theory alone doesn't cut it. The first part of the code, the one consisting of print() at the beginning, are an explanation of the arithmetic operators used, you don't really need to have it.

Top comments (0)