Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Christopher Mlalazi
Front End Web Development Techdegree Graduate 17,305 PointsCheck if value is not zero in a calculator
Hi guys. Does anyone know how I can check if number value entered in the divide section(number 4) is not zero, and if it is zero terminate the operation and prompt for another number greater than zero? This is an assignment in my CS course and I hope I have explained it well. Here is my code so far:
calculating = True
while calculating:
print("1 = Add")
print("2 = Subtract")
print("3 = Multiply")
print("4 = Divide")
prompt = int(input("Enter Number: "))
if prompt == 1:
a =int(input("Enter the value of a: "))
b = int(input("Enter the value of b: "))
c = a + b
print ('Answer is: ', c)
elif prompt == 2:
a = int(input("Enter the value of a: "))
b = int(input("Enter the value of b: "))
c = a - b
print ('Answer is: ', c)
elif prompt == 3:
a =int(input("Enter the value of a: "))
b = int(input("Enter the value of b: "))
c = a * b
print ('Answer is: ', c)
elif prompt == 4:
a =int(input("Enter the value of a: "))
b = int(input("Enter the value of b: "))
c = a / b
print ('Answer is: ', c)
else:
print("Exit")
calculating = False
3 Answers
Steven Parker
243,657 PointsPerhaps your course has not covered loops yet. But you could do something like this:
b = int(input("Enter the value of b: ")) # existing line
while b == 0:
b = int(input("We can't divide by 0! Enter another value for b: "))
Christopher Mlalazi
Front End Web Development Techdegree Graduate 17,305 Pointswill try ``` while b || a == 0: (what do you think?)
Steven Parker
243,657 PointsYou can only combine complete comparisons, and you don't need to worry about the value of a.
Christopher Mlalazi
Front End Web Development Techdegree Graduate 17,305 PointsBut what is ‘a’ holds the value 0(zero)?
Steven Parker
243,657 PointsThen you get a zero result .. but not an error.
Christopher Mlalazi
Front End Web Development Techdegree Graduate 17,305 PointsChristopher Mlalazi
Front End Web Development Techdegree Graduate 17,305 PointsHey Steven I have done loops in JavaScript and Java, but I was not sure how to execute it here in Python. Let me work on it and see if it works thanks will be back later.