40+ Python Calculator Examples

This post contains source code of 40+ Hand-Picked Python Calculator Examples that you can use for educational purpose. ( With credits to original owner ). If you want to modify and use the code for something else other than personal use then contact the owner for permission.

Some source codes of these python calculators are made using little bit of js and css.

Related Posts

Click a Code to Copy it, and Hover over a video to play it.

1. By BroFar

Basic python calculator by BroFar. The program asks for the first number then the second number after that the operator you want to use. It gives an output like – Your Expression and Answer is: 1.0 + 2.0 — 3.0. ( Source )

#Basic Calculator
#Enter first digit then second the operator
print ('This a super basic capculator\n')
print ('Created by BroFarOps 4/27/2019\n\n')
bro = float(input("Enter The First Number\n" ))
print(bro)
far = float(input("Enter the Second number\n"))
print(far)
ops = input("Enter the operator\n")

if ops =="+":
    print ('Addition')
elif ops =="-":
    print ('Subtraction')
elif ops =="*":
    print ('Multiplication')
elif ops =="x":
    print ('Multiplication')
elif ops =="/":
    print ('Division')
elif ops =="%":
    print ('Percentage')
elif ops =="a":
    print ('add')
elif ops =="s":
    print ('sub')
elif ops =="m":
    print ('mul')
elif ops =="d":
    print ('div')
elif ops =="p":
    print ('per')
elif ops =="A":
    print ('add')
elif ops =="S":
    print ('sub')
elif ops =="M":
    print ('mul')
elif ops =="D":
    print ('div')
elif ops =="P":
    print ('per')

print("\nYour Expression and Answer is:" )
print(bro)
print(ops)
print (far)
print("--------\n")

if ops =="+":
    print (bro+far)
elif ops =="-":
    print (bro-far)
elif ops =="*":
    print (bro*far)
elif ops =="x":
    print (bro*far)
elif ops =="/":
    print (bro/far)
elif ops =="%":
    print (bro%far)
elif ops =="a":
    print (bro+far)
elif ops =="s":
    print (bro-far)
elif ops =="m":
    print (bro*far)
elif ops =="d":
    print (bro/far)
elif ops =="p":
    print (bro%far)
elif ops =="A":
    print (bro+far)
elif ops =="S":
    print (bro-far)
elif ops =="M":
    print (bro*far)
elif ops =="D":
    print (bro/far)
elif ops =="P":
    print (bro%far)
else:
    print ("INVALID INPUT\n")
    print ('D D O')

2. By Scarlet Witch

Made by Scarlet Witch. You will need to enter the operation in single lines, whihc means first enter first number in first line then in the second line enter the operator after that in the third line enter the second number. The output will be in the format of ( SUM of 2 and 2 is 4 ). ( Source )

'''
Enter your input in this way:
    First number
    Operation 
    Second number

For Example:
    2
    +
    3
    
'''


try:
    print("Calcuator".center(55), '\n')
     
    first_no = input()

    if first_no.isnumeric() == False:
        print("Please input a number.")
        exit()

    operation = input()
    second_no = input()
    if second_no.isnumeric() == False:
        print('PLease input a NUMBER. ')
        exit()

    first_no = int(first_no)
    second_no = int(second_no)
    result = 0
    operation_name = 0
     

    if operation == '+':
        result = first_no + second_no
        operation_name = 'SUM'
    elif operation == '-':
        result = first_no - second_no
        operation_name = 'Difference'
    elif operation == '*':
        result = first_no * second_no
        
        
        operation_name = 'Product'
    elif operation == '%':
        result = first_no % second_no
        operation_name = 'Modulus'
    elif operation == '/':
        operation_name = 'Division'
        result = first_no / second_no 
    elif operation == '//':
        result = first_no // second_no
        operation_name = 'Quotient'
    elif operation == '**':
        result = first_no ** second_no
        operation_name = 'Exponent'
    else:
         print('Operation not recognized' )
         
    print(f'{operation_name} of {first_no} and {second_no} is {result }')
except:
    print('\n' 'An Error Occurred!') 
    print('''Enter your input in this way:
    First number
    Operation 
    Second number''')  

3. By iewiko

A small lightweight python calculator by iewiko. Enter first number press enter then enter the operator press enter then enter the second number and press enter to get the output. ( Source )

num1 = int(input(" "))
operator = input(" ")
num2 = int(input(" "))

if operator == "+":
    print(num1+num2)

elif operator == "-":
    if num1 > num2:
        print(num1 - num2)
    else:
        print(num2 - num1)

elif operator == "*":
    print(num1 * num2)

elif operator == "/":
    print(num1 / num2)

#incase in error
else:
    print("error")

4. By Mert Yazici

Made by Mert Yazici, it can calculate multiple math expressions. You can enter multiple operators and numbers like – 6 / 2*3 / 4 / 7, all in one single line with and without spaces in between. ( Source )

import sys
import codecs
import unittest
from itertools import groupby
from cmath import (
    sin, asin, sinh, asinh,
    cos, acos, cosh, acosh,
    tan, atan, tanh, atanh,
    sqrt, pi, e,
)
from math import (
    gamma, factorial, radians,
    gcd, ceil, floor, log, log10
)

sys.stdout = codecs.getwriter('utf_16')(
    sys.stdout.buffer, 'strict'
)

class UnknownFunctionError(Exception):
    pass

class Token:
    def __init__(self, t):
        self.t = t

    def __repr__(self):
        return type(self).__name__ + '("' + self.t + '")'

    def __eq__(self, other):
        return self.__class__ is other.__class__ and self.t == other.t

class UpArrow(Token):
    def __init__(self):
        self.t = '|'

class Func(Token):
    def __init__(self, t, arg_count=0):
        if t not in FUNCS:
            raise UnknownFunctionError(f'Function {t} is not defined')

        self._func = FUNCS[t]
        self.arg_count = arg_count
        self.t = t

    def __call__(self, *a):
        return self._func(*a)


class Op(Token):
    def __init__(self, t, func=None):
        self._func = func
        self.t = t

    def __call__(self, *a):
        return self._func(*a)

class UpArrowOp(UpArrow):
    def __init__(self, count):
        self.count = count
        self.t = '|'

    def __call__(self, left, right, count=None):
        count = count or self.count
        if count == 1:
            return left ** right

        elif right == 1:
            return left

        elif left == 0:
            return 1

        return self(left, self(left, right - 1, count), count - 1)

class Digit(Token):
    def __str__(self):
        return self.t

class Char(Token):
    def __str__(self):
        return self.t

OP_PREC = {
    '+': 1, '-': 1,
    '*': 2, '/': 2, 
    '^': 3, '#': 3,
    '|': 3,
    
}
DIGITS = '0123456789.j'
OPS = '()-+/*^ยฐ,!#%|'
OP_FUNCS = {
    '-': lambda a, b: a - b,
    '+': lambda a, b: a + b,
    '*': lambda a, b: a * b,
    '/': lambda a, b: a / b,
    '^': pow,
}
FUNCS = (
    'sin', 'asin', 'sinh', 'asinh',
    'cos', 'acos', 'cosh', 'acosh',
    'tan', 'atan', 'tanh', 'atanh',
    'sqrt', 'log', 'log10', 'gamma',
    'factorial', 'radians', 'min',
    'max', 'gcd', 'ceil', 'floor',
    'round',
)
FUNCS = dict(zip(FUNCS, (
    sin, asin, sinh, asinh,
    cos, acos, cosh, acosh,
    tan, atan, tanh, atanh,
    sqrt, log, log10, gamma,
    factorial, radians, min,
    max, gcd, ceil, floor,
    round,
)))

CONSTS = {'e': e, 'pi': pi}

def tokenize(expr):
    lst = []
    parens = 0

    for n in expr.lower():
        if n in DIGITS:
            if lst and lst[-1].t == ')':
                # (a+b)c -> (a+b)*c
                lst.append(Op('*', OP_FUNCS['*']))

            lst.append(Digit(n))

        elif n in OPS:
            if n == '|':
                lst.append(UpArrow())
                continue

            if n == '%':
                lst.extend([Op('/', OP_FUNCS['/']), 100.0 + 0j])
                continue

            if n == '(':
                parens += 1

            elif n == ')':
                if not parens:
                    return None

                parens -= 1

            if n == '-' and (not lst or lst[-1].t not in DIGITS + ')'): #unary minus
                lst.append(Op('#'))
                continue

            if lst and lst[-1].t in '+-/*^' and n not in '()':
                #Remove last item if last item is Op and current item is not unary minus
                lst.pop()

            elif lst and (n == '(' and (isinstance(lst[-1], Digit) or lst[-1].t == ')')):
                lst.append(Op('*', OP_FUNCS['*']))
   
            lst.append(Op(n, OP_FUNCS.get(n)))

        elif not n.isspace():
            if lst and isinstance(lst[-1], Digit):
                lst.append(Op('*', OP_FUNCS['*']))
            lst.append(Char(n))

    for i in range(parens):
        lst.append(Op(')'))

    tokens = []
    for k, v in groupby(lst, key=type):
        if k is Digit:
            n = ''.join(map(str, v))
            try:
                tokens.append(float(n))

            except:
                tokens.append(complex(n))

        elif k is Char:
            t = ''.join(map(str, v))
            if t in CONSTS:
                tokens.append(CONSTS[t])
            else:
                tokens.append(Func(t))

        elif k is UpArrow:
            count = len(list(v))
            tokens.append(UpArrowOp(count))

        else:
            tokens.extend(v)

    return tokens

def parse(tokens):
    #https://blog.kallisti.net.nz/2008/02/extension-to-the-shunting-yard-algorithm-to-allow-variable-numbers-of-arguments-to-functions/

    if tokens is None:
        return None

    out = []
    ops = []
    were_values = []
    arg_count = []
    for token in tokens:
        if isinstance(token, (complex, float)):
            if were_values:
                were_values[0] = True

            out.append(token)

        elif type(token) is Func:
            ops.insert(0, token)
            arg_count.insert(0, 0)
            if were_values:
                were_values[0] = True

            were_values.insert(0, False)

        else:
            if token.t == ',':
                while ops[0].t != '(':
                    out.append(ops.pop(0))

                if were_values.pop(0) is True:
                    arg_count[0] += 1

                were_values.insert(0, False)

            elif token.t == '!':
                ops.insert(0, Func('factorial', 1))

            elif token.t == 'ยฐ':
                ops.insert(0, Func('radians', 1))

            elif token.t == '(':
                ops.insert(0, token)

            elif token.t == ')':
                while ops[0].t != '(':
                    out.append(ops.pop(0))

                ops.pop(0)
                if ops and isinstance(ops[0], Func):
                    f = ops.pop(0)
                    a = arg_count.pop(0) + 1
                    were_values.insert(0, False)
                    f.arg_count = a
                    out.append(f)

            else:
                while (ops and ops[0].t != '(') and (type(ops[0]) is Func or (OP_PREC[token.t] <= OP_PREC[ops[0].t] and not (token.t in '^#|' and ops[0].t in '^#|'))):
                    out.append(ops.pop(0))

                ops.insert(0, token)

    out.extend(ops)
    return out

def eval_(expr, test=True):
    #https://en.m.wikipedia.org/wiki/Reverse_Polish_notation
    if test is False:
        print(expr, end=' = ')

    tokens = tokenize(expr)
    #print(tokens)
    rpn = parse(tokens)
    #print(rpn)
    if rpn is None:
        return 'Error'

    stack = []
    for i in rpn:
        if isinstance(i, (complex, float)):
            stack.append(i)

        elif type(i) is Func:
            slc = slice(-i.arg_count, None, 1)
            args = stack[slc]
            del stack[slc]
            stack.append(i(*args))

        else:
            if i.t == '#':
                stack.append(-stack.pop())
                continue

            try:
                o1 = stack.pop()
                o2 = stack.pop()

            except IndexError:
                return 'Error'

            stack.append(i(o2, o1))

    out = stack[0]
    if abs(round(out.real) - out.real) < 1e-10:
        out = complex(round(out.real), out.imag)

    if abs(round(out.imag) - out.imag) < 1e-10:
        out = complex(out.real, round(out.imag))

    if out.imag == 0:
        out = out.real
        if out.is_integer():
            out = int(out)

    return out

class Test(unittest.TestCase):
    def test_tokenize(self):
        cases = {
            '5!': [5.0, Op('!')],
            '(5!+22) * 3': [Op('('), 5.0, Op('!'), Op('+'), 22.0, Op(')'), Op('*'), 3.0],
            'sin(90ยฐ)': [Func('sin'), Op('('), 90.0, Op('ยฐ'), Op(')')],
        }

        inps = map(tokenize, cases.keys())
        outs = list(cases.values())
        self.assertSequenceEqual(
            list(inps), outs
        )

    def test_parse(self):
        cases = {
            '5+3': [5.0, 3.0, Op('+')],
            '(5+3) * 2': [5.0, 3.0, Op('+'), 2.0, Op('*')],
            '5 + 3 * 2': [5.0, 3.0, 2.0, Op('*'), Op('+')],
        }

        inps = map(
            lambda k: parse(tokenize(k)),
            cases.keys()
        )
        outs = list(cases.values())
        self.assertSequenceEqual(
            list(inps), outs
        )

    def test_eval_(self):
        cases = {
            'SiN(90ยฐ)': 1,
            'sin(pi/2)': 1,
            '1+(2*(2+1)+2-(3*2)+1)': 4,
            '6/2*3': 9,
            'tan(radians(45))': 1,
            'cos(0)': 1,
            '2^-3*4': 0.5,
            '-2 ^ 2': -4,
            '(-2) ^ 2': 4,
            '0.02(0.02)': 0.0004,
            '2 + 4': 6,
            '-2 + -4': -6,
            'sqrt(4)': 2,
            'sqrt(-4)': 2j,
            '4 + -2': 2,
            '2sin(90ยฐ)': 2,
            'max(2, 3, 4, log(64, 2))': 6,
            '6 * 3%': 0.18,
            '1 + 1%': 1.01,
            '((1 + 1))%': 0.02,
            '3|3': 27,
            '2||3': 16,
            '2|||||1': 2,
            '562||||||||||||1': 562,
            '2|2|2': 16,
            '2|(2||3/4)': 16,
            '2|5': 32,
            '3|4': 81,
            '2|||3': 2**16,
            '2|sin(90ยฐ)': 2,
            '2sin(45ยฐ + (30 + 15)ยฐ)': 2,
        }
        inps = map(eval_, cases.keys())
        outs = list(cases.values())
        self.assertSequenceEqual(
            list(inps), outs
        )
        self.assertRaises(
            UnknownFunctionError,
            lambda: eval_('unkfunc(123)')
        )

    def test_op_override(self):
        cases = {
            '2*-2': -4,
            '2/-2': -1,
            '2+*4': 8,
            '4*+2': 6,
            '4/+4': 8,
            '2^+6': 8,
            '2-^3': 8,
        }
        
        inps = map(eval_, cases.keys())
        outs = list(cases.values())
        self.assertSequenceEqual(
            list(inps), outs
        )

    def test_paren_autocomplete(self):
        cases = {
            '(2': 2,
            '(2(2 + 3)': 10,
            '(2(2+6': 16,
            '2)': 'Error',
            '2+3)2': 'Error',
        }

        inps = map(eval_, cases.keys())
        outs = list(cases.values())
        self.assertSequenceEqual(
            list(inps), outs
        )

i = input() or None
if i is None:
    unittest.main()
else:
    print(eval_(i, test=False))

5. By Caleb Guerra Ortega

A single line code calculator by Caleb Guerra Ortega. It supports multiple numbers and operators like – 2 + 2 – 2 * 2. ( Source )

print(eval(input()))

6. By Black Jesus!

Made by Black Jesus!. Enter the numbers and operators in different lines, first enter first number then operator then the second line, all in different lines. ( Source )

num1 = int(input(""))
op = (input (""))
num2 = int(input(""))    
if op =="+":
      result = str(num1 + num2)
      print ("Your answer is "+result)
elif  op =="-":
      result = str(num1 - num2)
      print ("Your answer is "+result)
elif  op =="*":
      result = str(num1 * num2)
      print ("Your answer is "+result) 
elif  op =="/":
      print (num1 / num2)
elif op =="//":
      result = str(num1 // num2)
      print ("Your answer is "+result) 
elif op =="**":
      result = str(num1 ** num2)
      print ("Your answer is "+result)
elif op =="%":
      result = str(num1 % num2)   
      print ("your answer is "+result) 
else:
      print ("invalid code")

7. By Alpin K Sajan

Made by Alpin K Sajan. You have to enter the first number then the second number after that the operator that you want to use. ( Source )

print("Please input your first number")
num1 = int(input())
print(num1)
print("Please input your second number")
num2 = int(input())
print(num2)
print("Enter the operation u want")
op=input()
print(op)
if(op=='+'):
 print(num1+num2)
elif op=='-':
 print(num1-num2)
elif op=='*':
 print(num1*num2)
elif op=='/':
 if num2==0:
  print("Division by Zero not possible, U idiot (โ”ฌโ”ฌ๏นโ”ฌโ”ฌ))")
  exit()
 print(num1/num2)
elif op=='%':
 print(num1%num2)

8. By Alex

Made by Alex. First you will get the option to choose the operator you want to use, after choosing the operator enter the first number and the second number to get its output. ( Source )

def add(x, y):
    return x + y 
def subtract(x, y):
    return x - y 
def multiply(x, y):
    return x * y 
def divide(x, y):
    return x / y
print(" Choose calculation ") 
print("1 +")
print("2 -") 
print("3 *") 
print("4 /") 
choice = input("please input your choice(1 or 2 or 3 or 4):") 
num1 = int(input("please input a number: ")) 
num2 = int(input("please input a number : "))
if choice == '1': print(num1,"+",num2,"=", add(num1,num2)) 
elif choice == '2': print(num1,"-",num2,"=", subtract(num1,num2)) 
elif choice == '3': print(num1,"*",num2,"=", multiply(num1,num2))
elif choice == '4': print(num1,"/",num2,"=", divide(num1,num2)) 
else: 
    print("error")   

9. By Mikki

Made by Mikki. Change the value of ‘a’ from 17 to your first number, change the value of ‘b’ from ‘3’ to your second number and change the ‘%’ operator with the operator you want to use and run the code. ( Source )

a = 17

b =3

c = a % b

print(c)

10. By Drazex

Made by Drazex. First choose the operator you want to use after that enter the first number and the second number to get the output. ( Source )

def multiply(x,y):
    var = x * y
    return var

def add(x,y):
    var = x + y
    return var
    
def divide (x,y):
    var = x / y
    return var
    
def subtract (x,y):
    var = x - y
    return var


# This section defines a list of functions, 
# and a list of strings to represent those
# functions. They have the same indices to
# match user input to the desired function.
operation = [add,subtract,divide,multiply]
options = ["+", "-", "/", "*"]
choice = input("Choose operation (+, -, *, /): ")


# if loop used only to handle errors.
if choice in options: # if valid input...
    user_choice = options.index (choice)
    num1 = int(input("First number: "))
    num2 = int(input("Second number: "))
    math = operation [user_choice] (num1, num2)
else: # if invalid input...
    math = "Invalid operation!"
    
print(math) # Print result or error message

11. By โ˜†HRITIK GAUTAMโ˜†

An advance Python calculator by โ˜†HRITIK GAUTAMโ˜† that has a GUI. You can use the calculator using your mouse from the GUI. ( Source )

import os
print("""
<!DOCTYPE html>
<html>
    <head>
        
        <title>ever best calculator</title>
        <meta charset="utf-8" />
        <meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0, width=device-width, user-scalable=true" />
        <link rel="stylesheet" href="calc.css" type="text/css">
        <script type="text/javascript" src="calc.js"></script>
    </head>
    <body>
    <svg viewBox="0 0 1320 300">
  <a id="s-text">
    <text x="15%" y="5%" dy="1em">
      MADE BY: HRITIK GAUTAM
    </text>
  </a>
  <use xlink:href="#s-text" class="text"></use>
  <use xlink:href="#s-text" class="text"></use>
  <use xlink:href="#s-text" class="text"></use>
  <use xlink:href="#s-text" class="text"></use>
  <use xlink:href="#s-text" class="text"></use>
 </div>
    <div class="container">

    <div class="div">
        <table><caption><pre>๐•ฎ๐–†๐–‘๐–ˆ๐–š๐–‘๐–†๐–™๐–”๐–—     by โ„โ„๐•€๐•‹๐•€๐•‚ ๐”พ๐”ธ๐•Œ๐•‹๐”ธ๐•„</bsp></caption>
            <tr>
                <td colspan="5"><div id="display-container"><div id="display1"><small><small><span></span></small></small></div><div id="h1"><small><small><span></span></small></small></div></div></td>
            </tr>
            
            <tr>
                <td><button class="top" onclick='getElementById("h1").innerHTML = bsp()'>Del</button></td>   
                <td><button class="top" onclick='getElementById("h1").innerHTML = mp()'>M+</button></td>
                <td><button class="top" onclick='getElementById("h1").innerHTML = mr()'>MR</button></td>
                <td><button class="top" onclick='getElementById("h1").innerHTML = maths("rand")'><small>Rnd</small></button></td>
                <td rowspan="2"><button id="c" class="top" onclick='getElementById("h1").innerHTML = c("")'>C</button></td>
            </tr>
            
            <tr>
                <td><button class="top" onclick='getElementById("h1").innerHTML = maths("res")'><sup>1</sup>/<sub>10</sub></button></td>
                <td><button class="top" onclick='getElementById("h1").innerHTML = maths("logTen")'><small>log10</small></sup></button></td>
                <td><button class="top" onclick='getElementById("h1").innerHTML = maths("ln")'>ln</button></td>
                <td><button class="top" onclick='getElementById("h1").innerHTML = PE("E")'>e</button></td>
             </tr>
             
             <tr>
                <td><button class="top" onclick='getElementById("h1").innerHTML = maths("sine")'>sin</button></td>
                <td><button class="top" onclick='getElementById("h1").innerHTML = maths("cosine")'>cos</button></td>
                <td><button class="top" onclick='getElementById("h1").innerHTML = maths("tangent")'>tan</sup></button></td>
                <td><button class="top" onclick='getElementById("h1").innerHTML = PE("PI")'>ฯ€</button></td>
                <td><button class="top" onclick='getElementById("h1").innerHTML = percent()'>%</button></td>
            </tr>
            
            <tr>
                <td><button class="top" onclick='getElementById("h1").innerHTML = maths("fact")'>n!</button></td>
                <td><button class="top" onclick='getElementById("h1").innerHTML = digit("%")'>Mod</button></td>
                <td><button class="top" onclick='getElementById("h1").innerHTML = power("^")'>x<sup>y</sup></button></td>
                <td><button class="top" onclick='getElementById("h1").innerHTML = power("โˆš")'><sup>y</sup>โˆšx</button></td>
                <td><button class="top" onclick='getElementById("h1").innerHTML = maths("cubert")'><sup>3</sup>โˆš</button></td>
            </tr>
            
            <tr>
                <td><button class="top disabled" onclic='getElementById("h1").innerHTML = digit("(")'>(</button></td>
                <td><button class="top disabled" onclic='getElementById("h1").innerHTML = digit(")")'>)</button></td>
                <td><button class="top" onclick='getElementById("h1").innerHTML = base("bin")'>bin</button></td>
                <td><button class="top" onclick='getElementById("h1").innerHTML = base("oct")'>oct</button></td>
                <td><button class="top" onclick='getElementById("h1").innerHTML = base("hex")'>hex</button></td>
            </tr>
            
            <tr>
                <td><button onclick='getElementById("h1").innerHTML = digit("7")'> 7</button></td>
                <td><button onclick='getElementById("h1").innerHTML = digit("8")'>8</button></td>
                <td><button onclick='getElementById("h1").innerHTML = digit("9")'>9</button></td>
                <td><button onclick='getElementById("h1").innerHTML = operators("+")'>+</button></td>
                <td><button onclick='getElementById("h1").innerHTML = maths("negpos")'>-/+</button> </td>
            </tr>
            
            <tr>
                <td><button onclick='getElementById("h1").innerHTML = digit("4")'>4</button></td>
                <td><button onclick='getElementById("h1").innerHTML = digit("5")'>5</button></td>
                <td><button onclick='getElementById("h1").innerHTML = digit("6")'>6</button></td>
                <td><button onclick='getElementById("h1").innerHTML = operators("-")'>-</button></td>
                <td><button onclick='getElementById("h1").innerHTML = maths("Sqrt")'>โˆš</button></td>
            </tr>
            
            <tr>
                <td><button onclick='getElementById("h1").innerHTML = digit("1")'>1</button></td>
                <td><button onclick='getElementById("h1").innerHTML = digit("2")'>2</button></td>
                <td><button onclick='getElementById("h1").innerHTML = digit("3")'>3</button></td>
                <td><button onclick='getElementById("h1").innerHTML = operators("/")'>/</button></td>
                <td><button onclick='getElementById("h1").innerHTML = maths("cube")'>x<sup>3</sup></button></td>
            </tr>
            
            <tr>
                <td><button onclick='getElementById("h1").innerHTML = dot(".")'>.</button></td>
                <td><button onclick='getElementById("h1").innerHTML = digit("0")'>0</button></td>
                <td><button onclick='getElementById("h1").innerHTML = equal()'>=</button></td>
                <td><button onclick='getElementById("h1").innerHTML = operators("*")'>X</button></td>
                <td><button onclick='getElementById("h1").innerHTML = maths("sqr")'>x<sup>2</sup></button></td>
            </tr>            
        </table>
    </div>
        <style>/* Created by hritik gautam*/

/*Save as calc.css*/
.container {
    width: 300px;
    padding:0px 10px;
    margin: 0px auto;
}
pre{
    margin: 0px;
    font-size: 12px;
}
h2 {
    color: blue;
    width: 300px;
    text-align: center;
}
.red {
    color: #678;
}
table {
    margin: 0px 5px 5px 5px;
}
caption{
    color: #abc;
    text-shadow: 2px 1px #282828;
    font-weight: bold;
}
button {
    width: 50px; 
    height: 50px; 
    font-size: 22px;
    background-color: #515bd4;
    color:#feda77;
    border: 2px #feda77 outset;
    border-radius: 5px;
    outline: none;
    cursor: pointer;
}
.top {
    height: 30px; 
    background-color:#515bd4;
    box-shadow: inset 5px 5px 5px #515bd4, inset -5px -5px 5px #515bd4;
    border-radius: 4px;
    border: 1px #feda77 outset;
    color: #feda77;
    text-shadow: 2px 2px 20px eef;
    font-size: 20px;
}
#c {
    height: 64px;
    color:red;
}
button:active{
    background-color: #515bd4;
    box-shadow: none ;
    padding-top: 4px;
    outline: 1px solid #feda77;
    border: 3px #feda77 inset;
}
.top:hover{
    background-color: orange;
    box-shadow: inset 5px 5px 5px #cab, inset -5px -5px 5px #515bd4;
}
button:hover{
    background-color:orange;
}
.top:active{
    background-color: orange;
    box-shadow: none ;
    padding-top: 4px;
    outline: 1px solid #feda77;
    border: 3px #515bd4 inset;
}
#display-container {
    border: 3px inset;
    margin-bottom: 10px;
}
#s-text > text {
  text-align: center;
  width: 100%;
  height: 100%;
  font: 5em Open Sans, Impact;
  flex: 1 100%;
}

.text {
  fill: none;
  stroke-width: 3;
  stroke-linejoin: round;
  stroke-dasharray: 80 350;
  stroke-dashoffset: 0;
  animation: stroke 10s infinite linear;
  stroke: white;
  flex: 1 100%;
}

.text:nth-child(5n + 1) {
  stroke: #f2385a;
  animation-delay: -1.5s;
}

.text:nth-child(5n + 2) {
  stroke: #f5a583;
  animation-delay: -2.5s;
}

.text:nth-child(5n + 3) {
  stroke: #e9f1df;
  animation-delay: -3.5s;
}

.text:nth-child(5n + 4) {
  stroke: #56d9cd;
  animation-delay: -4.5s;
}

.text:nth-child(5n + 5) {
  stroke: #3aa1bf;
  animation-delay: -6s;
}

@keyframes stroke {
  50% {
    stroke-dashoffset: -400;
  }

  100% {
    stroke-dashoffset: 100;
  }
}
#h1, #display1 { 
    width: 260px; 
    height: 25px; 
    padding: 2px;
    padding-top: 4px; 
    background-color:powderblue; 
    font-size: 20px;
    font-family: serif;
    font-weight: bold;
    text-align: right;
    overflow: hidden;
    color: #515bd4;
    text-shadow: 2px 2px 1px #8ac;
}
#display1 {
    font-size: 16px;
}
p {
    width: 270px;
    margin: 10px;
    margin-top: -10px;
    padding: 0px 5px;
    color: #feda77;
}
p:active{
    color: white;
}
span {
    color: #678;
}
ul {
    background-color: powderblue;
    width: 260px;
}
li {
    display: inline;
    background-color:#feda77;
    padding: 0px 0px;
    font-size: 20px;
}
.div {
    border: 5px #515bd4 ridge  ;
    border-radius: 10px;
    margin: 0px 5px 5px 5px;
    padding-top: 0px;
    width: 285px;
    box-shadow: -10px 10px 10px gray;
    background-color: orange;
    font-size: 11px;
    color: white;
}
.w {
    box-shadow: -10px 10px 10px silver;
    border: 5px orange groove;
    margin: 0px 5px 5px 5px;
    border-radius: 10px;
    padding-top: 0px;
    font-size: 11px;
    cursor: pointer;
    width: 285px;
    color: white;
}

}</style><script>// Created by sujeet gautam

//Save as calc.js
//Feel free to copy modify and do anything you want with this code.Thanks to John Wells and all who gave some helpful suggestions for the improvement of the calculator.

//     THE HRITIK CALCULATOR

//Declaring variables
var decimalPoint = enter = entered = operatorSign = rootNpower_Sign = flo = math = M = firstI = first = second = secondI = answer = theanswer = result = peSign = "";
var opsCheck = dotCounter = 0;
var removeFirstZero = "";
//To prevent printing more than one dot
function dot(b) {
    if (decimalPoint == "") {
        enter = entered = b;
        first+= enter;
        entered+= enter;
        decimalPoint = ".";
        dotCounter = 0;
        return first;
        } else {
        return first;
    }
}
//To control what happen when Pi and Euler is clicked
function PE(b) {
    decimalPoint = ".";
    dotCounter = 15;
    var cons = b;
    if (peSign == "") {
        if (operatorSign != "" && first == "" + operatorSign) {
            first = (cons = "PI") ? Math.PI: Math.E;
        } else if (operatorSign != "" && first > 0 || first < 0) {
            first = (cons == "PI") ? first + "*" + Math.PI: first + "*" + Math.E;
        } else if (first != "" && operatorSign != "") {
            first += (cons = "PI") ? Math.PI: Math.E;
        } else if (operatorSign == "" && first != "") {
            first = (cons == "PI") ? first + "*" + Math.PI: first + "*" + Math.E;
        } else {
            first = (cons == "PI") ? Math.PI: Math.E;
        }
    } else if (first !== "") {
        first = (cons == "PI") ? first + "*" + Math.PI: first + "*" + Math.E;
    } else {
        first = (cons == "PI") ? Math.PI:  Math.E;
    }
    return first;
}
function mp() {
    M = first;
    first = M;
    return first ;
}
function mr() {
    first = M;
    return first ;
}
//Cancel making all variable empty. All variable = ""
function c(c) {
    document.getElementById("display1").innerHTML = decimalPoint = operatorSign = rootNpower_Sign = entered = math = first = firstI = second = secondI = answer = theanswer = flo = M = "";
    return "";
}
//To calculate squares, cubes, factorials e.t.c. For calculations which use only one value. Variable 'firstI' was isolated by maths() function to be solved here
function mathematics() {
    if (math == "sqr") {
        result = firstI * firstI;
    } else if (math == "cube") {
        result = firstI * firstI * firstI;
    } else if (math == "Sqrt") {
        result = Math.sqrt(firstI);
    } else if (math == "cubert") {
        result = Math.cbrt(firstI);
    } else if (math == "negpos") {
        result = firstI * -1;
    } else if (math == "sine") {
        result = Math.sin(firstI);
    } else if (math == "cosine") {
        result = Math.cos(firstI);
    } else if (math == "tangent") {
        result = Math.tan(firstI);
    } else if (math == "ln") {
        result = Math.log(firstI);
    } else if (math == "logTen") {
        result = Math.log10(firstI);
    } else if (math == "rand") {
        result = Math.round(firstI);
    }else if (math == "res") {
        result = 1 / firstI;
    } else if (math == "fact") {
        n = firstI;
        firstI = 1;
        while (n > 1){
            firstI *= n;
            n -= 1;
        }
        result = firstI;
    } decimalPoint = (Math.round(result) == result) ? "": ".";
}
//To make variable 'first' and 'second' keep result of its values. e.g if it was 3 + 2 it must now be 5. This is done to prepare them for use in maths() function
function prep() {
    second = eval(second);
    first = eval(first);
}
//When sqr, cube e.t.c are clicked, this function, math(), does the following: 1. It extract the last number you entered from variable 'first' and keeps it as variable 'firstI'. 2. It calls mathematics function to work on the on variable 'firstI'. The answer is kept in 'result' variable. 3.It displays the answer of other previous numbers entered and the 'result' from mathematics e.g. 5 + 4 which was 3 + 2 + 2^2. Here 3 + 2 has become 5 and because of prep() function. 
function maths(a) {
    math = a;
    try {
        if (operatorSign == "+") {
            prep();
            firstI = first - second;
            mathematics();
            first = second + "+" + result;
        } else if (operatorSign == "-") {
            prep();
            firstI = second - first;
            mathematics();
            first = second + "-" + "(" + result + ")";
        } else if (operatorSign == "*") {
            prep();
            firstI = first / second;
            mathematics();
            first = second + "*" + result;
        } else if (operatorSign == "/") {
            prep();
            firstI = second / first;
            mathematics();
            first = second + "/" + result;
        } else {
            firstI = first;
            mathematics();
            first = result;
        }
        return first;
    } catch (first ) {
        first = second + operatorSign;
        return first;
    }
}
//This is just my notes:--> To remove first zero in second number zero must have its own function so that every entry of zero is checked to make sure that no number greater than zero should start with a zero
function digit(b) {
    opsCheck = 0;
    dotCounter++;
    if (first == Infinity || first == NaN) {
        first = 0;
    }
    peSign = "pes";
    entered = b;
    if (rootNpower_Sign != "") {
        first = (first === "0" && entered !== ".") ? entered: first + entered;
        return secondI + firstI + rootNpower_Sign + first;
    } else {
        first = (first === "0" && entered !== ".") ? entered: first + entered;
        theanswer = eval(first) + "";
        if (theanswer.length > 14) {
            theanswer = Math.abs((theanswer*1).toPrecision(14));
        }
          document.getElementById("display1").innerHTML = first;
        return theanswer;
    }
}
var thebase = "";
function base(a) {
    thebase = a;
    first *= 1;
    if (thebase == "bin") {
        firstII = first.toString(2);
    } else if (thebase == "oct") {
        firstII = first.toString(8);
    } else if (thebase == "hex") {
        firstII = first.toString(16);
    }
    return firstII;
}
//Four functions below are for themes
function themes(thm) {
    theme = thm;
    el = document.getElementsByClassName("div");
    if (theme == 1) {
        el[0].id="theme1";
    } else if (theme == 2) {
        el[0].id="theme2";
    } else if (theme == 3) {
        el[0].id="theme3";
    } else {
        el[0].id="theme4";
    }
}
//back space
function bsp() {
    first += "";
    dotCounter--;
    decimalPoint = dotCounter >= 0 ? ".": "";
    first = first.substr(0, first.length - 1);
    document.getElementById("display1").innerHTML = first;
    try{
        eval(first);
        return first;
    } catch(first) {
        eval(first);
    return "";
    }
}
//Two functions below calculate power and root
function pow() {
     first *= 1;
     result = Math.pow(firstI, first);
}
function roots() {
     first *= 1;
     result = Math.pow(first, 1 / firstI).toPrecision(12);
     result = Math.abs(result);
}
//When operators ,+ - / * are clicked op() function does a number of things. It checks if power or root were clicked. If yes, it calculates the previous numbers and the add the new operator. If not it add the operator clicked
function operators(b) {
    peSign = "";
    if (opsCheck == 0) {
    opsCheck = 1;
    document.getElementById("display1").innerHTML = first;
    try {
        if (rootNpower_Sign == "^") {
            if (operatorSign == "+") {
                pow();
                answer = result + second;
            } else if (operatorSign == "-") {
                pow();
                answer = second - result;
            } else if (operatorSign == "*") {
                pow();
                answer = result * second;
            } else if (operatorSign == "/") {
                pow();
                answer = second / result;
            } else {
                pow();
                answer = result;
            }
        } else if (rootNpower_Sign == "โˆš") {
            if (operatorSign == "+") {
                roots();
                answer = second + result;
            } else if (operatorSign == "-") {
                roots();
                answer = second - result;
            } else if (operatorSign == "*") {
                roots();
                answer = result * second;
            } else if (operatorSign == "/") {
                roots();
                answer = second / result;
            } else {
                roots();
                answer = result;
            }
        } else if (a == "%") {
            answer = second % first;
        } else {
            operatorSign = b;
            first += operatorSign;
            decimalPoint = "";
        }
        rootNpower_Sign = "";
        operatorSign = b;
        firstI = "";
        second = answer;
        first = answer + operatorSign;
        decimalPoint = "";
document.getElementById("display1").innerHTML = first;
    return eval(second);
    } catch(x) {
        if (first != "<span class='red'>Press ON to start</span>") {
            operatorSign = b;
            second = eval(first);
            first += operatorSign;
            decimalPoint = "";
        } else {
            first = "<span class='red'>Press ON to start</span>" ;
        }
        document.getElementById("display1").innerHTML = first;
        return (second == undefined ) ? 0 : eval(second);
        }
    } else {
        operatorSign = b;
        first += "";
        first = first.substr(0, first.length - 1);
        first = first + operatorSign;
        document.getElementById("display1").innerHTML = first;
        return (second == undefined ) ? 0 : eval(second);
    }
}
function percent() {
    first = eval(first) * 100;
    return first + "%";
}
//toggles the negative sign
function negpos() {
    first = (operatorSign == "") ? first *= -1: first;
    return first ;
}
function power(b) {
    rootNpower_Sign = b;
    if (operatorSign == "+" && second != "") {
        prep();
        firstI = first - second;
        first = "";
        secondI = second + "+";
        return second + "+" + firstI + rootNpower_Sign;
    } else if (operatorSign == "-" && second != "") {
        prep();
        firstI = second - first;
        first = "";
        secondI = second + "-";
        return second + "-" + firstI + rootNpower_Sign;
    } else if (operatorSign == "*" && second != "") {
        prep();
        firstI = first / second;
        first = "";
        secondI = second + "*";
        return second + "*" + firstI + rootNpower_Sign;
    } else if (operatorSign == "/" && second != "") {
        prep();
        firstI = second / first;
        first = "";
        secondI = second + "/";
    return second + "/" + firstI + rootNpower_Sign;
    } else {
        rootNpower_Sign = b;
        firstI = first;
        first = "";
        return firstI + rootNpower_Sign;
    }
}
function equal() {
document.getElementById("display1").innerHTML = first;
    try {
        if (rootNpower_Sign == "^") {
            if (operatorSign == "+") {
                pow();
                first = result + second;
            } else if (operatorSign == "-") {
                pow();
                first = second - result;
            } else if (operatorSign == "*") {
                pow();
                answer = result * second;
                first = answer;
            } else if (operatorSign == "/") {
                pow();
                first = second / result;
            } else {
                pow();
                first = result;
            }
        } else if (rootNpower_Sign == "โˆš") {
            if (operatorSign == "+") {
                roots();
                first = result + second;
            } else if (operatorSign == "-") {
                roots();
                first = second - result;
            } else if (operatorSign == "*") {
                roots();
                first = result * second;
            } else if (operatorSign == "/") {
                roots();
                first = second / result;
            } else {
                roots();
                first = result;
            }
        } else if (operatorSign == "%") {
            answer = second % first;
        } else {
            if (first == "") {
                first = first ;
            } else {
                try{
                    first = eval(first) + "";
                    if (first.length > 14)  {
                        first = Math.abs((first*1).toPrecision(14));
                    }
                } catch (first) {
                    first = "<small><small>Enter number or delete operator<!--Incorrect input. Click C to clear--></small></small>";
                    return first;
                    first = "";
                }
            }
        }
        rootNpower_Sign = operatorSign = answer = firstI = second = "";
        flo = first;
        flo = Math.floor(flo);
        decimalPoint = (flo == first) ? "": ".";
        return first;
    } catch(operatorSign) {
        operatorSign = "";
        first = eval(first) + "";
        if (first.length > 14) {
            first = Math.abs((first*1).toPrecision(14));
        }
        flo = first;
        flo = Math.floor(flo);
        decimalPoint = (flo == first) ? "": ".";
        return first;
    }
}</script>
    </body>
</html>
      
 """)

__import__("os").system("touch trick.png")

12. By Louis

Made by Louis. You can enter multiple operators and numbers like ( 9 + 9 – 2 ) with and without space in between the operators and numbers. ( Source )

from math import *
eq = input() or '(log(4)+sqrt(15))/pi'
print(f'{eq} = {eval(eq)}')

13. By Slothy

Made by Slothy. The calculation needs to be entered in one single line without any spaces in between the numbers and operators. Multiple numbers and operators is supported. ( Source )

from operator import pow, truediv, mul, add, sub  

operators = {
  '+': add,
  '-': sub,
  '*': mul,
  '/': truediv
}

def calculate(s):
	if s.isdigit():
		return float(s)
	for c in operators.keys():
		left, operator, right = s.partition(c)
		if operator in operators:
			return operators[operator](calculate(left), calculate(right))

calc = input("Type calculation:\n")
print("Answer: " + str(calculate(calc)))

14. By Qrt4276

Made by Qrt4276. You have to first select what you want to do, like if you want to do addition then enter ‘Add’, other operators are – Subtract, Multiply, Divide. After selecting the operator enter the first and the second number. ( Source )

def add(x,y):
  return x + y
def subtract(x,y):
  return x - y
def multiply(x,y):
  return x * y
def divide(x,y):
  return x / y
print("We all hate math, heres a calculator.")
choice = input("Chosen Operation: ")
print(choice)
num1 = float(input("First Number: "))
print(num1)
num2 = float(input("Second Number: "))
print(num2)

if choice == "add" or choice == "Add":
				   print(f"{num1} + {num2} = {add(num1,num2)}")
if choice == "subtract" or choice == "Subtract":
				   print(f"{num1} - {num2} = {subtract(num1,num2)}")
if choice == "multiply" or choice == "Multiply":
				   print(f"{num1} * {num2} = {multiply(num1,num2)}")
if choice == "divide" or choice == "Divide":
				   print(f"{num1} / {num2} = {divide(num1,num2)}")

print("Have a Nice day! ๐Ÿ˜Š")

15. By Siddharth Malhotra

Made by Siddharth Malhotra. Enter the first number in first line then the operator in second line after that the third number in third line. ( Source )

num1 = int(input(""))
oprator = input("")
num2 = int(input(""))

if oprator == "+":
    print(num1 + num2)
elif oprator == "-":
    print(num1-num2)
elif oprator == "*":
    print(num1*num2)
elif oprator == "/":
    print(num1/num2)
elif oprator == "**":
    print(num1**num2)
else:
    print("Error")

16. By Giorgi R

Made by Giorgi R. You have to enter two numbers with space in between and the program will print out all the results of those numbers when used with different operators. ( Source )

num1, num2 = input('enter 2 numbers: ').split()
num1 = int(num1)
num2 = int(num2)
sum = num1 + num2
difference = num1 - num2
product = num1 * num2
quetient = num1 // num2
remainder = num1 % num2
print("{} + {} = {}".format(num1, num2, sum))
print("{} - {} = {}".format(num1, num2, difference))
print("{} * {} = {}".format(num1, num2, product))
print("{} / {} = {}".format(num1, num2, quetient))
print("{} % {} = {}".format(num1, num2, remainder))

17. By Vasiliev Egor

Made by Vasiliev Egor. The calculation needs to be entered in three separate lines without space. So enter first number in first line then operator in second and the third number in third. ( Source )

num = int (input (""))
znak = input ("")
num2 = int (input (""))
res = 0

if znak == ('+'):
	res = num + num2
	print (res)
elif znak == ('-'):
	res = num - num2
	print (res)
elif znak == ('*'):
	res = num * num2
	print (res)
elif znak == ('/'):
	res = num / num2
	print (res)
else:
	print ("Invalid input")

18. By Amit Pathak

Made by Amit Pathak. Just like the above python code, this one also needs the input in three different lines. ( Source )

a = int(input())
what = input()
b = int(input())


if what == '+' :
   c = a + b
   print('equalis:' + str(c))
elif what == '-' :
   c = a - b
   print('equalis:' + str(c))
elif what == '/':
   c = a / b
   print('equalis:' + str(c))
elif what == '*' :
   c = a * b
   print('equalis:' + str(c))
elif what == '%' :
   c = a % b
   print('equalis:' + str(c))
elif what == '%%' and a%b == 0 :
   c = a%b == 0
   print('equalis:' + str(c))
else:
   print('false')

19. By Daryl Adopo

Simple calculator by Daryl Adopo. The number you want to calculate needs to be entered directly into the python code, at the bottom of the code change the numbers of this line – calculator(563,23,”/”). Change 563 to your first number, 23 to your second number and / to your operator. ( Source )

def calculator(num_1, num_2, op):
  result = 0
  if op == "+":
    result = num_1 + num_2
  elif op == "-":
    result = num_1 - num_2
  elif op == "*":
    result = num_1 * num_2
  elif op == "/":
    result = num_1 / num_2
  print (f"{num_1} {op} {num_2} = {result}")

calculator(563,23,"/")

20. By Abdelkader Barraj

Made by Abdelkader Barraj. First select the operator you want to use after that enter the first number and the second number. The program will give you the output and start again. ( Source )

while True:
   print("Options:")
   print("Enter '+' to add two numbers")
   print("Enter '-' to subtract two numbers")
   print("Enter '*' to multiply two numbers")
   print("Enter '/' to divide two numbers")
   print("Enter 'Q' to end the program")
   user_input = input(" Your choice here : ")

   if user_input.upper() == "Q":
      break
   else:
      n1=float(input('enter the first number :'))
      n2=float(input('enter the second number : '))
   if user_input == "+":
      res=n1+n2
   elif user_input == "-":
      res=n1-n2
   elif user_input == "*":
      res=n1*n2
   elif user_input == "/":
      try:
          res=n1/n2
      except ZeroDivisionError:
          print("Zero Devision Error !!! ")
          continue
   else:
      print("Unknown input")
      continue
   print(n1,user_input,n2,"=",res)

21. By Aditya

Python calculator by Aditya. Enter the calculation in separate lines, first enter 1st number then in second line enter 2nd number after that enter the operator in the third line.( Source )

from ast import operator


num_1  = float(input(""))
num_2 = float(input(""))
oper = input("")
if oper == '+':
    print("The answer is: ",num_1 + num_2)
elif oper == '-' :
    print("The answer is: ",num_1 - num_2)
elif oper == '/':
    print("The answer is: ",num_1 / num_2)
elif oper == '*' :
    print("The answer is: ",num_1 * num_2)
else:
    print("Please Enter Valid Operator")

22. By Deepak

Made by Deepak. You have to first input the operation name add, subtract, multiply, divide, square root, square or cube in first line, after that in second line enter the first number and in third line enter the second number. ( Source )

print("*"*6 + "simple calculater" + "*"*6)
print("Made by Deepak!!!")
print("_"*102)
print("")
print("")
while True:
   op1= input("")
   num1 = float(input(""))
   if op1 == "add":
       num2=float(input(""))
       result=num1+num2
       print("your answer is",result)
       break
   elif op1 =="subtract":
       num2=float(input(""))
       result= num1 - num2
       print("your answer is", result)
       break
   elif op1 =="multiply":
       num2=float(input(""))
       result = num1*num2
       print("your answer is",result)
       break
   elif op1 == "divide":
       num2=float(input(""))
       result = num1/num2
       print("your answer is",result)
       break
   elif op1=="square root":
       result=num1**0.5
       print ("your answer is",result)
       break
   elif op1== "square":
       result= num1**2
       print("your answer is",result)
       break
   elif op1=="cube":
       result =num1**3
       print("your answer is",result)
       break
   else:
       print("unexpected input!!!!!  :(")
       break
print("")
print("")
print("_"*102)
print("")
print("")
print("Thankyou for your co-operation:)")

23. By Gun

Made by gun. Enter first number then second number after that select the operator you want to use. ( Source )

n1 = float(input("Your First Number: \n"))
n2 = float(input("Your Second Number: \n"))
rl = input("Choose operator: \n")


if rl == '+':
    print(n1+n2)
elif rl == '-':
    print(n1-n2)
elif rl == '*':
    print(n1*n2)
elif rl == '/':
    print(n1/n2)


else:
    print("Invalid Entry")
    print(" Use->  +, - , * , / ")

24. By Valentin Danilov

Made by Valentin Danilov. You have to first select the operator you want to use after that enter the first and the second number. The program will give you the results and start again. ( Source )

while True:
    print("โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”")
    print("options:")
    print("enter '+' to add")
    print("enter '-' to subtract")
    print("enter '*' to multiply")
    print("enter '/' to divide")
    print("enter 'quit' to close the program")
    print("โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”")
    user_input = input("โ€ข")

    if user_input == 'quit':
        break
    elif user_input == '+':
        ...
    elif user_input == '-':
        ...
    elif user_input == '*':
        ...
    elif user_input == '/':
        ...
    else:
        print("user input error")

    if user_input == '+':
        num1 = float(input("โ€ขโ€ขfirst number: "))
        print(num1)
        num2 = float(input("โ€ขโ€ขโ€ขsecond number: "))
        print(num2)
        result = str(num1 + num2)
        print("โ€ขโ€ขโ€ขanswer: " + result)

    elif user_input == '-':
        num1 = float(input("โ€ขโ€ขfirst number: "))
        print(num1)
        num2 = float(input("โ€ขโ€ขโ€ขsecond number: "))
        print(num2)
        result = str(num1 - num2)
        print("โ€ขโ€ขโ€ขanswer: " + result)

    elif user_input == '*':
        num1 = float(input("โ€ขโ€ขfirst number: "))
        print(num1)
        num2 = float(input("โ€ขโ€ขโ€ขsecond number: "))
        print(num2)
        result = str(num1 * num2)
        print("โ€ขโ€ขโ€ขanswer: " + result)

    elif user_input == '/':
        num1 = float(input("โ€ขโ€ขfirst number: "))
        print(num1)
        num2 = float(input("โ€ขโ€ขโ€ขsecond number: "))
        print(num2)
        result = str(num1 / num2)
        print("โ€ขโ€ขโ€ขanswer: " + result)

25. By Tim Thuma

Made by Tim Thuma. The code is only 7 lines long and you can enter the calculation in one single line, with or without spaces. ( Source )

i=input("Enter a calculation: ")
print(i)

#Printing result
print("\nYour calculation: "+i)
try:
  print("Result: "+str(eval(i)))
except:
  print("\nAn error occured. Please follow instructions.")

26. By Krishna Sambhajirao Kale

Made by Krishna. First select what operator you want to use using number 1, 2, 3, 4 after that enter the first and the second number to get the output. ( Source )

print("*******calculator*******")
print("1.addition")
print("2.substraction")
print("3.multiplication")
print("4.division")
ch = int(input("enter your choice(1-4)"))
if ch == 1:
  a=int(input("enter the 1st no."))
  b=int(input("enter the 2nd no."))
  c=a+b
  print("the addition is",c)
elif ch == 2:
  a=int(input("enter the 1st no."))
  b=int(input("enter the 2nd no."))
  d=a-b
  print("the subtraction is",d)
elif ch == 3:
  a=int(input("enter the 1st no."))
  b=int(input("enter the 2nd no."))
  e=a*b
  print("the multiplication is",e)
elif ch == 4:
  a=int(input("enter the 1st no."))
  b=int(input("enter the 2nd no."))
  f=a/b
  print("the division is",f)
else:
  print("the choise is invalid")

27. By ANJALI SAHU

Made by Anjali Sahu. Enter first number after that second number after that the operator. ( Source )

def calc(a,b):
     add,sub,mul,div=a+b,a-b,a*b,a/b
     if x== "+":
         print(a,"+",b,"=",add)
     elif x=="-":
         print(a,"-",b,"=",sub)
     elif x=="*":
         print (a,"*",b,"=",mul)
     elif x=="/":
         print(a,"/",b,"=",div)
     else:
         return ("INVALID OPERARTION")
#--------------------------------
print ("********MY CALCULATOR*********")
a=int(input("Enter 1st number:"))
print (a)
b=int(input ("Enter 2nd number:"))
print (b)
x=(input("Enter the operator(+,*,+,/):"))
print (x)
calc(a,b)

28. By Rohit Panchal

A little bit advance python calculator by Rohit Panchal. First enter the operation you want to do, after that enter the first and the second number for result. You can also exit the calculator by entering ‘exit’. ( Source )

print("Operations:")
print("Enter 'add' for addition")
print("Enter 'sub' for subtraction")
print("Enter 'mul' for multiplication")
print("Enter 'div' for division")
print("Enter 'rem' for remainder")
print("Enter 'que' for quotient")
print("Enter 'exp' for exponentiation")
print("Enter 'exit' when you want to stop the calculator")
    
while True:
    
    user_input = input("Enter the operation you want to carry out: ")
    
    if user_input == "add":
        print("Enter 2 numbers for addition")
        num1 = float(input("Enter 1st number"))
        num2 = float(input("Enter 2nd number"))
        result = num1 + num2
        print(" Your result is " + str(result))
        
    elif user_input == "sub":
        print("Enter 2 numbers for subtraction")
        num1 = float(input("Enter 1st number"))
        num2 = float(input("Enter 2nd number"))
        result = num1 - num2   
        print(" Your result is " + str(result))
        
    elif user_input == "mul":
        print("Enter 2 numbers for multiplication")
        num1 = float(input("Enter 1st number"))
        num2 = float(input("Enter 2nd number"))
        result = num1 * num2
        print(" Your result is " + str(result))
        
    elif user_input == "div":
        print("Enter 2 numbers for division")
        num1 = float(input("Enter 1st number"))
        num2 = float(input("Enter 2nd number"))
        result = num1 / num2
        print(" Your result is " + str(result))
        
        
    elif user_input == "rem":
        print("Enter 2 numbers to calculate remainder such that num1 divided by num2 gives the remainder")
        num1 = float(input("Enter 1st number"))
        num2 = float(input("Enter 2nd number"))
        result = num1 % num2
        print(" Your result is " + str(result))
        
        
    elif user_input == "que":
        print("Enter 2 numbers to calculate quotient such that num1 divided by num2 gives the quotient")
        num1 = float(input("Enter 1st number"))
        num2 = float(input("Enter 2nd number"))
        result = num1 // num2
        print(" Your result is " + str(result))
        
        

        
    elif user_input == "exp":
        print("Enter 2 numbers such that the second number is the power of first number to which it is raised to")
        num1 = float(input("Enter 1st number"))
        num2 = float(input("Enter 2nd number"))
        result = num1 ** num2
        print(" Your result is " + str(result))
        
        
    elif user_input == "exit":
        print("Thanks for using")
        break        

 
   
    else:
        print("Please choose a valid operation")

29. By Jasmine Shaik

Made by Jasmine Shaik. First you have to select the operator that you want after that the first and second number. ( Source )

# This function adds two numbers 
def add(x, y):
   return x + y

# This function subtracts two numbers 
def subtract(x, y):
   return x - y

# This function multiplies two numbers
def multiply(x, y):
   return x * y

# This function divides two numbers
def divide(x, y):
   return x / y

print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")

# Take input from the user 
choice = input("Enter choice(1/2/3/4):")

num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))

if choice == '1':
   print(num1,"+",num2,"=", add(num1,num2))

elif choice == '2':
   print(num1,"-",num2,"=", subtract(num1,num2))

elif choice == '3':
   print(num1,"*",num2,"=", multiply(num1,num2))

elif choice == '4':
   print(num1,"/",num2,"=", divide(num1,num2))
else:
   print("Invalid input")

30. By SOUMYA

Made by SOUMYA. First choose the operator you want to use after that enter first and the second number to get the results. ( Source )

print('---Wanted the answers faster just try this minni calculator---')
print('What you wanted to do ??')
print('1.addition')
print('2.subtraction')
print('3.multiplication')
print('4.division')

n=input('\nEnter your Choice-')
print(n,"\n")
x=float(input('Enter first no.= '))
print(x,"\n")
y=float(input('Enter another no.='))
print(y,"\n")

if (n=='addition'):
    print('x+y=',x+y)
elif (n=='subtraction'):
    print('x-y=',x-y)
elif (n=='multiplication'):
    print('x*y=',x*y)
elif(n=='division'):
    print('x/y=',x/y)
else:
    print('you entered invalid operator')
print('THANK YOU!!!')

31. By Hrithika Reddy

Made by Hrithika Reddy. ( Source )

Enter first number: 3
Enter second number: 3
choose Operation: +
Select operations: 3.0 + 3.0 = 6.0
# take inputs
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))

# choise operation
print("choose Operation: +, -, *, /")
select = input("Select operations: ")

# check operations and display result
# add(+) two numbers
if select == "+":
    print(num1, "+", num2, "=", num1+num2)

# subtract(-) two numbers
elif select == "-":
    print(num1, "-", num2, "=", num1-num2)

# multiplies(*) two numbers
elif select == "*":
    print(num1, "*", num2, "=", num1*num2)

# divides(/) two numbers
elif select == "/":
    print(num1, "/", num2, "=", num1/num2)

else:
    print("Invalid input")
    #the result and operation process comes in floats DO NOT MIND THAT 

32. By Mohammad Amin Safdel

Made by Mohammad Amin Safdel. ( Source )

add
Enter a number 30
Enter another number 30
The answer is:60.0
while True:
         print("Options:")
         print("Enter 'add' to add two numbers")
         print("Enter 'subtract' to subtract two numbers")
         print("Enter 'mutiply' to mutiply two numbers")
         print("Enter 'divide' to divide two numbers")
         print("Enter 'quatient' to floor divide two numbers")
         print("Enter 'modulus' to remaind of a division")
         print("Enter 'power' one number power of another")
         print("Enter 'quit' to end the program")
         user_input=input(":")
         if user_input=="add":
            num1=float(input("Enter a number"))
            num2=float(input(" Enter another number"))
            result=str(num1+num2)
            print(" The answer is:"+result)
         elif user_input=="subtract":
              num1=float(input("Enter a number"))
              num2=float(input(" Enter another number"))
              result=str(num1-num2)
              print(" The answer is:"+result)
         elif user_input=="multiply":
              num1=float(input("Enter a number"))
              num2=float(input(" Enter another number"))
              result=str(num1*num2)
              print(" The answer is:"+result)
         elif user_input=="divide":
              num1=float(input("Enter a number"))
              num2=float(input(" Enter another number"))
              result=str(num1/num2)
              print(" The answer is:"+result)
         elif user_input=="qoutient":
              num1=float(input("Enter a number"))
              num2=float(input(" Enter another number"))
              result=str(num1//num2)
              print(" The answer is:"+result)
         elif user_input=="modulus":
              num1=float(input("Enter a number"))
              num2=float(input(" Enter another number"))
              result=str(num1%num2)
              print(" The answer is:"+result)
         elif user_input=="power":
              num1=float(input("Enter a number"))
              num2=float(input(" Enter another number"))
              result=str(num1**num2)
              print(" The answer is:"+result)
         if user_input=="quit":
            break                

33. By MD. Ferdous Ibne Abu Bakar

Made by MD. Ferdous Ibne Abu Bakar. ( Source )

12+12
12.0 + 12.0 = 24.0
try:
#Taking inputs...
 num1 = float(input())
 symbol = str(input())
 num2 = float(input())

#Calculating your inputs...
 calc_plus = num1 + num2
 calc_minus = num1 - num2
 calc_multiplication = num1 * num2
 calc_division = num1 / num2


#Analysing & printing output...
 if symbol == '+':
  print(str(num1)+' + '+str(num2)+' = '+str(calc_plus))

 elif symbol == '-':
  print(str(num1)+' โ€” '+str(num2)+' = '+str(calc_minus))

 elif symbol == '*' or symbol == 'ร—':
  print(str(num1)+' ร— '+str(num2)+' = '+str(calc_multiplication))

 elif symbol == '/' or symbol == 'รท':


  print(str(num1)+' รท '+str(num2)+' = '+str(calc_division))

#For invalid input...
 else:
  print ('''SORRY! This calculator is unable to solve your problem ๐Ÿ˜”. May be your input/s is/are invalid. Try again...
  
Please input like this: 
           21   [input a number] 
        <press enter>
           +    [input a mathematical symbol]
        <press enter>
           23.5 [input another number]
            RUNโ–ถ

*Learn more: Line-8

(If you find any bug, let me know in the comments)
''')

except ZeroDivisionError:
  print(str(num1)+' รท '+str(num2)+' = '+'Undefined')
  
except ValueError:
  print ('''SORRY! This calculator is unable solve your problem ๐Ÿ˜”. May be your input/s is/are invalid. Try again...
  
  
Please input like this: 
           21   [input a number] 
        <press enter>
           +    [input a mathematical symbol]
        <press enter>
           23.5 [input another number]
            RUNโ–ถ

*Learn more: Line-8

(If you find any bug, let me know in the comments)
  ''')

34. By Stash

Made by Stash. ( Source )

******** CALCULATOR *********
Enter Operation

>>> 1+2 = 3
import os
print("******** CALCULATOR *********")

print("Enter Opeartion")
#print(Enter somthing like 2-3 and press enter)
operation = str(input(""))
resultat = eval(operation)
os.system("pause")
print ("\n>>> {} = {}".format(operation ,resultat))

35. By Mirielle

Made by Mirielle. Python Scientific calculator. ( Source )

       CALCULATIONS   
<<<<------------------->>>
>>> EXPRESSION : 12+12
>>> RESULT     : 24

>>> Author      : Cbr
# type help for more....
#       INPUT FORMAT:
# <<<<----------------->>>>> 
# The program is capable of solving input of this format:
# 1. x * x + x % x - x
# 2. sqrt(x) + cos(x) / tan(x) + 2 * pi
#  and so on... All in a single line.
# you can also use methods like:
# e.g factorial(5)*x, sin(20), pow(2, 2)*6 e.t.c
from sys import exit
from math import *
import base64
    
def calc(exp):
    global operators, errors
    if exp == 'help':
        print(base64.b64decode(ppp).decode('utf-8'))
        help(__import__('math'))
        return exit()
    if exp.isalpha() == True:
        print(errors[1])
        return exit()
    if not any([x in exp for i,x in enumerate(operators)]):
        print(errors[1])
        return exit()
    if not any([x in exp for i,x in enumerate(list(map(str, range(0,11))))]):
        print(errors[0])
        return exit()
    else:
        try:
            return (
                '       CALCULATIONS   \n'
                '<<<<------------------->>>\n'
                f'>>> EXPRESSION : {exp}\n'
                f'>>> RESULT     : {eval(exp)}\n\n'
                '>>> Author      : Cbr'
                )
        except (SyntaxError, NameError):
            print(errors[0])
            return exit()

operators = ['+','/','//','*','%','-']
errors = [
    '>>>    Syntax Error',
    '>>>    Bad input using default!',
    '>>>    Math Error'
    ]
ppp = '''QXV0aG9yIDogQ2JyCkRhdGUgICA6IFNlcHRlbWJlciwgMjAxOQpUaXRsZSAgOiBTY2llbnRpZmljIGNhbGN1bGF0b3IKCiAgICAgSU5QVVQgRk9STUFUOgo8PDw8LS0tLS0tLS0tLS0tLS0tLS0+Pj4+PiAKVGhlIHByb2dyYW0gaXMgY2FwYWJsZSBvZiBzb2x2aW5nIGlucHV0IG9mIHRoaXMgZm9ybWF0OgoxLiB4ICogeCArIHggJSB4IC0geAoyLiBzcXJ0KHgpICsgY29zKHgpIC8gdGFuKHgpICsgMiAqIHBpCiBhbmQgc28gb24uLi4gQWxsIGluIGEgc2luZ2xlIGxpbmUuCgoKV0hFUkUgICA+Pj4+Pj46CgpzcXJ0ICA9IHNxdWFyZSByb290ID4+PiBzcXJ0KHgpCnRhbiAgID0gdGFuICAgICA+Pj4gdGFuKHgpCnBpICAgID0gMy4xNCAgICA+Pj4gcGkgKiB4CmUgICAgID0gMi4xNyAgICA+Pj4gZSAqIHgKc2luICAgPSBzaW4gICAgID4+PiBzaW4oeCkKKiogICAgPSBwb3cgICAgID4+PiB4Kip5CmUudC5jCgogICAgIFJFQUQgTU9SRQo8PDwtLS0tLS0tLS0tLS0tLT4+Pj4K'''
inp = input('Input a Mathematical expression :\ne.g 2*sin(20)+factorial(5)/45\nor simply...\n3*3+3+6+2+5%6\nAll in a single line\n\nyou can also type help for more\n\n')
print(calc(inp))

    

36. By Aman[Imaziue Coders]

Made by Aman [Imaziue Coders]. Addition calculator. ( Source )

ENTER YOUR NUMBER: 6
ENTER ANOTHER NUMBER:6
12.0
num1=input("ENTER YOUR NUMBER:")
num2=input("ENTER ANOTHER NUMBER:")
result=float(num1)+float(num2)

print(result)

37. By Shams Karimi

Made by Shams Karimi. ( Source )

First number  : 10.0
Math operator : +
Second number : 10.0
*------*
|RESULT|
*------*
10.0 + 10.0 = 20.0
operators  = ["+" , "-" , "*" , "/"]

#1st input line.   write any number
num_1 = (float(input("First number  : ")))
print (num_1)


#2nd input line.   write a math operator (+,-,*,/)
op_input = input("Math operator : ")
print (op_input)

#3rd input line.   write any number
num_2 = (float(input("Second number : ")))
print (num_2)

#decoration
print ("*------*\n|RESULT|\n*------*")

#calculations
if operators[0] in op_input:
 result = num_1 + num_2
 print (str(num_1) + " + " + str(num_2) +  " = " + str(result))
 
elif operators[1] in op_input:
 result = num_1 - num_2
 print (str(num_1) + " - " + str(num_2) + " = " + str(result))
 
elif operators[2] in op_input: 
 result = num_1 * num_2
 print (str(num_1) + " * " + str(num_2) + " = " + str(result))
 
elif operators[3] in op_input:
 try:
   result = num_1 / num_2
 except ZeroDivisionError:
   result = "Error"
 print (str(num_1) + " / " + str(num_2) + " = " + str(result))

print("\nCOME ON, GIVE IT A LIKE :)")

38. By Daveenis

Made by Daveenis. ( Source )

Chose operation: 1
Write a number: 30
Write another number: 30
60.0
import math

def main(): 

    operation = input('Chose operation: 1 for addition, 2 for subtraction, 3 for division, 4 for multiplication, 5 for square root, exit to stop program: ')
    
    if (operation == '1'):
        num1 = input('Write a number: ')
        num2 = input('Write another number: ')
        a = float(num1) + float(num2)
        print(a)
        main() 
    
    elif (operation == '2'):
        num1 = input('Write a number: ')
        num2 = input('Write another number: ')
        a = float(num1) - float(num2)
        print(a)
        main() 
    
    elif (operation == '3'):
        num1 = input('Write a number: ')
        num2 = input('Write another number: ')
        a = float(num1) / float(num2)
        print(a)
        main() 
    
    elif (operation == '4'):
        num1 = input('Write a number: ')
        num2 = input('Write another number: ')
        a = float(num1) * float(num2)
        print(a)
        main() 
    
    elif (operation == '5'):
        num = input('Write a number: ')
        a = math.sqrt(float(num))
        print(a)
        main()

    elif (operation == 'exit'):
        print('Exiting')
        exit()

    else:
        print('Such operation does not exist.')
        main()

if __name__ == '__main__':
    main()

39. By Faisal

Made by Faisal. ( Source )

>>> 5
>>> +
>>> 2
7
class BrainFrok:
    def __init__(self, x):
        self.code = x

    def Evaluate(code):
        array = [0]
        x = 0
        index = 0
        loop = []
        while x < len(code):
            if code[x] == ">":
                index += 1
                if index == len(array):
                    array.append(0)

            if code[x] == "<":
                index -= 1
                if index < 0:
                    array.insert(0, 0)
                    index += 1

            if code[x] == "+":
                array[index] += 1
                if array[index] == 256:
                    array[index] = 0

            if code[x] == "-":
                array[index] -= 1
                if array[index] == -1:
                    array[index] = 255

            if code[x] == ".":
                print(chr(array[index]),end="")

            if code[x] == ",":
                array[index] = ord(input(">>> "))
                print(chr(array[index]))

            if code[x] == "[":
                loop.append(x)

            if code[x] == "]":
                if array[index] != 0:
                    x = loop[-1]
                else:
                    del loop[-1]
            x += 1

BrainFrok.Evaluate("""
>,>,>,>
+++++[<<<<+++++++++>>>>-]<<<<
[>>-<<-]
>>>>
>>>>++++++[<<<<++++++++>>>>-]
<<<<[-<->]
<[>+>>-<<<-]
>[<+>-]
<<<[<+>>>>+<<<-]
<[>+<-]
[>]
>[<<->>-]
<<.
""")

40. By Muhammad

Made by Muhammad. ( Source )

plz enter the first number : 1
plz enter the second number : 1
plz enter your sign : the sum is 2.0
num1=float(input("plz enter the first number : "))
num2=float(input("plz enter the second number : "))
sign=input("plz enter your sign : ")

if sign =="+":
    sum=num1+num2
    print("the sum is {}".format(sum))
elif sign=="-":
    sub=num1-num2
    print("the sub is {}".format(sub))
elif sign=="*":
    mul=num1*num2
    print("the multiplication is{}".format(mul))
elif sign=="/":
    if num2 ==0:
        print("can't divided by zero'")
    else:
        div=num1/num2
        print("num1/num2={}".format(div))

41. By DrChicken24

Made by DrChicken24. ( Source )

The operation you chose was: 1

Your first number is: 5

Your second number is: 5

Square Root Number: 
ERROR: You didn't type a SqrtNumber.
(If you aren't using said operation, put in zero)
5 + 5 = 10.0

import math

sqrt = math.sqrt

#Define the functions for each feature

def add(x, y):
    return x + y

def subtract(x, y):
    return x - y

def multiply(x, y):
    return x * y

def divide(x, y):
    return x / y

def power(x, y):
    return x ** y
    
def root(x):
    return sqrt(x)
    
#Print the options to the screen

print("Enter any of the following numbers in the first line,\nthen press enter and type the first number,\nand repeat for the second/third.\nIf you aren't using Square Root, type 0 for the\nlast number. If you are using square root,\ntype 0 for the second and third numbers.\n")
print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")
print("5. Exponents")
print("6. Square Root")

print("\n")
print("----------------------------------------------------\n") #Seperator

#Define variable for the user's operation choice and output their choice to the screen. If the operation is greater than 4, it will output a developer made error message telling them their mistake

try:
    user_choice = input("The operation you chose was: ")
    if user_choice > str(6):
        print("ERROR: The highest\noperation is 6 (square root)\n")
    
    else:
        print(str(user_choice) + "\n")

except:
    print("\nERROR: You didn't type an operation.")

#Define variables for the user's number choices, and print the numbers they chose. If they didn't type anything, instead of an EOFError, it will tell them they didn't type the number

try:
    num1 = input("Your first number is: ")
    print(str(num1) + "\n")
    
except EOFError:
    print("\nERROR: You didn't type the first number.\n")

try:
    num2 = input("Your second number is: ")
    print(str(num2) + "\n")
    
except EOFError:
    print("\nERROR: You didn't type the second number.\n")
    
try:
    sqrtNum = input("Square Root Number: ")
    print(str(sqrtNum) + "\n")

except EOFError:
    print("\nERROR: You didn't type a SqrtNumber.\n(If you aren't using said operation, put in zero)")

#Actual operations (what will happen when the user puts in all of the information). If any NameErrors occur, it will tell the user what happened

try:
    if user_choice == '1':
        print(num1, "+", num2, "=", add(float(num1), float(num2)))

except NameError:
    print("\nERROR: You either didn't enter\na first or second number-or both-so the\noperation cannot be completed.")

try:
    if user_choice == '2':
        print(num1, "-", num2, "=", subtract(float(num1), float(num2)))

except NameError:
    print("\nERROR: You either didn't enter\na first or second number - or both - so the\noperation cannot be completed.")

try:
    if user_choice == '3':
        print(num1, "*", num2, "=", multiply(float(num1), float(num2)))

except NameError:
    print("\nERROR: You either didn't enter\na first or second number-or both-so the\noperation cannot be completed.")

try:
    if user_choice == '4':
        print(num1, "/", num2, "=", divide(float(num1), float(num2)))

except NameError:
    print("\nERROR: You either didn't enter\na first or second number-or both-so the\noperation cannot be completed.")

try:
    if user_choice == '5':
        print(num1, "**", num2, "=", power(float(num1), float(num2)))

except NameError:
    print("\nERROR: You either didn't enter\na first or second number-or both-so the\noperation cannot be completed.")
    
try:
    if user_choice == '6':
        print("The square root of ", sqrtNum, "=", root(float(sqrtNum)))

except NameError:
    print("\nERROR: You either didn't enter\na first or second number-or both-so the\noperation cannot be completed.")