Create a Calculator in Python Programming Language

Create a Calculator in Python Programming Language

Create a Calculator in Python Programming Language

Why a calculator tutorial still matters?

A calculator is one of the most approachable projects for anyone learning to code. It’s small enough to finish in an afternoon, but rich enough to teach important programming ideas: functions, error handling, input validation, and (if you want) a touch of GUI design. In this post I’ll walk you through a human-friendly Python calculator: first a clean command-line version, then an optional simple GUI using tkinter. I’ll explain each piece of code like I’m standing beside you — one step at a time.

What you’ll learn

  • How to structure a small but robust Python program.
  • How to validate user input and handle common errors gracefully.
  • How to add new functions (percent, power, memory) in a way that scales.
  • How to write the blog post for humans and search engines (SEO friendly suggestions included).

Step 1. Import Required Libraries

import tkinter as tk
from tkinter import messagebox
  • tkinter → Python’s built-in GUI library for creating windows, buttons, and other widgets.
  • messagebox → used to show pop-up error messages when invalid expressions are entered.

2. Create a Gradient Button Class

We want buttons with beautiful gradients, not just plain colors. For that, we create a custom GradientButton class:
class GradientButton(tk.Canvas):
    def __init__(self, master, text, command=None,
                 width=80, height=60,
                 color1="#6a11cb", color2="#2575fc"):
        super().__init__(master, width=width, height=height, highlightthickness=0)
        self.command = command
        self.text = text
        self.color1 = color1
        self.color2 = color2

        self._draw_gradient()
        self.create_text(width // 2, height // 2, text=text,
                         fill="white", font=("Arial", 16, "bold"))
        self.bind("", lambda e: self.command() if self.command else None)
  • master → parent widget (container).
  • text → button label like 1, +, =.
  • command → function called when button is clicked.
  • _draw_gradient() → draws the gradient background.
  • create_text → draws the button label.
  • bind("<Button-1>") → makes the button clickable.
Gradient Drawing Logic:
def _draw_gradient(self):
    steps = 100
    r1, g1, b1 = self.winfo_rgb(self.color1)
    r2, g2, b2 = self.winfo_rgb(self.color2)
    r_ratio = (r2-r1)/steps
    g_ratio = (g2-g1)/steps
    b_ratio = (b2-b1)/steps

    for i in range(steps):
        nr = int(r1 + (r_ratio * i))
        ng = int(g1 + (g_ratio * i))
        nb = int(b1 + (b_ratio * i))
        color = f"#{nr>>8:02x}{ng>>8:02x}{nb>>8:02x}"
        self.create_line(0, i, self.winfo_reqwidth(), i, fill=color)
  • winfo_rgb(color) → gets RGB values for the top and bottom colors.
  • steps → number of horizontal lines to draw for the gradient.
  • Interpolates color values from color1 → color2.
  • create_line draws each line to create a smooth gradient.

3. Create the Calculator Window

class GradientCalculator(tk.Tk):
    def __init__(self):
        super().__init__()
        self.title('Stylish Gradient Calculator')
        self.geometry('360x520')
        self.configure(bg="#1e1e2f")
        self._create_widgets()
  • Subclass tk.Tk to make the main window.
  • Set title, size, and background color.
  • _create_widgets() → sets up Entry, result label, and buttons.

4. Create Input and Result Display

# Input field
self.display = tk.Entry(self, font=('Arial', 20),
                        justify='right', bd=0, relief='flat')
self.display.pack(fill='both', ipadx=8, ipady=10, pady=10, padx=10)

# Result label
self.result_label = tk.Label(self, text="Result: ",
                             font=("Arial", 16),
                             fg="white", bg="#1e1e2f", anchor="e")
self.result_label.pack(fill='both', padx=10, pady=(0, 10))
  • Entry → for typing expressions.
  • justify='right' → numbers align to the right.
  • result_label → shows results below input without overwriting it.
  • anchor='e' → aligns text to the right.

5. Create the Buttons

buttons = [
    '7', '8', '9', '/',
    '4', '5', '6', '*',
    '1', '2', '3', '-',
    '0', '.', '=', '+',
]

frame = tk.Frame(self, bg="#1e1e2f")
frame.pack(expand=True, fill='both')

for i, label in enumerate(buttons):
    def cmd(x=label):
        self.on_press(x)

    btn = GradientButton(
        frame,
        text=label,
        command=cmd,
        color1="#ff9966", color2="#ff5e62"
    ) if label == '=' else GradientButton(
        frame,
        text=label,
        command=cmd,
        color1="#36d1dc", color2="#5b86e5"
    )

    btn.grid(row=i // 4, column=i % 4, padx=5, pady=5)
  • buttons → list of all button labels.
  • Frame → container for the buttons.
  • Loops through buttons, creating GradientButton for each.
  • The = button gets a special gradient to highlight it.
  • grid → arranges buttons in a 4×4 grid.

6. Handle Button Presses

def on_press(self, label):
    if label == '=':
        try:
            result = eval(self.display.get())
            self.result_label.config(text=f"Result: {result}")
        except Exception as e:
            messagebox.showerror('Error', f'Bad expression: {e}')
    else:
        self.display.insert('end', label)
  • = → evaluates expression in Entry.
  • eval() → converts string like "12+3" into a numeric result.
  • result_label.config(...) → updates the result without clearing the input.
  • Other buttons → append value to Entry.

7. Run the Calculator

if __name__ == '__main__':
    GradientCalculator().mainloop()

✅ Key Features

Feature Explanation
Gradient buttons Smooth color transition, makes the UI modern
Dark theme Colors pop and look professional
Separate result label Shows results without clearing input
= button highlight Clearly indicates the main action
Easy to expand Add %, Clear, Backspace buttons easily

Full Code

"""
Python Calculator
- Stylish Gradient GUI with tkinter
"""

import tkinter as tk
from tkinter import messagebox


# -----------------------------
# CLI CALCULATOR
# -----------------------------
OPERATIONS = {
    '+': lambda a, b: a + b,
    '-': lambda a, b: a - b,
    '*': lambda a, b: a * b,
    '/': lambda a, b: a / b if b != 0 else float('inf'),
    '^': lambda a, b: a ** b,
}


def parse_number(text):
    """Try to convert input text into a number."""
    try:
        if '.' in text:
            return float(text)
        return int(text)
    except ValueError:
        raise ValueError(f"Invalid number: {text}")


def calculate(a_text, op, b_text):
    a = parse_number(a_text)
    b = parse_number(b_text)
    if op not in OPERATIONS:
        raise ValueError(f"Unsupported operation: {op}")
    return OPERATIONS[op](a, b)


def cli_calculator():
    print("Python Calculator!")
    print("Enter expressions like: 12 + 4 or 2.5 ^ 3")
    print("Supported ops: + - * / ^")

    while True:
        try:
            text = input("\nExpression (or type quit): ").strip()
            if text.lower() in ('quit', 'exit'):
                print("Bye — happy coding!")
                break

            parts = text.split()
            if len(parts) != 3:
                print("Please enter expressions in the form: number operator number")
                continue

            a_text, op, b_text = parts
            result = calculate(a_text, op, b_text)
            if result == float('inf'):
                print("Error: Division by zero")
            else:
                print(f"Result: {result}")

        except Exception as e:
            print("Error:", e)


# -----------------------------
# GRADIENT BUTTON GUI
# -----------------------------
class GradientButton(tk.Canvas):
    def __init__(self, master, text, command=None,
                 width=80, height=60,
                 color1="#6a11cb", color2="#2575fc"):
        super().__init__(master, width=width, height=height, highlightthickness=0)
        self.command = command
        self.text = text
        self.color1 = color1
        self.color2 = color2

        self._draw_gradient()
        self.create_text(width // 2, height // 2, text=text,
                         fill="white", font=("Arial", 16, "bold"))
        self.bind("", lambda e: self.command() if self.command else None)

    def _draw_gradient(self):
        steps = 100
        r1, g1, b1 = self.winfo_rgb(self.color1)
        r2, g2, b2 = self.winfo_rgb(self.color2)
        r_ratio = (r2 - r1) / steps
        g_ratio = (g2 - g1) / steps
        b_ratio = (b2 - b1) / steps

        for i in range(steps):
            nr = int(r1 + (r_ratio * i))
            ng = int(g1 + (g_ratio * i))
            nb = int(b1 + (b_ratio * i))
            color = f"#{nr >> 8:02x}{ng >> 8:02x}{nb >> 8:02x}"
            self.create_line(0, i, self.winfo_reqwidth(), i, fill=color)


class GradientCalculator(tk.Tk):
    def __init__(self):
        super().__init__()
        self.title('Calculator in Python (Skill & Dedication)')
        self.geometry('360x520')
        self.configure(bg="#1e1e2f")
        self._create_widgets()

    def _create_widgets(self):
        # Input field
        self.display = tk.Entry(self, font=('Arial', 20),
                                justify='right', bd=0, relief='flat')
        self.display.pack(fill='both', ipadx=8, ipady=10, pady=10, padx=10)

        # Result label (below input)
        self.result_label = tk.Label(self, text="Result: ",
                                     font=("Arial", 16),
                                     fg="white", bg="#1e1e2f", anchor="e")
        self.result_label.pack(fill='both', padx=10, pady=(0, 10))

        buttons = [
            '7', '8', '9', '/',
            '4', '5', '6', '*',
            '1', '2', '3', '-',
            '0', '.', '=', '+',
        ]

        frame = tk.Frame(self, bg="#1e1e2f")
        frame.pack(expand=True, fill='both')

        for i, label in enumerate(buttons):
            def cmd(x=label):
                self.on_press(x)

            btn = GradientButton(
                frame,
                text=label,
                command=cmd,
                color1="#ff9966", color2="#ff5e62"
            ) if label == '=' else GradientButton(
                frame,
                text=label,
                command=cmd,
                color1="#36d1dc", color2="#5b86e5"
            )

            btn.grid(row=i // 4, column=i % 4, padx=5, pady=5)

    def on_press(self, label):
        if label == '=':
            try:
                result = eval(self.display.get())
                # Keep expression in entry, show result separately
                self.result_label.config(text=f"Result: {result}")
            except Exception as e:
                messagebox.showerror('Error', f'Bad expression: {e}')
        else:
            self.display.insert('end', label)



# -----------------------------
# ENTRY POINT
# -----------------------------
if __name__ == '__main__':

        GradientCalculator().mainloop()

Final Output Result:

Calculator in Python Programming Language Screenshot

🧾 FAQs About Python Calculator

1. What concepts can I learn by creating a calculator in Python?

You’ll understand basic syntax, user input handling, conditionals, arithmetic operations, and simple error handling.

2. How can I extend this calculator further?

You can add features like exponentiation, square roots, history tracking, or even a graphical interface using Tkinter.

3. Can I use this calculator in a GUI window instead of the terminal?

Yes, using the Tkinter or PyQt library, you can create buttons and display results visually.

4. What happens if the user enters invalid input?

You can wrap your input and calculations in a try-except block to catch ValueError and show a friendly error message.

5. Is Python good for building full-fledged calculator apps?

Yes! Python is great for both simple and complex calculators, from CLI tools to advanced GUI-based or web-based calculators.

6. How do I make the calculator repeat until the user exits?

Wrap your code inside a while True loop and provide an option to quit (e.g., pressing “q” to exit).
Previous Post Next Post

Contact Form