Matt D
Matt D

Reputation: 81

Function with if statements returns none?

I have a function I'm writing that divides two numbers. I'm to add error messages if the user attempts 0/0 or x/0 where x is any number. Entering nonzero input yields the correct answer, but if the denominator is 0, the function prints the correct statement, followed by NONE.

Any explanations? Here's my code:

def divide():
    num1, num2 = prompt()
    if num1 == 0 and num2 == 0:
        print "Dividing zero by zero is undefined."
    elif num1 != 0 and num2 == 0:
        print "Cannot divide by zero."
    else:
        return float(num1) / num2

I've seen people have this issue when printing variables, and using return solved their issue, but here I am printing a string so I don't want to use return, right?

Upvotes: 0

Views: 10755

Answers (2)

albert
albert

Reputation: 8593

I just want to give you a short overview about how to improve your code by using Python's built-in exceptions.

There are several built-in exceptions which will be raised automatically when doing faulty operations. So there is ZeroDivisionError which is raised when dividing by zero. You can catch any of these exceptions by using try-except-blocks.

I am using those built-in exceptions in order to tell the user if his input was invalid or if he decided to divide by zero.

For doing this I rewrote your code as shown below:

def prompt():
    num1 = input('Please input a number: ')
    try:
        num1 = float(num1)
    except Exception as e:
        print('Your input is invalid. Starting at first input again.')
        return prompt()

    num2 = input('Please input another number: ')
    try:
        num2 = float(num2)
    except Exception as e:
        print('Your input is invalid. Starting at first input again.')
        return prompt()

    return num1, num2 


def divide():
    num1, num2 = prompt()
    result = None
    msg = None
    try:
        result = num1 / num2
    except ZeroDivisionError as e:
        msg = str(e)
        result = None
    return msg, result

msg, result = divide()

if result:
    print('The result of you calculation is: {}'.format(result))
else:
    print('The following error occured: {}'.format(msg))

You can still do some further improvements or shorten my code, for sure. However, I decided to keep this code in this state since I do not want to confuse you too much at this point.

Upvotes: 1

Tony Babarino
Tony Babarino

Reputation: 3405

Functions in Python return None if there is no return statement and you only return in the else branch of your program.

Consider throwing an exception instead of using print. You can find more information here, including an example of division by zero: https://docs.python.org/2/tutorial/errors.html

Upvotes: 1

Related Questions