Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/360.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何防止TypeError:+;的操作数类型不受支持:';非类型';和';浮动';_Python - Fatal编程技术网

Python 如何防止TypeError:+;的操作数类型不受支持:';非类型';和';浮动';

Python 如何防止TypeError:+;的操作数类型不受支持:';非类型';和';浮动';,python,Python,如何防止add函数引发的TypeError发生 #TypeError:不支持+:“非类型”和“浮点”的操作数类型 在函数number_1中,您忘记返回值 另一方面,为什么要使用两个不同的函数来做相同的事情? 我做了一些清理,并添加了一些评论以澄清问题 def input_number(prompt): while True: x = input(prompt) try: # You don't need to cast to fl

如何防止
add
函数引发的
TypeError
发生

#TypeError:不支持+:“非类型”和“浮点”的操作数类型



在函数
number_1
中,您忘记返回值

另一方面,为什么要使用两个不同的函数来做相同的事情? 我做了一些清理,并添加了一些评论以澄清问题

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))
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))