Skip to content

Commit 0640d57

Browse files
Merge pull request #58 from jyotish6699/fix/improve-calculator-input-flow
fix(calculator): retry invalid operands and prevent division/modulus by zero
2 parents 5b543b3 + 9d86a46 commit 0640d57

1 file changed

Lines changed: 42 additions & 35 deletions

File tree

math/Simple-Calculator/Simple-Calculator.py

Lines changed: 42 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -20,42 +20,49 @@
2020
break
2121

2222
if choice in ['1', '2', '3', '4', '5', '6']:
23-
try:
24-
num1 = float(input("\n📥 Enter first number: "))
25-
num2 = float(input("📥 Enter second number: "))
26-
27-
if choice == '1':
28-
result = num1 + num2
29-
print(f"\n✨ Result: {num1} + {num2} = {result}\n")
30-
31-
elif choice == '2':
32-
result = num1 - num2
33-
print(f"\n✨ Result: {num1} - {num2} = {result}\n")
34-
35-
elif choice == '3':
36-
result = num1 * num2
37-
print(f"\n✨ Result: {num1} × {num2} = {result}\n")
38-
39-
elif choice == '4':
40-
if num2 == 0:
41-
print("\n❌ Error! Division by zero is not allowed.\n")
42-
else:
43-
result = num1 / num2
44-
print(f"\n✨ Result: {num1} ÷ {num2} = {result}\n")
45-
46-
elif choice == '5':
47-
if num2 == 0:
48-
print("\n❌ Error! Modulus by zero is not allowed.\n")
49-
else:
50-
result = num1 % num2
51-
print(f"\n✨ Result: {num1} % {num2} = {result}\n")
23+
while True:
24+
try:
25+
num1 = float(input("\n📥 Enter first number: "))
26+
27+
num2 = float(input("📥 Enter second number: "))
28+
29+
if choice == '1':
30+
result = num1 + num2
31+
print(f"\n✨ Result: {num1} + {num2} = {result}\n")
32+
33+
elif choice == '2':
34+
result = num1 - num2
35+
print(f"\n✨ Result: {num1} - {num2} = {result}\n")
36+
37+
elif choice == '3':
38+
result = num1 * num2
39+
print(f"\n✨ Result: {num1} × {num2} = {result}\n")
40+
41+
elif choice == '4':
42+
if num2 == 0:
43+
print("\n❌ Error! Division by zero is not allowed.\n")
44+
continue
45+
else:
46+
result = num1 / num2
47+
print(f"\n✨ Result: {num1} ÷ {num2} = {result}\n")
48+
49+
elif choice == '5':
50+
if num2 == 0:
51+
print("\n❌ Error! Modulus by zero is not allowed.\n")
52+
continue
53+
else:
54+
result = num1 % num2
55+
print(f"\n✨ Result: {num1} % {num2} = {result}\n")
56+
57+
elif choice == '6':
58+
result = num1 ** num2
59+
print(f"\n✨ Result: {num1} ^ {num2} = {result}\n")
5260

53-
elif choice == '6':
54-
result = num1 ** num2
55-
print(f"\n✨ Result: {num1} ^ {num2} = {result}\n")
56-
57-
except ValueError:
58-
print("\n❌ Invalid input! Please enter valid numbers.\n")
61+
except ValueError:
62+
print("\n❌ Invalid input! Please enter valid numbers.\n")
63+
continue
64+
65+
break
5966

6067
else:
6168
print("\n❌ Invalid choice! Please select 1-7.\n")

0 commit comments

Comments
 (0)