1
+ # Define a function to add two numbers
1
2
def add(x, y):
2
3
"""Function to add two numbers"""
3
4
return x + y
4
5
6
+ # Define a function to subtract two numbers
5
7
def subtract(x, y):
6
8
"""Function to subtract two numbers"""
7
9
return x - y
8
10
11
+ # Define a function to multiply two numbers
9
12
def multiply(x, y):
10
13
"""Function to multiply two numbers"""
11
14
return x * y
12
15
16
+ # Define a function to divide two numbers
13
17
def divide(x, y):
14
18
"""Function to divide two numbers"""
19
+ # Check if the second number is not zero to avoid division by zero error
15
20
if y != 0:
16
21
return x / y
17
22
else:
23
+ # Return an error message if the second number is zero
18
24
return "Error: Cannot divide by zero"
19
25
26
+ # Define the main function that serves as the entry point of the program
20
27
def main():
28
+ # Display the title of the program
21
29
print("Simple Calculator")
30
+ # Display the available mathematical operations
22
31
print("Available operations:")
23
32
print("1. Add")
24
33
print("2. Subtract")
25
34
print("3. Multiply")
26
35
print("4. Divide")
27
36
37
+ # Prompt the user to select an operation
28
38
choice = input("Enter your choice (1/2/3/4): ")
29
39
40
+ # Prompt the user to enter the first number
30
41
num1 = float(input("Enter the first number: "))
42
+ # Prompt the user to enter the second number
31
43
num2 = float(input("Enter the second number: "))
32
44
45
+ # Perform the selected operation and display the result
33
46
if choice == '1':
34
47
print(f"Result: {num1} + {num2} = {add(num1, num2)}")
35
48
elif choice == '2':
@@ -39,7 +52,10 @@ def main():
39
52
elif choice == '4':
40
53
print(f"Result: {num1} / {num2} = {divide(num1, num2)}")
41
54
else:
55
+ # Inform the user if an invalid choice was made
42
56
print("Invalid choice. Please select a valid operation (1/2/3/4).")
43
57
58
+ # Check if the script is being run directly and not imported
44
59
if __name__ == "__main__":
60
+ # If the script is run directly, call the main function to start the calculator
45
61
main()
0 commit comments