Below Simple Calculator program in Python is a command-line application that allows the user to perform basic mathematical operations. The program starts by defining four functions: add, subtract, multiply, and divide. Each function takes two arguments, x and y, and performs the corresponding mathematical operation on them. The return value of each function is the result of the operation.
Next, the program prints out a menu of options for the user to select from. The user is prompted to enter a choice, which should be a number from 1 to 4. The program then gets two numbers from the user and assigns them to the variables num1 and num2.
After that, the program uses an if-elif block to check the value of the choice variable. Based on the value entered by the user, the program performs the corresponding operation by calling the appropriate function. The result of the operation is then printed out to the console.
If the user enters an invalid choice, the program will print out “Invalid Input”.
This program allows the user to perform basic mathematical operations using a simple and easy-to-use command-line interface. The code is easy to understand, and it is well-organized, making it easy to add new functionality or modify existing functionality. This program is a good starting point for creating a more advanced calculator application with additional functionality like trigonometric functions, logarithmic functions, square root, etc.
Here is a simple calculator program in Python:
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):
return x / y
print("Select operation.")
print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")
choice = input("Enter choice(1/2/3/4): ")
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
if choice == '1':
print(num1, "+", num2, "=", add(num1, num2))
elif choice == '2':
print(num1, "-", num2, "=", subtract(num1, num2))
elif choice == '3':
print(num1, "*", num2, "=", multiply(num1, num2))
elif choice == '4':
print(num1, "/", num2, "=", divide(num1, num2))
else:
print("Invalid Input")
This program defines four functions for basic mathematical operations: add, subtract, multiply, and divide. It then prompts the user to select an operation by entering a number from 1 to 4. The program then gets two numbers from the user and performs the selected operation using the appropriate function. The result is then printed out to the console.
In this example, the calculator project is simple, but you can add more functionality to it like trigonometric function, logarithmic function, square root, etc. Also, you can include exception handling to handle cases like dividing by zero.
You can also make this program more interactive by creating a GUI using libraries like Tkinter or PyQt. This would make the calculator more user-friendly and visually appealing.
Leave a Reply