Skip to content

aryan-r03/scientific-calculator

Folders and files

NameName
Last commit message
Last commit date

Latest commit

ย 

History

8 Commits
ย 
ย 
ย 
ย 
ย 
ย 

Repository files navigation

Typing SVG

Python NumPy CustomTkinter GUI License

Interface Operations Theme Design


๐Ÿงฎ Modern Scientific Calculator with Dual Interface

Professional Python calculator featuring both CLI and modern GUI interfaces. Built with NumPy for precise scientific calculations and CustomTkinter for a sleek, responsive user experience.

๐Ÿ”ข Perfect for learning Python GUI development, numerical computing, and software design patterns

Features โ€ข Demo โ€ข Quick Start โ€ข Usage โ€ข Operations


๐Ÿ“‹ Table of Contents


๐ŸŒŸ Project Overview

Calculator
Dual Interface
CLI & GUI modes
Flexible usage
Math
Scientific Ops
9+ operations
NumPy precision
Code
Clean Code
Modular design
Separation of concerns
Design
Modern UI
CustomTkinter
Responsive layout

A professional scientific calculator with dual interface support - both command-line and modern GUI. Built to demonstrate clean Python architecture, numerical computing with NumPy, and modern GUI design with CustomTkinter.

๐ŸŽฏ Why This Project?

For Learning:

  • ๐ŸŽ“ Master Python GUI programming
  • ๐Ÿ“Š Understand NumPy for calculations
  • ๐Ÿ—๏ธ Learn modular architecture
  • ๐ŸŽจ Explore CustomTkinter styling
  • ๐Ÿ”ข Practice mathematical algorithms

For Projects:

  • ๐Ÿ’ผ Portfolio-worthy application
  • ๐ŸŽจ Modern, professional UI
  • ๐Ÿงช Robust error handling
  • ๐Ÿ“ฑ Responsive design
  • ๐Ÿ”ง Easy to extend and customize

โœจ Features

Core Capabilities

Category Features
๐Ÿ”ข Basic Operations โœ… Addition (+)
โœ… Subtraction (โˆ’)
โœ… Multiplication (ร—)
โœ… Division (รท)
โœ… Parentheses support ( )
โœ… Decimal point precision
๐Ÿ”ฌ Scientific Functions โœ… Power (x^y)
โœ… Square root (โˆšx)
โœ… Cube root (โˆ›x)
โœ… Logarithm base 10 (logโ‚โ‚€)
โœ… Natural logarithm (ln)
โœ… High precision computation
๐Ÿ–ฅ๏ธ GUI Interface โœ… Modern CustomTkinter design
โœ… Responsive button layout
โœ… Real-time expression display
โœ… Clear and backspace functions
โœ… Color-coded operators
โœ… Smooth hover effects
โŒจ๏ธ CLI Interface โœ… Interactive menu system
โœ… Color-coded output
โœ… Formatted results display
โœ… Operation selection (1-9)
โœ… Continuous calculation mode
โœ… Graceful exit handling
๐Ÿ›ก๏ธ Error Handling โœ… Division by zero protection
โœ… Invalid input detection
โœ… Negative root handling
โœ… Logarithm domain validation
โœ… Expression syntax checking
โœ… User-friendly error messages
๐ŸŽจ Customization โœ… Dynamic appearance mode (Light/Dark)
โœ… Custom color themes
โœ… Resizable window
โœ… Configurable button styles
โœ… Adjustable fonts and sizes
โœ… Easy theme switching

๐ŸŽฌ Demo & Preview

GUI Calculator Interface

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚                     Calculator                     โ”‚
โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค
โ”‚                                                    โ”‚
โ”‚         โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”           โ”‚
โ”‚         โ”‚          123 + 456           โ”‚  Display  โ”‚
โ”‚         โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜           โ”‚
โ”‚                                                    โ”‚
โ”‚           โ”Œโ”€โ”€โ”€โ” โ”Œโ”€โ”€โ”€โ” โ”Œโ”€โ”€โ”€โ” โ”Œโ”€โ”€โ”€โ” โ”Œโ”€โ”€โ”€โ”            โ”‚
โ”‚           โ”‚ ( โ”‚ โ”‚ ) โ”‚ โ”‚ C โ”‚ โ”‚ โŒซ โ”‚ โ”‚ ร— โ”‚            โ”‚
โ”‚           โ””โ”€โ”€โ”€โ”˜ โ””โ”€โ”€โ”€โ”˜ โ””โ”€โ”€โ”€โ”˜ โ””โ”€โ”€โ”€โ”˜ โ””โ”€โ”€โ”€โ”˜            โ”‚
โ”‚                                                    โ”‚
โ”‚                 โ”Œโ”€โ”€โ”€โ” โ”Œโ”€โ”€โ”€โ” โ”Œโ”€โ”€โ”€โ” โ”Œโ”€โ”€โ”€โ”            โ”‚
โ”‚                 โ”‚ 7 โ”‚ โ”‚ 8 โ”‚ โ”‚ 9 โ”‚ โ”‚ รท โ”‚            โ”‚
โ”‚                 โ””โ”€โ”€โ”€โ”˜ โ””โ”€โ”€โ”€โ”˜ โ””โ”€โ”€โ”€โ”˜ โ””โ”€โ”€โ”€โ”˜            โ”‚
โ”‚                                                    โ”‚
โ”‚                 โ”Œโ”€โ”€โ”€โ” โ”Œโ”€โ”€โ”€โ” โ”Œโ”€โ”€โ”€โ” โ”Œโ”€โ”€โ”€โ”            โ”‚
โ”‚                 โ”‚ 4 โ”‚ โ”‚ 5 โ”‚ โ”‚ 6 โ”‚ โ”‚ โˆ’ โ”‚            โ”‚
โ”‚                 โ””โ”€โ”€โ”€โ”˜ โ””โ”€โ”€โ”€โ”˜ โ””โ”€โ”€โ”€โ”˜ โ””โ”€โ”€โ”€โ”˜            โ”‚
โ”‚                                                    โ”‚
โ”‚                 โ”Œโ”€โ”€โ”€โ” โ”Œโ”€โ”€โ”€โ” โ”Œโ”€โ”€โ”€โ” โ”Œโ”€โ”€โ”€โ”            โ”‚
โ”‚                 โ”‚ 1 โ”‚ โ”‚ 2 โ”‚ โ”‚ 3 โ”‚ โ”‚ + โ”‚            โ”‚
โ”‚                 โ””โ”€โ”€โ”€โ”˜ โ””โ”€โ”€โ”€โ”˜ โ””โ”€โ”€โ”€โ”˜ โ””โ”€โ”€โ”€โ”˜            โ”‚
โ”‚                                                    โ”‚
โ”‚                 โ”Œโ”€โ”€โ”€โ” โ”Œโ”€โ”€โ”€โ” โ”Œโ”€โ”€โ”€โ” โ”Œโ”€โ”€โ”€โ”            โ”‚
โ”‚                 โ”‚ 0 โ”‚ โ”‚00 โ”‚ โ”‚ . โ”‚ โ”‚ = โ”‚            โ”‚
โ”‚                 โ””โ”€โ”€โ”€โ”˜ โ””โ”€โ”€โ”€โ”˜ โ””โ”€โ”€โ”€โ”˜ โ””โ”€โ”€โ”€โ”˜            โ”‚
โ”‚                                                    โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

CLI Calculator Interface

=============== Calculator ===============

         Select operation :

1. Addition
   2. Subtraction
      3. Multiplication
4. Division
   5. Power (x^y)
   6. Square Root
 7. Cube Root
           8. Logarithm (base 10)
              9. Natural Logarithm (ln)


Enter choice (1-9) : 
โ–ˆ

You choose to 'Add'

Enter first number  : 25
Enter second number : 75
โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
Sum is = 100.0
โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

Press Enter to calculate again

System Architecture

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚               User Interface Layer               โ”‚
โ”‚  โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”      โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”  โ”‚
โ”‚  โ”‚  CLI Interface  โ”‚      โ”‚  GUI Interface    โ”‚  โ”‚
โ”‚  โ”‚  (calculator.py)โ”‚      โ”‚(Calculator_GUI.py)โ”‚  โ”‚
โ”‚  โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜      โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜  โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
โ”‚                        โ”‚
โ–ผ                        โ–ผ
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚                 Computation Layer                   โ”‚
โ”‚  โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”   โ”‚
โ”‚  โ”‚  Python eval() / NumPy Functions             โ”‚   โ”‚
โ”‚  โ”‚  โ€ข Basic arithmetic (+ - ร— รท)                โ”‚   โ”‚
โ”‚  โ”‚  โ€ข Scientific operations (โˆš, โˆ›, log, ln)     โ”‚   โ”‚
โ”‚  โ”‚  โ€ข Expression evaluation                     โ”‚   โ”‚
โ”‚  โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜   โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
โ”‚
โ–ผ
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚                   Error Handling                    โ”‚
โ”‚  โ€ข Division by zero                                 โ”‚
โ”‚  โ€ข Invalid expressions                              โ”‚
โ”‚  โ€ข Domain errors (negative roots, log of negatives) โ”‚
โ”‚  โ€ข Syntax errors                                    โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

๐Ÿง  Tech Stack

Technologies & Libraries

Python
Python 3.8+
Core language
NumPy
NumPy
Scientific computing
CLI
Built-in Libraries
Math, eval
GUI
CustomTkinter
Modern GUI

Component Stack

Component Technology Purpose
GUI Framework CustomTkinter Modern, themed Tkinter widgets
Scientific Math NumPy sqrt, cbrt, log, log10 functions
Expression Eval Python eval() Dynamic expression evaluation
CLI Output ANSI Escape Codes Colored terminal output
Error Handling Try-Except Blocks Robust error management

๐Ÿ“ฆ Installation

System Requirements

Requirement Minimum Recommended
Python 3.8 3.9 - 3.11
RAM 512 MB 1 GB+
Disk Space 50 MB 100 MB+
OS Windows 7+, macOS 10.12+, Linux (any modern distro)

Dependencies

# Required Dependencies
numpy>=1.24.0           # Scientific computations
customtkinter>=5.0.0    # Modern GUI (for GUI version only)

# Standard Library (Built-in)
math                    # Basic mathematical functions
tkinter                 # GUI toolkit (usually pre-installed)

๐Ÿš€ Quick Start

Step 1๏ธโƒฃ: Clone Repository

git clone https://github.com/your-username/scientific-calculator.git
cd scientific-calculator

Step 2๏ธโƒฃ: Create Virtual Environment (Recommended)

Windows:

python -m venv venv
venv\Scripts\activate

macOS/Linux:

python -m venv venv
source venv/bin/activate

Step 3๏ธโƒฃ: Install Dependencies

For CLI Calculator Only:

pip install numpy

For Both CLI and GUI:

pip install numpy customtkinter

Or use requirements file:

pip install -r requirements.txt

Verify installation:

python -c "import numpy, customtkinter; print('All dependencies installed!')"

Step 4๏ธโƒฃ: Run the Calculator

CLI Version (Command Line):

python calculator.py

GUI Version (Graphical Interface):

python Calculator_GUI.py

๐Ÿ’ป Usage Guide

CLI Calculator (calculator.py)

Features:

  • ๐Ÿ“‹ Interactive menu with 9 operations
  • ๐ŸŽจ Color-coded output for better readability
  • ๐Ÿ”„ Continuous calculation mode
  • โœ… Error handling with clear messages

Usage Flow:

1. Run: python calculator.py
2. Select operation number (1-9)
3. Enter required numbers
4. View result
5. Press Enter to calculate again
6. Press any other key + Enter to exit

Example Session:

$ python calculator.py

Select operation :

1. Addition
   2. Subtraction
      3. Multiplication
4. Division
   5. Power (x^y)
   6. Square Root
 7. Cube Root
           8. Logarithm (base 10)
              9. Natural Logarithm (ln)

Enter choice (1-9) : 5

You choose to 'Check Exponential value'

  Enter base   : 2
Enter exponent : 10
โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
Exponential value is = 1024.0
โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

Press Enter to calculate again

GUI Calculator (Calculator_GUI.py)

Features:

  • ๐Ÿ–ฑ๏ธ Click buttons or use keyboard
  • ๐Ÿ“ฑ Responsive, resizable window
  • ๐ŸŽจ Modern dark theme with green accents
  • โŒซ Backspace for corrections
  • ๐Ÿ”„ Clear button to reset

Usage:

1. Run: python Calculator_GUI.py
2. Click number buttons or type directly
3. Click operation buttons (+, -, ร—, รท)
4. Use parentheses ( ) for complex expressions
5. Press = to calculate result
6. Use C to clear, โŒซ to backspace

Keyboard Shortcuts:

  • 0-9 - Enter numbers
  • + - * / - Operators
  • ( ) - Parentheses
  • . - Decimal point
  • Enter - Calculate (=)
  • Escape - Clear (C)
  • Backspace - Delete last character

Example Expressions:

Simple:        25 + 75 = 100
Complex:       (10 + 5) * 2 = 30
Decimal:       3.14 * 2 = 6.28
Nested:        ((5 + 3) * 2) - 4 = 12

๐Ÿ”ข Supported Operations

CLI Calculator Operations

Operation Choice Syntax Example Result
Addition 1 a + b 25 + 75 100
Subtraction 2 a - b 100 - 42 58
Multiplication 3 a ร— b 12 ร— 8 96
Division 4 a รท b 50 รท 2 25
Power 5 a^b 2^10 1024
Square Root 6 โˆša โˆš144 12
Cube Root 7 โˆ›a โˆ›27 3
Logarithm (base 10) 8 logโ‚โ‚€(a) logโ‚โ‚€(100) 2
Natural Logarithm 9 ln(a) ln(e) 1

GUI Calculator Operations

Button Function Example
0-9 Number input Press '5' โ†’ displays '5'
00 Double zero Quick entry of '00'
. Decimal point 3.14, 2.5, 0.001
+ Addition 5 + 3 = 8
โˆ’ Subtraction 10 - 4 = 6
ร— Multiplication 7 ร— 8 = 56
รท Division 20 รท 4 = 5
( ) Parentheses (5 + 3) ร— 2 = 16
= Calculate result Evaluates expression
C Clear all Resets display
โŒซ Backspace Deletes last character

Error Handling

Error Type Condition Message/Behavior
Division by Zero x รท 0 "Error! Division by zero." (CLI)
"Error" (GUI)
Negative Square Root โˆš(-x) "Square root of negative number not possible"
Negative Cube Root โˆ›(-x) "Cube root of negative number not possible"
Invalid Logarithm log(0) or log(-x) "Logarithm not defined for non-positive numbers"
Invalid Expression Syntax error "Error" displayed, expression cleared

โš™๏ธ Configuration

GUI Appearance Settings

Modify in Calculator_GUI.py:

# Appearance Mode: "light", "dark", or "system" (follows OS)
ctk.set_appearance_mode("dark")  # Change to "light" for light mode

# Color Theme: "blue", "green", or "dark-blue"
ctk.set_default_color_theme("green")  # Change to "blue" for blue accent

# Window Configuration
app.geometry("420x500")        # Width x Height
app.resizable(width=True, height=True)  # Allow resizing

Button Styling

# Number Buttons (Gray)
fg_color="#444"           # Button background
hover_color="#555"        # Hover effect

# Operator Buttons (Orange)
fg_color="#ff9f0a"        # Bright orange
hover_color="#e68900"     # Darker on hover

# Button Dimensions
width=80                  # Button width in pixels
height=70                 # Button height in pixels
corner_radius=15          # Rounded corners

# Font Settings
font=("Helvetica", 18)    # Font family and size

Display Settings

# Entry Widget (Display)
width=400                 # Display width
height=50                 # Display height
font=("Helvetica", 28)    # Font size
justify="center"          # Text alignment: "left", "center", "right"

CLI Output Customization

ANSI Color Codes in calculator.py:

# Color Codes
\033[34m  # Blue (for prompts)
\033[32m  # Green (for results)
\033[33m  # Yellow (for hints)
\033[35m  # Magenta (for goodbye)
\033[3m   # Italic
\033[0m   # Reset formatting

# Example: Change result color from green to cyan
print(f"Result = \033[36m {result} \033[0m")  # Cyan

Disable Colors (for unsupported terminals):

# Remove all \033[...m codes for plain text output
print(f"Result = {result}")

๐ŸŽจ Customization

Extension Ideas

๐Ÿ”ข Add More Scientific Functions

In CLI (calculator.py):

# Add trigonometric functions
elif choice == 10:
    print("You choose to 'Calculate Sine'")
    a = float(input("\nEnter angle in degrees: "))
    print(f"sin({a}ยฐ) = {np.sin(np.radians(a)):.4f}")

elif choice == 11:
    print("You choose to 'Calculate Cosine'")
    a = float(input("\nEnter angle in degrees: "))
    print(f"cos({a}ยฐ) = {np.cos(np.radians(a)):.4f}")

elif choice == 12:
    print("You choose to 'Calculate Tangent'")
    a = float(input("\nEnter angle in degrees: "))
    print(f"tan({a}ยฐ) = {np.tan(np.radians(a)):.4f}")

# Add factorial
elif choice == 13:
    print("You choose to 'Calculate Factorial'")
    n = int(input("\nEnter positive integer: "))
    if n >= 0:
        print(f"{n}! = {np.math.factorial(n)}")

In GUI (Calculator_GUI.py):

# Add scientific function buttons
buttons_scientific = [
    ("sin", 1, 6, lambda: press("np.sin(np.radians(")),
    ("cos", 2, 6, lambda: press("np.cos(np.radians(")),
    ("tan", 3, 6, lambda: press("np.tan(np.radians(")),
    ("โˆš", 4, 6, lambda: press("np.sqrt(")),
    ("ฯ€", 5, 6, lambda: press(str(np.pi))),
    ("e", 6, 6, lambda: press(str(np.e))),
]
๐Ÿ“ Add Calculation History
class CalculatorHistory:
    def __init__(self):
        self.history = []
        self.max_size = 50
    
    def add_calculation(self, expression, result):
        """Add calculation to history"""
        self.history.append({
            'expression': expression,
            'result': result,
            'timestamp': datetime.now()
        })
        if len(self.history) > self.max_size:
            self.history.pop(0)
    
    def get_history(self, n=10):
        """Get last n calculations"""
        return self.history[-n:]
    
    def clear_history(self):
        """Clear all history"""
        self.history = []
    
    def save_to_file(self, filename='calc_history.txt'):
        """Save history to file"""
        with open(filename, 'w') as f:
            for calc in self.history:
                f.write(f"{calc['timestamp']}: {calc['expression']} = {calc['result']}\n")

# Usage
history = CalculatorHistory()

# In calculate() function
result = eval(expression)
history.add_calculation(expression, result)
๐ŸŽจ Create Custom Themes
# Define theme dictionaries
THEMES = {
    'dark': {
        'bg': '#1e1e1e',
        'fg': '#ffffff',
        'button_bg': '#333333',
        'button_hover': '#555555',
        'operator_bg': '#ff9f0a',
        'operator_hover': '#e68900'
    },
    'light': {
        'bg': '#ffffff',
        'fg': '#000000',
        'button_bg': '#e0e0e0',
        'button_hover': '#d0d0d0',
        'operator_bg': '#007aff',
        'operator_hover': '#0051d5'
    },
    'ocean': {
        'bg': '#0d1b2a',
        'fg': '#e0e1dd',
        'button_bg': '#1b263b',
        'button_hover': '#415a77',
        'operator_bg': '#00d9ff',
        'operator_hover': '#00b8d4'
    },
    'sunset': {
        'bg': '#2d1b00',
        'fg': '#fff8dc',
        'button_bg': '#5c3d00',
        'button_hover': '#8b5e00',
        'operator_bg': '#ff6b35',
        'operator_hover': '#e85d2e'
    }
}

def apply_theme(theme_name):
    """Apply selected theme"""
    theme = THEMES.get(theme_name, THEMES['dark'])
    # Apply colors to widgets
    # ... update all widget colors
โŒจ๏ธ Add Keyboard Shortcuts
def on_key_press(event):
    """Handle keyboard input"""
    key = event.char
    
    if key.isdigit() or key in '+-*/.()':
        press(key)
    elif event.keysym == 'Return':
        calculate()
    elif event.keysym == 'Escape':
        clear()
    elif event.keysym == 'BackSpace':
        backspace()

# Bind keyboard events
app.bind('<Key>', on_key_press)
๐Ÿ’พ Save/Load Expressions
def save_expression():
    """Save current expression to file"""
    filename = ctk.filedialog.asksaveasfilename(
        defaultextension=".txt",
        filetypes=[("Text files", "*.txt"), ("All files", "*.*")]
    )
    if filename:
        with open(filename, 'w') as f:
            f.write(expression)

def load_expression():
    """Load expression from file"""
    global expression
    filename = ctk.filedialog.askopenfilename(
        filetypes=[("Text files", "*.txt"), ("All files", "*.*")]
    )
    if filename:
        with open(filename, 'r') as f:
            expression = f.read()
            equation.set(expression)

# Add buttons
save_btn = ctk.CTkButton(app, text="Save", command=save_expression)
load_btn = ctk.CTkButton(app, text="Load", command=load_expression)
๐Ÿ“Š Add Scientific Mode Toggle
class ScientificCalculator:
    def __init__(self):
        self.mode = 'basic'  # 'basic' or 'scientific'
    
    def toggle_mode(self):
        """Switch between basic and scientific mode"""
        if self.mode == 'basic':
            self.mode = 'scientific'
            self.show_scientific_buttons()
        else:
            self.mode = 'basic'
            self.hide_scientific_buttons()
    
    def show_scientific_buttons(self):
        """Show additional scientific function buttons"""
        # sin, cos, tan, log, ln, ฯ€, e, etc.
        pass
    
    def hide_scientific_buttons(self):
        """Hide scientific buttons"""
        pass

๐Ÿ—๏ธ Architecture

Project Structure

scientific-calculator/
โ”‚
โ”œโ”€โ”€ ๐Ÿ“„ calculator.py              # CLI Calculator
โ”‚   โ”œโ”€โ”€ Menu system (1-9 operations)
โ”‚   โ”œโ”€โ”€ NumPy scientific functions
โ”‚   โ”œโ”€โ”€ Color-coded output (ANSI)
โ”‚   โ”œโ”€โ”€ Error handling
โ”‚   โ””โ”€โ”€ Continuous calculation loop
โ”‚
โ”œโ”€โ”€ ๐Ÿ“„ Calculator_GUI.py          # GUI Calculator
โ”‚   โ”œโ”€โ”€ CustomTkinter interface
โ”‚   โ”œโ”€โ”€ Button grid layout (7x6)
โ”‚   โ”œโ”€โ”€ Expression evaluation
โ”‚   โ”œโ”€โ”€ Real-time display update
โ”‚   โ”œโ”€โ”€ Event handlers (press, clear, backspace)
โ”‚   โ””โ”€โ”€ Styling and theming
โ”‚
โ”œโ”€โ”€ ๐Ÿ“„ requirements.txt           # Dependencies
โ”‚   โ”œโ”€โ”€ numpy>=1.24.0
โ”‚   โ””โ”€โ”€ customtkinter>=5.0.0
โ”‚
โ”œโ”€โ”€ ๐Ÿ“„ README.md                  # Documentation
โ”‚
โ””โ”€โ”€ ๐Ÿ“„ LICENSE                    # MIT License

Code Flow Diagrams

CLI Calculator Flow:

Start
  โ”‚
  โ–ผ
Display Menu (1-9)
  โ”‚
  โ–ผ
Get User Choice
  โ”‚
  โ”‚--โ†’ Choice 1-5: Get 2 numbers
  โ”‚   โ”‚--โ†’ Perform operation
  โ”‚   โ”‚--โ†’ Display result
  โ”‚
  โ”‚--โ†’ Choice 6-9: Get 1 number
  โ”‚   โ”‚--โ†’ Validate (negative check for roots, log)
  โ”‚   โ”‚--โ†’ Perform operation
  โ”‚   โ”‚--โ†’ Display result
  โ”‚
  โ”‚--โ†’ Invalid: Show error
  โ”‚
  โ–ผ
Ask to Continue
  โ”‚
  โ”‚--โ†’ Enter pressed: Loop back to menu
  โ”‚--โ†’ Any key: Exit with goodbye

GUI Calculator Flow:

Initialize GUI
  โ”‚
  โ–ผ
Display Window
  โ”‚
  โ”‚--โ†’ Button Click Event
  โ”‚   โ”‚--โ†’ Number/Operator: Append to expression
  โ”‚   โ”‚--โ†’ Clear: Reset expression
  โ”‚   โ”‚--โ†’ Backspace: Remove last char
  โ”‚   โ”‚--โ†’ Equals: Evaluate expression
  โ”‚       โ”‚--โ†’ Valid: Display result
  โ”‚       โ”‚--โ†’ Error: Display "Error"
  โ”‚
  โ”‚--โ†’ Keep window open (mainloop)

Design Patterns

Pattern Implementation Benefit
Separation of Concerns Separate CLI and GUI interfaces Modular, maintainable code
Event-Driven Button callbacks, event handlers Responsive UI, clean flow
Error Handling Try-except blocks, validation Robust, user-friendly
Function Composition Helper functions (press, clear, calculate) Reusable, testable code

๐Ÿ› Troubleshooting

Common Issues & Solutions

โŒ Module Not Found: customtkinter

Symptoms:

ModuleNotFoundError: No module named 'customtkinter'

Solutions:

  1. Install CustomTkinter:

    pip install customtkinter
  2. Verify Installation:

    pip list | grep customtkinter
  3. Use Virtual Environment:

    python -m venv venv
    source venv/bin/activate  # Linux/Mac
    venv\Scripts\activate     # Windows
    pip install customtkinter
  4. Alternative: Use Standard Tkinter: If CustomTkinter doesn't work, modify code to use standard Tkinter:

    import tkinter as tk
    # Replace ctk with tk
๐Ÿ–ฅ๏ธ GUI Window Not Appearing

Symptoms:

  • Script runs but no window shows
  • Window appears then immediately closes

Solutions:

  1. Check Display Environment (Linux):

    echo $DISPLAY
    # Should output something like :0 or :1
  2. Test Tkinter Installation:

    python -c "import tkinter; tkinter.Tk()"
    # Should show empty window
  3. macOS: Grant Terminal Access:

    • System Preferences โ†’ Security & Privacy
    • Allow Terminal to control computer
  4. Windows: Update Graphics Drivers

  5. Add Error Handling:

    try:
        app = ctk.CTk()
        app.mainloop()
    except Exception as e:
        print(f"GUI Error: {e}")
๐Ÿ”ข Calculation Errors in GUI

Symptoms:

  • "Error" displayed frequently
  • Unexpected results

Solutions:

  1. Check Expression Syntax:

    • Ensure balanced parentheses
    • Use * for multiplication (not ร—)
    • Avoid starting with operators
  2. Division by Zero:

    # Add check before eval
    if '/0' in expression or 'รท0' in expression:
        equation.set("Cannot divide by zero")
        return
  3. Add Expression Validation:

    def is_valid_expression(expr):
        """Check if expression is valid"""
        try:
            # Check balanced parentheses
            if expr.count('(') != expr.count(')'):
                return False
            # Test evaluation without executing
            compile(expr, '<string>', 'eval')
            return True
        except:
            return False
  4. Safe Eval:

    import ast
    import operator
    
    # Use safer eval with limited operators
    safe_operators = {
        ast.Add: operator.add,
        ast.Sub: operator.sub,
        ast.Mult: operator.mul,
        ast.Div: operator.truediv,
        ast.Pow: operator.pow,
    }
๐ŸŽจ Colors Not Displaying (CLI)

Symptoms:

  • ANSI codes visible as text
  • No colored output in terminal

Solutions:

  1. Windows: Enable ANSI Support:

    import os
    os.system('color')  # Enable ANSI in Windows CMD
  2. Use colorama (cross-platform):

    pip install colorama
    from colorama import init, Fore, Style
    init()  # Initialize colorama
    
    print(f"{Fore.GREEN}Result = {result}{Style.RESET_ALL}")
  3. Disable Colors:

    # Remove all \033[...m codes
    print(f"Result = {result}")  # Plain text
โš ๏ธ NumPy Import Errors

Symptoms:

ModuleNotFoundError: No module named 'numpy'
ImportError: numpy.core.multiarray failed to import

Solutions:

  1. Install NumPy:

    pip install numpy
  2. Upgrade NumPy:

    pip install --upgrade numpy
  3. Check Python Version:

    python --version
    # NumPy requires Python 3.8+
  4. Reinstall NumPy:

    pip uninstall numpy
    pip install numpy

๐Ÿš€ Future Enhancements

Planned Features

Feature Description Status
๐Ÿ”ข Complete Scientific Functions Add sin, cos, tan, asin, acos, atan ๐Ÿ”„ Planned
๐Ÿ“Š Graphing Calculator Plot functions and equations ๐Ÿ”„ Planned
๐Ÿ“ Calculation History Save and view past calculations ๐Ÿ”„ Planned
๐Ÿ”ข Unit Converter Convert between units (length, weight, etc.) ๐Ÿ’ก Idea
๐ŸŽจ Theme Selector Multiple color themes to choose from ๐Ÿ’ก Idea
๐Ÿ“ฑ Mobile App Port to iOS/Android with Kivy ๐Ÿ’ก Idea
๐Ÿ”Š Voice Input Speak mathematical expressions ๐Ÿ’ก Idea
๐Ÿ“ Geometry Tools Area, perimeter, volume calculations ๐Ÿ’ก Idea
๐Ÿ“ˆ Statistics Mode Mean, median, standard deviation ๐Ÿ’ก Idea
๐Ÿ”— API Integration Wolfram Alpha or Symbolab integration ๐Ÿ’ก Idea

๐Ÿค Contributing

Contributions are welcome! Help improve this calculator:

Ways to Contribute

Bug
Report Bugs
Found an issue?
Open an issue
Feature
Suggest Features
Have an idea?
Share it!
Code
Submit Code
Add features?
Send a PR
Docs
Improve Docs
Better explanation?
Update README

Development Workflow

  1. Fork the repository
  2. Clone your fork:
    git clone https://github.com/your-username/scientific-calculator.git
    cd scientific-calculator
  3. Create a feature branch:
    git checkout -b feature/new-function
  4. Make your changes
  5. Test thoroughly (CLI and GUI)
  6. Commit with clear messages:
    git commit -m 'Add trigonometric functions'
  7. Push to your fork:
    git push origin feature/new-function
  8. Open a Pull Request

Code Style Guidelines

  • โœ… Follow PEP 8 for Python code
  • โœ… Use descriptive variable names
  • โœ… Add comments for complex logic
  • โœ… Include docstrings for functions
  • โœ… Test with various inputs
  • โœ… Update documentation for new features

๐Ÿ“„ License

This project is licensed under the MIT License

Free to use, modify, and distribute with attribution

Click to view full license
MIT License

Copyright (c) 2025 Scientific Calculator Project

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

๐Ÿ™ Acknowledgments

Special thanks to:

  • ๐Ÿ Python Software Foundation for the amazing language
  • ๐Ÿ”ข NumPy Developers for scientific computing tools
  • ๐ŸŽจ CustomTkinter for modern GUI widgets
  • ๐Ÿ‘ฅ Open Source Community for inspiration and support
  • ๐Ÿ’š You for using and supporting this project!

๐Ÿ‘จโ€๐Ÿ’ป Author

Author Typing SVG

๐ŸŽ“ Computer Applications in AI & ML
Building practical software solutions with Python


๐Ÿ“ž Support

Need Help?

Docs
Documentation
Complete README Guide
Setup & troubleshooting
Code
Code Comments
In-line Documentation
Implementation details

Refer to the troubleshooting section above for common issues and solutions


๐ŸŒŸ Show Your Support

If this project helped you, please consider:

GitHub stars GitHub forks GitHub watchers



โญ Star this repository if you found it helpful!

๐Ÿด Fork it to customize for your needs!

๐Ÿ“ข Share it with Python learners!


Footer

๐Ÿงฎ "Mathematics is the language with which God has written the universe." - Galileo Galilei





ยฉ 2025 Open Source Project | Scientific Computing | MIT License


About

A professional scientific calculator with dual interface support - both command-line and modern GUI. Built to demonstrate clean Python architecture, numerical computing with NumPy, and modern GUI design with CustomTkinter.

Resources

Stars

Watchers

Forks

Packages

 
 
 

Contributors

Languages