Saturday, November 28, 2026 04:23 AM
Change Language
Follow Us
Work From Home Jobs

python calculator

rojgareasy
By rojgareasy On October 13, 2026
5 min read • 61 views

import tkinter as tk
from tkinter import messagebox
import ast
import operator
import re

# ---------- Colors ----------
BG = "#151923"
DISPLAY_BG = "#222938"
NUMBER_BG = "#30394B"
OPERATOR_BG = "#3867E8"
SPECIAL_BG = "#D94B59"
EQUAL_BG = "#20A477"
TEXT_COLOR = "#FFFFFF"

# ---------- Calculator Logic ----------
def safe_calculate(expression):
    """Evaluate arithmetic expressions safely."""
    allowed_operators = {
        ast.Add: operator.add,
        ast.Sub: operator.sub,
        ast.Mult: operator.mul,
        ast.Div: operator.truediv,
        ast.Mod: operator.mod,
        ast.USub: operator.neg,
        ast.UAdd: operator.pos,
    }

    def evaluate(node):
        if isinstance(node, ast.Expression):
            return evaluate(node.body)

        if isinstance(node, ast.Constant):
            if type(node.value) in (int, float):
                return node.value
            raise ValueError("Invalid number")

        if isinstance(node, ast.BinOp):
            op_type = type(node.op)
            if op_type not in allowed_operators:
                raise ValueError("Invalid operator")

            left = evaluate(node.left)
            right = evaluate(node.right)

            if op_type is ast.Div and right == 0:
                raise ZeroDivisionError

            return allowed_operators[op_type](left, right)

        if isinstance(node, ast.UnaryOp):
            op_type = type(node.op)
            if op_type not in allowed_operators:
                raise ValueError("Invalid operator")
            return allowed_operators[op_type](evaluate(node.operand))

        raise ValueError("Invalid expression")

    tree = ast.parse(expression, mode="eval")
    result = evaluate(tree)

    if isinstance(result, complex) or not isinstance(result, (int, float)):
        raise ValueError("Invalid result")

    if not (-float("inf") < result < float("inf")):
        raise ValueError("Result out of range")

    return result


def format_number(number):
    """Remove unnecessary decimal zeros."""
    if isinstance(number, float) and number.is_integer():
        return str(int(number))
    return str(number)


def press(value):
    current = display_var.get()

    if current in ("Error", "Cannot divide by zero"):
        current = ""

    if value == "C":
        display_var.set("0")
        return

    if value == "⌫":
        display_var.set(current[:-1] or "0")
        return

    if value == "±":
        try:
            if not current or current == "0":
                return

            # Toggle the sign of the current final number.
            match = re.search(r"(\d+\.?\d*|\.\d+)$", current)
            if not match:
                return

            start, end = match.span()
            number = match.group()

            if start > 0 and current[start - 1] == "-":
                # Remove minus only if it is a unary minus.
                if start == 1 or current[start - 2] in "+-*/%(":
                    current = current[:start - 1] + current[start:]
                else:
                    current = current[:start] + number
            else:
                current = current[:start] + "-" + number + current[end:]

            display_var.set(current)
        except Exception:
            pass
        return

    if value == "%":
        match = re.search(r"(\d+\.?\d*|\.\d+)$", current)
        if match:
            number = float(match.group())
            start, end = match.span()
            current = current[:start] + format_number(number / 100) + current[end:]
            display_var.set(current)
        return

    if value == "=":
        try:
            expression = current.replace("×", "*").replace("÷", "/")
            if not expression or not re.fullmatch(r"[0-9+\-*/%. ()]+", expression):
                raise ValueError("Invalid expression")

            result = safe_calculate(expression)
            display_var.set(format_number(result))
        except ZeroDivisionError:
            display_var.set("Cannot divide by zero")
        except Exception:
            display_var.set("Error")
        return

    # Start a fresh expression after a result or error.
    if current in ("Error", "Cannot divide by zero"):
        current = ""

    if value in ("+", "-", "×", "÷", "%"):
        if not current:
            if value != "-":
                return
        elif current[-1] in "+-×÷":
            current = current[:-1]

    if value == ".":
        # Only one decimal point per current number.
        last_number = re.split(r"[+\-×÷%]", current)[-1]
        if "." in last_number:
            return
        if not last_number:
            value = "0."

    if current == "0" and value not in (".", "+", "-", "×", "÷", "%"):
        current = ""

    display_var.set(current + value)


def keyboard_input(event):
    """Handle keyboard keys."""
    key = event.char

    if key.isdigit() or key == ".":
        press(key)
    elif key in "+-*/%":
        mapping = {"*": "×", "/": "÷"}
        press(mapping.get(key, key))
    elif event.keysym in ("Return", "KP_Enter"):
        press("=")
    elif event.keysym == "BackSpace":
        press("⌫")
    elif event.keysym == "Escape":
        press("C")


# ---------- Main Window ----------
root = tk.Tk()
root.title("Python Calculator")
root.geometry("360x520")
root.minsize(320, 460)
root.configure(bg=BG)

display_var = tk.StringVar(value="0")

# ---------- Heading ----------
heading = tk.Label(
    root,
    text="PYTHON CALCULATOR",
    font=("Arial", 16, "bold"),
    bg=BG,
    fg=TEXT_COLOR
)
heading.pack(pady=(18, 12))

# ---------- Display ----------
display = tk.Entry(
    root,
    textvariable=display_var,
    font=("Arial", 25),
    bg=DISPLAY_BG,
    fg=TEXT_COLOR,
    insertbackground=TEXT_COLOR,
    justify="right",
    relief="flat",
    bd=0,
    state="readonly",
    readonlybackground=DISPLAY_BG
)
display.pack(fill="x", padx=18, ipady=16, pady=(0, 18))

# ---------- Buttons ----------
button_frame = tk.Frame(root, bg=BG)
button_frame.pack(fill="both", expand=True, padx=14, pady=(0, 14))

buttons = [
    ["C", "⌫", "%", "÷"],
    ["7", "8", "9", "×"],
    ["4", "5", "6", "-"],
    ["1", "2", "3", "+"],
    ["±", "0", ".", "="],
]

for row_index, row in enumerate(buttons):
    button_frame.grid_rowconfigure(row_index, weight=1)

    for col_index, value in enumerate(row):
        button_frame.grid_columnconfigure(col_index, weight=1)

        if value == "C":
            color = SPECIAL_BG
        elif value == "=":
            color = EQUAL_BG
        elif value in ("⌫", "%", "÷", "×", "-", "+", "±"):
            color = OPERATOR_BG
        else:
            color = NUMBER_BG

        button = tk.Button(
            button_frame,
            text=value,
            font=("Arial", 17, "bold"),
            bg=color,
            fg=TEXT_COLOR,
            activebackground="#596579",
            activeforeground=TEXT_COLOR,
            relief="flat",
            bd=0,
            cursor="hand2",
            command=lambda v=value: press(v)
        )

        button.grid(
            row=row_index,
            column=col_index,
            sticky="nsew",
            padx=4,
            pady=4,
            ipadx=2,
            ipady=8
        )

# Keyboard shortcuts
root.bind("<Key>", keyboard_input)

root.mainloop()
Dhiraj Singh

Dhiraj Singh

I am a content researcher and publisher specializing in Government Job Notifications, Recruitment Updates, Sarkari Schemes, Admit Cards, Syllabus, and Results. With over 4 years of experience, I focus on providing verified and reliable information collected from official government portals, employment news sources, and state recruitment boards. My objective is to deliver accurate, timely, and well-explained updates to help students and job seekers access authentic information without confusion. I ensure every post includes clear details such as eligibility, selection process, exam pattern, age limits, important dates, and step-by-step application guidelines. Transparency, trust, and user-focused content are the core values behind my work, making rojgareasy.com a dependable platform for Government Job and Recruitment information.

Leave a Comment