Search code examples
pythonpython-2.7pythagorean

Stop python from going to the very last statement


I am currently writing a program that will solve the pythagorean theorem. However, I have a bug in the program. Whenever I put in a negative number for length a or b, it prints out "A cannot be less than zero" but goes ahead and solves for C anyway and prints out the length of C even though the user hasn't input b yet. How can I make it so when the user inputs a negative number it prints out the statement "A cannot be less than zero" and then loops again to inputting a length for the side, instead of how it is now where after it prints out the statement it redirects to the end?

Here is my code:

 import math
    print"This program will solve the pythagorean theorem for you"
    unit=raw_input('Enter the unit you will be using')
    a=float(raw_input('Enter the length of side a'))
    if a<=0:
      print"A cannot be less than zero"
    else:
        b=float(raw_input('Enter the length of side b'))
    if b<=0:
      print"B cannot be less than zero"
    else:
        c2=(a**2)+(b**2)
        c=math.sqrt(c2)
        c=str(c)
        print "The length of side C is: "+ c + " " + unit + "."

Solution

  • Well to begin with, if you want to constantly check your inputs, you are going to have to use a loop. As in, the psuedocode for the algorithm should be:

    Loop Begin
    Check the value of a and b
    If a or b is less than 0 then ask for input again
    Otherwise, continue
    

    Please note, that the algorithm has to run at least once.

    That is basically how the psuedocode should look like. So, this is a case where you can use a do-while loop construct. In Python, there isn't something like this, so we emulate it:

    import math
    
    
    def take_in():
        a = raw_input("Enter the value of side a -> ")
        b = raw_input("Enter the value of side b -> ")
    
        # Trying to convert to a float
        try:
            a, b = float(a), float(b)
            # If successfully converted, then we return
            if a > 0 and b > 0:
                return a, b
        except ValueError:
            pass
        # If we cannot return, then we return false, with a nice comment
    
        print "Invalid input"
        return False
    
    
    def main():
        # Calling the function at least once
        valid = take_in()
    
        # While we are not getting valid input, we keep calling the function
        while not valid:
            # Assigning the value to valid
            valid = take_in()
    
        # Breaking the return tuple into a and b
        a, b = valid
        print math.sqrt(a ** 2 + b ** 2)
    
    
    if __name__ == '__main__':
        main()