> For the complete documentation index, see [llms.txt](https://htooaunklinn-organization.gitbook.io/htooaunklinn-docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://htooaunklinn-organization.gitbook.io/htooaunklinn-docs/hardware-and-iot/python/command-line-calculator-with-python.md).

# Command-Line Calculator with Python

Create a command-line calculator app, `mycal`, using Python and `argparse`. Run it from the Terminal like:

```bash
mycal -s "+" -f "100" -n "200"
```

Follow these steps to build it:

**Step 1: Create the Python Script**

Create a file named `mycal` and add the following script:

```python
#!/usr/bin/env python3
import argparse

def calculate(sign, first, second):
    try:
        first = float(first)
        second = float(second)

        if sign == "+":
            return first + second
        elif sign == "-":
            return first - second
        elif sign == "*":
            return first * second
        elif sign == "/":
            return first / second
        else:
            return "Invalid operator!"
    except Exception as e:
        return f"Error: {e}"

def main():
    parser = argparse.ArgumentParser(description="Simple CLI Calculator")

    parser.add_argument('-s', '--sign', required=True, help='Operator: +, -, *, /')
    parser.add_argument('-f', '--first', required=True, help='First number')
    parser.add_argument('-n', '--second', required=True, help='Second number')

    args = parser.parse_args()

    result = calculate(args.sign, args.first, args.second)
    print(f"Result: {result}")

if __name__ == "__main__":
    main()
```

**Step 2: Make It Executable**

In the Terminal, run:

```bash
chmod +x mycal
```

Move it to your path:

```bash
mv mycal /usr/local/bin/
```

Now, use it like:

```bash
mycal -s "+" -f "100" -n "200"
```

Output:

```
Result: 300.0
```

#### Notes

* `-s` for sign/operator
* `-f` for the first number
* `-n` for the second number
* Use full names: `--sign`, `--first`, `--second` if preferred

Interested in expanding functionality with power (`**`), modulus (`%`), or string expressions? Let me know!

#### Issue with Missing Directory and Operation Permission

The user is experiencing two issues on their macOS system:

1. **Missing Directory**: The `/usr/local/bin` directory does not exist, only `/usr/local` is present. This might require creating the directory if needed by running:

   ```bash
   mkdir /usr/local/bin
   ```

   Ensure you have the proper permissions or use `sudo` if necessary.
2. **Permission Error**: When trying to move a file to `/bin` using:

   ```bash
   sudo mv mycal /bin
   ```

   The operation fails with "Operation not permitted". This could be due to system integrity protection (SIP) preventing modifications to system directories.

#### Suggestions

* **Create Missing Directory**: If you need `/usr/local/bin`, create it with:

  ```bash
  sudo mkdir -p /usr/local/bin
  ```
* **Address Operation Not Permitted**: Try using a different directory such as `/usr/local/bin`:

  ```bash
  sudo mv mycal /usr/local/bin
  ```

Ensure SIP is not overly restrictive for necessary operations or consider alternative directories like `/usr/local/bin` for installing custom binaries.

**If you're using macOS and need to move CLI tools to a secure location, follow these steps.** System Integrity Protection (SIP) in macOS restricts access to certain system folders like `/bin`.

#### 💡 Recommended Approach: Create a Custom Bin Directory

***

**🔧 Step-by-Step Guide**

**1. Create a Custom CLI Tools Folder**

```bash
mkdir -p $HOME/.mybin
```

**2. Transfer Your Script**

If `mycal` is in the current directory:

```bash
mv mycal $HOME/.mybin/
```

**3. Update Your PATH Variable**

Edit your shell configuration file:

* **zsh**: `~/.zshrc`
* **bash**: `~/.bash_profile` or `~/.bashrc`

Add this line:

```bash
export PATH="$HOME/.mybin:$PATH"
```

Reload your shell configuration:

```bash
source ~/.zshrc   # or source ~/.bash_profile
```

**✅ Verify It**

Run your script:

```bash
mycal -s "+" -f "100" -n "200"
```

Expected output:

```
Result: 300.0
```

You can edit `mycal` anytime in `$HOME/.mybin`. For features like history or logging, feel free to reach out!
