B.Sc Computer Science with Data Analytics
Python Programming - Lab
Core Lab 5
Bharathiar University
Program 11 - Write a python program to make a simple calculator.
SOURCE CODE:
# Function to add two numbers
def add(x, y):
return x + y
# Function to subtract two numbers
def subtract(x, y):
return x - y
# Function to multiply two numbers
def multiply(x, y):
return x * y
# Function to divide two numbers
def divide(x, y):
if y == 0:
return "Error! Division by zero."
return x / y
# Main function to perform calculations based on user input
def calculator():
print("Simple Calculator")
print("Operations: +, -, *, /")
while True:
# Get user input for operation and numbers
operation = input("Enter operation (+, -, *, /) or 'exit' to quit: ")
if operation.lower() == 'exit':
break
try:
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
except ValueError:
print("Invalid input! Please enter numbers.")
continue
# Perform calculation based on the chosen operation
if operation == '+':
print("Result:", add(num1, num2))
elif operation == '-':
print("Result:", subtract(num1, num2))
elif operation == '*':
print("Result:", multiply(num1, num2))
elif operation == '/':
print("Result:", divide(num1, num2))
else:
print("Invalid operation! Please enter +, -, *, or /.")
# Call the calculator function to run the calculator program
calculator()
OUTPUT:
Simple Calculator
Operations: +, -, *, /
Enter operation (+, -, *, /) or 'exit' to quit: +
Enter first number: 2
Enter second number: 5
Result: 7.0
Enter operation (+, -, *, /) or 'exit' to quit: -
Enter first number: 10
Enter second number: 2
Result: 8.0
Enter operation (+, -, *, /) or 'exit' to quit: *
Enter first number: 2
Enter second number: 3
Result: 6.0
Enter operation (+, -, *, /) or 'exit' to quit: /
Enter first number: 10
Enter second number: 5
Result: 2.0
Enter operation (+, -, *, /) or 'exit' to quit: =
Enter first number: 2
Enter second number: 3
Invalid operation! Please enter +, -, *, or /.
Enter operation (+, -, *, /) or 'exit' to quit: exit
No comments:
Post a Comment