我正在代码学院学习python,我正在努力完成他们的复习作业。我应该定义一个函数,然后设置一个if/else循环来检查我得到的输入类型,然后返回int/foat的绝对值或错误消息。
我试着看类似的问题,但我不明白这些代码比我能理解的O_O要复杂得多。我又看了一遍函数模块的课程,但我认为我正确地遵循了函数制作模式?在我调用函数之前,应该有额外的一行吗?我试着继续,但在其他练习中我也收到了同样的错误信息。
如果有任何回复,我将不胜感激:)
def distance_from_zero(thing):
thing = input
if type(thing) != int or float:
return "Not an integer or float!"
else:
return abs(thing)
distance_from_zero(thing)
您是否试图使用输入函数从用户那里获取值?如果是,您必须在其中添加括号:
thing = input()
# If you're using python 2.X, you should use raw_input instead:
# thing = raw_input()
此外,如果你正试图这样做,你就不需要输入参数
如果您的意思是input
是一个参数,那么在定义变量之前,您将尝试使用变量。distance_from_zero(thing)
不能工作,因为thing
没有在函数之外定义,所以应该先定义该变量,或者用一个小值调用它:
thing = 42
distance_from_zero(thing)
# or
distance_from_zero(42)
thing
在传递给distance_from_zero函数时没有定义?
def distance_from_zero(input):
if type(input) != int or float:
return "Not an integer or float!"
else:
return abs(input)
thing = 5
distance_from_zero(thing)
您没有定义thing
。请尝试
def distance_from_zero(thing):
if type(thing) != int or float:
return "Not an integer or float!"
else:
return abs(thing)
thing = 1
distance_from_zero(thing)
或者你的意思是,接受用户输入?
def distance_from_zero():
thing = int(input())
if type(thing) != int or float:
return "Not an integer or float!"
else:
return abs(thing)
distance_from_zero()
您的代码if type(thing) != int or float:
将始终转到True
,因为它是if (type(thing) != int) or float
。将其更改为if not isinstance(thing, (int, float)):
。