Build a Powerful Calculator Using Python in Just Minutes!
Build a Powerful Calculator Using Python in Just Minutes!
here are the steps to create a basic calculator using Python:
- Define functions for each arithmetic operation (addition, subtraction, multiplication, and division).
- Define a function to take user input (the two numbers and the operation they want to perform).
- Call the appropriate arithmetic function based on the user's input.
- Print the result of the calculation.
Here's an example code for a basic calculator 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")
while True:
choice = input("Enter choice(1/2/3/4): ")
if choice in ('1', '2', '3', '4'):
num1 = float(input("Enter first number: "))
num2 = float(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))
break
else:
print("Invalid Input")
In this code, the user is prompted to select an operation (addition, subtraction, multiplication, or division), and then enters the two numbers they want to perform the operation on. The appropriate function is called based on the user's choice, and the result is printed to the console.
Comments
Post a Comment