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