Python से Simple Calculator कैसे बनाएं | Python Calculator Code in Hindi (CLI + GUI Tutorial)

Python से Simple Calculator कैसे बनाएं (CLI & GUI) — Step by Step (Hindi)

Python Simple Calculator in Hindi Tutorial

अगर आप Python से एक simple calculator बनाना सीखना चाहते हैं — तो यह पोस्ट आपके लिए है। यहाँ हम दो तरह के calculator बनाएँगे: Command-line (Terminal) और GUI (Tkinter)। दोनों बिलकुल beginners-friendly हैं।


🔧 क्या चाहिए (Requirements)

  • Python 3 (अगर नहीं है तो python.org से इंस्टॉल करें)
  • Basic text editor (Notepad, VS Code, PyCharm आदि)
  • GUI के लिए Python में built-in tkinter (Python के साथ आता है)

1️⃣ Command-line (Terminal) Simple Calculator

यह सबसे आसान तरीका है — टर्मिनल/कमांड प्रॉम्प्ट में चलेगा।


# simple_calc_cli.py

def add(a, b):
    return a + b

def subtract(a, b):
    return a - b

def multiply(a, b):
    return a * b

def divide(a, b):
    if b == 0:
        return "Error: Zero se divide nahi kar sakte"
    return a / b

def main():
    print("=== Simple Python Calculator (CLI) ===")
    print("Operations: + , - , * , /")
    while True:
        try:
            x = float(input("Pehla number (ya 'q' quit ke liye): "))
        except ValueError:
            print("Program exited.")
            break
        op = input("Operation (+, -, *, /): ").strip()
        try:
            y = float(input("Dusra number: "))
        except ValueError:
            print("Invalid number. Try again.")
            continue

        if op == "+":
            print("Result:", add(x, y))
        elif op == "-":
            print("Result:", subtract(x, y))
        elif op == "*":
            print("Result:", multiply(x, y))
        elif op == "/":
            print("Result:", divide(x, y))
        else:
            print("Invalid operation. Try +, -, *, /")

        cont = input("Aur calculation karein? (y/n): ").lower()
        if cont != 'y':
            print("Thanks for using calculator!")
            break

if __name__ == "__main__":
    main()

चलाने का तरीका: टर्मिनल में `python simple_calc_cli.py` चलाओ और निर्देश फॉलो करो।


2️⃣ GUI Calculator using Tkinter (Simple Calculator)

यह छोटा सा विंडो वाला calculator है — buttons और display के साथ।


# simple_calc_gui.py

import tkinter as tk

def on_click(btn_text):
    current = display.get()
    if btn_text == "C":
        display.set("")
    elif btn_text == "=":
        try:
            # evaluate expression safely
            result = str(eval(current))
            display.set(result)
        except Exception:
            display.set("Error")
    else:
        display.set(current + btn_text)

# Window setup
root = tk.Tk()
root.title("Simple Calculator")
root.resizable(False, False)

display = tk.StringVar()
entry = tk.Entry(root, textvariable=display, font=("Arial", 24), bd=8, relief=tk.RIDGE, justify='right')
entry.grid(row=0, column=0, columnspan=4, padx=8, pady=8)

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

# place buttons in grid
row_index = 1
col_index = 0
for b in buttons:
    action = lambda x=b: on_click(x)
    btn = tk.Button(root, text=b, width=5, height=2, font=("Arial", 18), command=action)
    if b == 'C':
        btn.grid(row=5, column=0, columnspan=4, sticky="we", padx=4, pady=4)
    else:
        btn.grid(row=row_index, column=col_index, padx=4, pady=4)
        col_index += 1
        if col_index > 3:
            col_index = 0
            row_index += 1

root.mainloop()

नोट: यह उदाहरण छोटा और शिक्षण के लिए है — eval() का उपयोग किया गया है क्योंकि यह सिंपल expression evaluation देता है। पर ध्यान रखें कि eval unsafe input के साथ खतरनाक हो सकता है — प्रोडक्शन में उपयोग से पहले input validation ज़रूरी है।


⚠️ Safety Tip (eval() के बारे में)

eval() सीधे किसी string को Python expression के रूप में चलाता है — अगर user से अनजान या malicious input आ सकता है तो यह खतरा पैदा कर सकता है। सीखने के लिए ठीक है, पर असली project में safer parser (या manually parse करना) बेहतर है।


📝 Bonus: CLI Calculator — Improved (with operators map)


# improved_cli.py
import operator

ops = {
    '+': operator.add,
    '-': operator.sub,
    '*': operator.mul,
    '/': lambda a, b: "Error: divide by zero" if b == 0 else operator.truediv(a, b)
}

a = float(input("Pehla number: "))
op = input("Operator (+ - * /): ")
b = float(input("Dusra number: "))

if op in ops:
    print("Result:", ops[op](a, b))
else:
    print("Invalid operator")

✅ Conclusion

अब आपने दो तरह के simple calculator बनाए — एक टर्मिनल आधारित और एक GUI आधारित। शुरुआत के लिए यह बेहतरीन है।

अगर आप चाहो तो मैं infix expression parsing वाला safer evaluator, या scientific calculator (sin, cos, log) वाला version भी बना कर दे सकता हूँ। बताओ कौनसा चाहिए?

Python Calculator, Simple Calculator Python, Python GUI Calculator, Tkinter Tutorial in Hindi, Python Projects for Beginners, Python Code in Hindi, Python CLI Calculator, Python Basic Programs, Python सीखें, Python Programming Hindi

🔥 Related Posts (Suggested)

💡 अगर यह पोस्ट पसंद आई तो शेयर करो और नीचे कमेंट में बताओ — मैं GUI को और सुंदर बना कर दे दूंगा!

❓Frequently Asked Questions (FAQ)

1️⃣ Python में Calculator कैसे बनाया जा सकता है?

Python में calculator बनाने के लिए आप input() और basic operators (+, -, *, /) का उपयोग कर सकते हैं। इसके अलावा Tkinter लाइब्रेरी से GUI Calculator भी बनाया जा सकता है।

2️⃣ Tkinter क्या है?

Tkinter Python की एक built-in GUI लाइब्रेरी है जो विंडो, बटन और इनपुट बॉक्स जैसी इंटरफेस बनाने की सुविधा देती है। इससे आप अपने प्रोग्राम को यूजर-फ्रेंडली बना सकते हैं।

3️⃣ क्या Python में GUI बनाना मुश्किल है?

नहीं, Python में GUI बनाना बहुत आसान है। Tkinter या PySimpleGUI जैसी लाइब्रेरी की मदद से आप कुछ ही लाइनों में calculator, form या tool बना सकते हैं।

4️⃣ क्या Python calculator मोबाइल पर चल सकता है?

Python calculator मोबाइल पर सीधे नहीं चलता, लेकिन अगर आप Pydroid 3 या Termux जैसी apps का उपयोग करें तो Python scripts को मोबाइल में भी चला सकते हैं।

5️⃣ क्या यह calculator offline चलेगा?

हाँ, यह calculator पूरी तरह से offline चलता है क्योंकि यह केवल Python code पर आधारित है, किसी इंटरनेट कनेक्शन की जरूरत नहीं होती।

टिप्पणियाँ

इस ब्लॉग से लोकप्रिय पोस्ट

RBSE Class 12 Computer Science Chapter 1 Question and Answers

अपने कंप्यूटर में पाइथन कैसे इनस्टॉल करें How to install Python in your Computer