Sai Prasad Gudari
Sai Prasad Gudari

Reputation: 17

How to prevent TypeError: unsupported operand type(s) for +: 'NoneType' and 'float'

How can I prevent this TypeError from occurring raised by the add function?

#TypeError: unsupported operand type(s) for +: 'NoneType' and 'float'


def number_1(prompt1):
    while True:
        x = input(prompt1)
        try:
            float(x)
            break
        except ValueError:
            print("\"{0}\" is not a number\nEnter again".format(x))


def number_2(prompt2):
    while True:
        y = input(prompt2)
        try:
            float(y)
            return float(y)
            break
        except ValueError:
            print("\"{0}\" is not a number\nEnter again".format(y))

def add(p,q):
    return p + q

num1 = number_1("Enter num1: ")
num2 = number_2("Enter num2: ")

print(add(num1,num2))  # TypError raised here

Upvotes: 0

Views: 341

Answers (1)

albjerto
albjerto

Reputation: 571

In the function number_1 you forgot to return the value.

On a side note, why are you using two different functions that do the same thing? I cleaned up a bit and added comments for clarification.

def input_number(prompt):
    while True:
        x = input(prompt)
        try:
            # You don't need to cast to float twice. Just do it in the return statement. 
            # If there's something wrong, the exception is raised before the return

            return float(x)

            # A break here is useless because return will prevent the while loop from continuing running
        except ValueError:
            print("\"{0}\" is not a number\nEnter again".format(x))

def add(p,q):
    return p + q

num1 = input_number("Enter num1: ")
num2 = input_number("Enter num2: ")

num3 = add(num1, num2)

print("Result: {}".format(num3))

Upvotes: 1

Related Questions