Repository navigation
Expand file tree
/
Copy pathCalculator.py
More file actions
57 lines (52 loc) · 1.73 KB
/
Copy pathCalculator.py
File metadata and controls
57 lines (52 loc) · 1.73 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
def Validity():
while True:
try:
n1 = float(input("Enter number : "))
n2 = float(input("Enter another number : "))
except ValueError:
print("Invalid input. Please enter number(s)")
else:
break
return n1, n2
while True:
n1, n2 = Validity()
operator = input("Enter operation (+, -, *, /, %) : ")
# Keep asking for valid operator
valid_operator = ['+', '-', '*', '/', '%']
while operator not in valid_operator:
print("Invalid operation. Please enter one of +, -, *, /, %.")
operator = input("Enter operation again: ")
# Perform the operation
if operator == '+':
result = n1 + n2
elif operator == '-':
result = n1 - n2
elif operator == '*':
result = n1 * n2
elif operator == '/':
if n2 != 0:
result = n1 / n2
else:
result = "INFINITY!"
elif operator == '%':
if n2 != 0:
result = n1 % n2
else:
result = "Cannot perform modulo by zero!"
else:
result = "Invalid operation. Please enter one of +, -, *, /, or %."
print("Your result is :", result)
# Ask if the user wants to calculate again
while True:
again = input("Do you want to calculate? (yes/no) : ").strip().lower()
if again == 'yes':
break
elif again not in ['yes', 'no']:
print("Invalid input. Please enter 'yes' or 'no'.")
elif again == 'no':
print("Thanks for calculating :)")
exit()
'''
This code is a basic calculator that performs addition, subtraction, multiplication, division based on user input.
It handles division by zero and invalid operations gracefully.
'''