Skip to content

Commit c7864b8

Browse files
ManOfDiamondtechyminati
authored andcommitted
Add a simple calculator
1 parent 1f97166 commit c7864b8

1 file changed

Lines changed: 62 additions & 0 deletions

File tree

‎calculator.py‎

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
# This function adds two numbers
2+
def add(x, y):
3+
return x + y
4+
5+
# This function subtracts two numbers
6+
def subtract(x, y):
7+
return x - y
8+
9+
# This function multiplies two numbers
10+
def multiply(x, y):
11+
return x * y
12+
13+
# This function divides two numbers
14+
def divide(x, y):
15+
return x / y
16+
17+
18+
print("What do you want to do?")
19+
print("1.Add")
20+
print("2.Subtract")
21+
print("3.Multiply")
22+
print("4.Divide")
23+
24+
while True:
25+
# take input from the user
26+
choice = input("Enter choice(1/2/3/4): ")
27+
28+
# check if choice is one of the four options
29+
if choice in ('1', '2', '3', '4'):
30+
num1 = float(input("Enter first number: "))
31+
num2 = float(input("Enter second number: "))
32+
33+
if choice == '1':
34+
print(num1, "added to", num2)
35+
print("Sum:", add(num1, num2))
36+
37+
elif choice == '2':
38+
print(num2, "subtracted from", num1)
39+
print("Difference:", subtract(num1, num2))
40+
41+
elif choice == '3':
42+
print(num1, "multiplied", num2)
43+
print("Product:", multiply(num1, num2))
44+
45+
elif choice == '4':
46+
print(num1, "divided by", num2)
47+
print("Result:", divide(num1, num2))
48+
49+
else:
50+
print("Invalid input, retrying") #if the value isn't one of the four options
51+
continue
52+
# check if user wants another calculation
53+
while True:
54+
another = input("Another calculation?(y/N)")
55+
if another == 'y':
56+
break
57+
elif another == 'n':
58+
print("Thank you!")
59+
exit()
60+
else:
61+
print("Thank you!")
62+
exit()

0 commit comments

Comments
 (0)