-

Easy Python Learning: Basic calculator script in Python

By Admin | 25-Jul-2023

 Easy Python Learning: Basic calculator script in Python

To create a calculator in Python, Below is a simple script that can perform addition, subtraction, multiplication, and division:

To create a calculator in Python, Below is a simple script that can perform addition, subtraction, multiplication, and division:

def add(x, y):
    return x + y

def subtract(x, y):
    return x - y

def multiply(x, y):
    return x * y

def divide(x, y):
    if y == 0:
        return "Error: Cannot divide by zero"
    return x / y

print("Basic Calculator")
print("Select operation:")
print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")

while True:
    choice = input("Enter choice (1/2/3/4) or 'q' to quit: ")

    if choice.lower() == 'q':
        print("Exiting the calculator.")
        break

    if choice not in ['1', '2', '3', '4']:
        print("Invalid input. Please try again.")
        continue

    num1 = float(input("Enter the first number: "))
    num2 = float(input("Enter the second number: "))

    if choice == '1':
        print("Result:", add(num1, num2))
    elif choice == '2':
        print("Result:", subtract(num1, num2))
    elif choice == '3':
        print("Result:", multiply(num1, num2))
    elif choice == '4':
        print("Result:", divide(num1, num2))
    else:
        print("Invalid input. Please try again.")

Save this code in a file with a .py extension, run the script, and you'll have a basic calculator in action. It will keep asking for the user's choice until the user decides to quit by entering 'q'. The calculator handles floating-point numbers and provides a message when attempting to divide by zero.

learn python, basic calculator script in python, learning python, learning python for beginners, python for beginners,

Tags

#learn python # basic calculator script in python # learning python # learning python for beginners # python for beginners #

Comments (0)

Leave a Comment