调用函数时如何修复“NameError:name'thing'未定义”?

2024-05-17 02:37:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在代码学院学习python,我正在努力完成他们的复习作业。 我应该定义一个函数,然后设置一个if/else循环来检查得到的输入类型,然后返回int/float的绝对值或错误消息。

我试着看类似的问题,但我不明白这些代码比我能理解的复杂得多。我又看了一遍功能模块的课程,但我认为我正确地遵循了功能生成模式?在我调用函数之前应该有一个额外的行吗?我试着继续练习,但在其他练习中我得到了同样的错误信息。

如有任何回复,我将不胜感激:)

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)

Tags: or函数代码fromreturnif定义作业
3条回答

您是否尝试使用输入函数从用户获取值? 如果是,则必须在其中添加括号:

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。请试试看

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

thing传递给距离为零的函数时没有定义?

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)

相关问题 更多 >