Sure, I can help you with that!
Let's start with JavaScript:
JavaScript Calculator:
First, let's create a simple HTML file that will display our calculator:
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Calculator</title>
</head>
<body>
<div>
<input type="text" id="result" disabled>
</div>
<div>
<button onclick="calculate('1')">1</button>
<button onclick="calculate('2')">2</button>
<button onclick="calculate('3')">3</button>
<button onclick="calculate('+')">+</button>
</div>
<div>
<button onclick="calculate('4')">4</button>
<button onclick="calculate('5')">5</button>
<button onclick="calculate('6')">6</button>
<button onclick="calculate('-')">-</button>
</div>
<div>
<button onclick="calculate('7')">7</button>
<button onclick="calculate('8')">8</button>
<button onclick="calculate('9')">9</button>
<button onclick="calculate('*')">*</button>
</div>
<div>
<button onclick="calculate('0')">0</button>
<button onclick="calculate('.')">.</button>
<button onclick="calculate('/')">/</button>
<button onclick="calculate('=')">=</button>
</div>
<div>
<button onclick="clearResult()">Clear</button>
</div>
<script src="calculator.js"></script>
</body>
</html>
Next, let's create a JavaScript file named calculator.js that will handle the calculation:
let result = document.getElementById("result");
function calculate(value) {
if (value === '=') {
result.value = eval(result.value);
} else {
result.value += value;
}
}
function clearResult() {
result.value = '';
}
In this code, we first declare a variable named result that will hold the input field where our calculation will be displayed. We then define two functions: calculate() and clearResult(). The calculate() function checks if the value passed as an argument is the equal sign (=) or not. If it's the equal sign, we evaluate the calculation using the eval() function and display the result in the input field. If it's not the equal sign, we simply append the value to the input field. The clearResult() function clears the input field.
Python Calculator:
Now, let's create a Python program that will do the same thing:
def calculate():
operation = input("Enter the operation (+, -, *, /): ")
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
if operation == '+':
print(num1 + num2)
elif operation == '-':
print(num1 - num2)
elif operation == '*':
print(num1 * num2)
elif operation == '/':
print(num1 / num2)
else:
print("Invalid operation")
calculate()
In this code, we define a function named calculate() that asks the user for an operation (+, -, *, /), the first number, and the second number. We then perform the calculation based on the operation entered using if-else statements and display the result using the print() function.
Both of these solutions offer basic functionality and can be extended as needed. I hope this helps!