Python Forum

Full Version: Python calculator divide by zero help
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I'm a beginner at python and I am building a calculator for a project and have everything working as needed except one small part. I have to get a similar output The Result of 20.0/0.0=You cannot divide by Zero. I am not allowed to use try-except so I tried using if statement but I seem to be doing it wrong. My code is below I appreciate any tips or help.

loRange = int(input('Enter your Lower range: '))
hiRange = int(input('Enter your Higher range: '))
number_1 = int(input('Enter your first number: '))
number_2 = int(input('Enter your second number: '))

def add(x, y):
return x + y

def subtract(x, y):
return x - y

def multiply(x, y):
return x * y

def divide(x, y):
return x / y

if (loRange <= number_1 <= hiRange) and (loRange <= number_2 <= hiRange):
print('The Result of', number_1, '+' ,number_2, '=', add(number_1,number_2))
print('The Result of', number_1, '-' ,number_2, '=', subtract(number_1,number_2))
print('The Result of', number_1, '*' ,number_2, '=', multiply(number_1,number_2))
print('The Result of', number_1, '/' ,number_2, '=', divide(number_1,number_2))
else:
print("The input values are outside the input range")

if (number_1 == 0) or (number_2 == 0):
print('You cannot divide by Zero')

print('Thanks for using our calculator!')
I think if you put your
def divide(x, y):
    if x == 0 or y == 0:
        print('You cannot divide by Zero')
    else:
        return x / y
you might have more luck.
Thanks for the tip I'm a noob at python and this class is accelerated online.
Technically you should only be preventing a divide BY zero (a zero in the denominator). Zero divided by zero is undefined and zero divided by any other number is zero.

In your case, you should only be guarding against y == 0.
Very good point.