Search code examples
pythonexceptionnonetypedivide-by-zeronested-function

How to handle None value in nested functions and exception


updated to

My goal is that

  1. to get q = getQuotient() line is called only when both x and y are not None
  2. to get calc1() stop running and go back to main to run b.calc2() AFTER getting the ZeroDivisionError.
  3. to get b.calc2() line gets executed whether b.calc1() got caught in the ZeroDivisionException or not when x and y can be None as well as numbers including 0.

I added my questions in comments below.

My goal is that

  1. to get q = getQuotient() line is called if only x and y are not None
  2. to get b.calc2() line gets executed whether b.calc1() got caught in the ZeroDivisionException or not when x and y can be None as well as numbers including 0.

a.py

import b
if __name__ == "__main__":
    b.calc1()
    print("Done with 1")
    b.calc2()
    print("Done with 2")

b.py

def calc1():
    x = getX()
    y = getY()
    if not x or not y:
        return

    q = getQuotient(x, y)
    if q:
        print(q)
    # does more stuff here
    # and I would like this calc1() to stop here, stop running if getQuotient() gets the ZeroDivisionError.

def getQuotient(x, y):
    try:
        return x/y
    except ZeroDivisionError:
        print("zero division error happened.")
    # what can, should I do here? 
    # I would like calc1() to stop running and go back to main if it gets ZeroDivisionError.
    # How's "return None" since "if quotient" line will stop processing any further if y is zero?
    # if I raise, it terminates the program, which means b.calc2() won't run. I need it to run, though.

# ...

Solution

  • a.py

    import b
    if __name__ == "__main__":
        b.calc1()
        print("Done with 1")
        b.calc2()
        print("Done with 2")
    

    b.py

        def calc1():
        x = getX()
        y = getY()
        if not x or not y:
            return
    
        q = getQuotient(x, y)
        if not q:
            return
        else:
            # The other lines 
            # of code to run if it
            # is not 'None'
       
    def getQuotient(x, y):
        try:
            return x/y
        except ZeroDivisionError:
            print("zero division error happened.")
    
    P.S using 'return None' will also do in your version of b.py but it will return None automatically in case of exception.