Cal11 calculator

Python How to Make Calculator with Square Root

Reviewed by Calculator Editorial Team

This guide shows you how to create a Python calculator that can perform basic arithmetic operations including square root calculations. We'll walk through the code step by step and provide a complete working example.

Creating a Basic Python Calculator

Before adding square root functionality, let's create a simple calculator that can handle basic operations like addition, subtraction, multiplication, and division.

The basic calculator will use Python's built-in functions and simple conditional logic to determine which operation to perform.

Step 1: Set Up the Calculator Structure

We'll create a function that takes three parameters: two numbers and an operator. The function will then perform the appropriate calculation based on the operator.

Step 2: Implement Basic Operations

We'll use Python's arithmetic operators to implement addition, subtraction, multiplication, and division.

Step 3: Handle User Input

We'll create a simple interface that prompts the user to enter two numbers and select an operation.

Adding Square Root Functionality

Now let's enhance our calculator to include square root calculations using Python's math module.

The square root of a number x is a value that, when multiplied by itself, gives x. In Python, we can calculate square roots using the math.sqrt() function.

Step 1: Import the Math Module

First, we need to import Python's math module which contains the sqrt() function.

Step 2: Add Square Root to Operations

We'll modify our calculator function to handle square root operations when the user selects this option.

Step 3: Update the User Interface

We'll add a new option to our user interface for square root calculations.

Complete Calculator Code

Here's the complete Python code for a calculator with square root functionality:

This code includes all the functionality we've discussed, with clear comments explaining each part.

import math

def calculator():
    print("Python Calculator with Square Root")
    print("Operations available:")
    print("1. Addition (+)")
    print("2. Subtraction (-)")
    print("3. Multiplication (*)")
    print("4. Division (/)")
    print("5. Square Root (√)")

    while True:
        try:
            # Get user input
            num1 = float(input("Enter first number: "))
            operation = input("Enter operation (1/2/3/4/5): ")
            if operation != '5':
                num2 = float(input("Enter second number: "))

            # Perform calculation
            if operation == '1':
                result = num1 + num2
                print(f"Result: {num1} + {num2} = {result}")
            elif operation == '2':
                result = num1 - num2
                print(f"Result: {num1} - {num2} = {result}")
            elif operation == '3':
                result = num1 * num2
                print(f"Result: {num1} * {num2} = {result}")
            elif operation == '4':
                if num2 == 0:
                    print("Error: Division by zero")
                else:
                    result = num1 / num2
                    print(f"Result: {num1} / {num2} = {result}")
            elif operation == '5':
                if num1 < 0:
                    print("Error: Square root of negative number")
                else:
                    result = math.sqrt(num1)
                    print(f"Result: √{num1} = {result}")
            else:
                print("Invalid operation selected")

            # Ask if user wants to continue
            another = input("Do you want to perform another calculation? (yes/no): ")
            if another.lower() != 'yes':
                break

        except ValueError:
            print("Invalid input. Please enter numbers only.")

# Run the calculator
calculator()

Example Usage

Let's walk through an example of using our calculator to find the square root of a number.

Step 1: Run the Program

Execute the Python script in your terminal or IDE.

Step 2: Select Square Root Operation

When prompted, enter '5' to select the square root operation.

Step 3: Enter the Number

Input the number you want to find the square root of (e.g., 25).

Step 4: View the Result

The calculator will display the square root of your number (e.g., √25 = 5.0).

FAQ

Can I use this calculator for complex numbers?
No, this calculator only handles real numbers. For complex numbers, you would need to use Python's cmath module.
What happens if I enter a negative number for square root?
The calculator will display an error message since the square root of a negative number is not a real number.
Can I modify this calculator to add more operations?
Yes, you can easily extend this calculator by adding more conditions to the if-elif structure in the calculator function.
Is there a way to make this calculator graphical?
Yes, you could use libraries like Tkinter or PyQt to create a graphical user interface for your calculator.
How can I improve the error handling in this calculator?
You could add more specific error messages and validation for user inputs to make the calculator more robust.