Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 11 additions & 4 deletions Basic calculator
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
#Donald's Basic calculator
#this function adds two numbers
def add(x,y):
return x + y
Expand All @@ -19,6 +18,10 @@ def divide(x,y):
def modulus(x,y):
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There is no check for zero division error in both divide and modulus function so the code will fail when user tries to divide 1 by 0.

better approach would be.

def divide(x,y):
try:
return x / y
except ZeroDivisionError as e:
return e

return x % y

#this function gives the exponent of two numbers
def exponent(x, y):
return x ** y


print('''Welcome!
Simple calculator
Expand All @@ -28,13 +31,14 @@ print('2.subtract')
print('3.multiply')
print('4.divide')
print('5.modulus')
print('6.exponent')

while True:
#take input from the user
choice = input('Enter choice(1/2/3/4/5):')
choice = input('Enter choice(1/2/3/4/5/6):')

#check if the choice is one of the five options
if choice in ('1','2','3','4','5'):
#check if the choice is one of the six options
if choice in ('1','2','3','4','5','6'):
try:
num1 = float(input('Enter first number:'))
num2 = float(input('Enter second number'))
Expand All @@ -57,6 +61,9 @@ while True:
elif choice == '5':
print (num1, '+', num2, '=', modulus(num1, num2))

elif choice == '6':
print (num1, '+', num2, '=', exponent(num1, num2))


#check if user wants another calculation
# break the while loop if the answer is no
Expand Down