【问题标题】:python return - "name not defined"python return - “名称未定义”
【发布时间】:2016-05-16 12:37:29
【问题描述】:

我正在尝试让此脚本将信息写入基本文本文件。我还在学习python。

问题出在这里:

file_text = """%s SHOOT DETAILS\n
Number of shoots:\t %s
Maximum range:\t %s
Number of firers:\t %s
Number of lanes active:\t %s
Number of details:\t %s
Troops per detail:\t %s
\n 
RANGE STAFF
Ammo NCO:\t %s
Medical Supervisor:\t %s
IC Butts:\t %s""" % (shoot_name, number_of_shoots, max_range, number_of_firers, number_of_lanes, number_of_details, size_of_details, ammo_nco, medical_supervisor, ic_butts)

错误信息: NameError: name 'number_of_details' 未定义

上面的内容(据说)是这样写到一个文件中的:

def generatedocument():
    file = open(file_name, 'w')
    file.write(file_text)
    os.startfile(file_name)

但是我之前确实在以下函数中定义了它:

def detailformation():
    number_of_details = number_of_firers / number_of_lanes
    return number_of_details

定义的 size_of_details 出现相同的问题:

def detailsizer():
    size_of_details = number_of_firers / detailformation()
    return size_of_details

还有范围工作人员选择器功能,有时它会给我一个类似的错误。它们来自这个从列表中随机选择它们的函数:

def range_staff():
    print "\n"
    ammo_nco = (random.choice(fiveplatoon))
    print "Ammo NCO: "+ammo_nco
    fiveplatoon.remove(ammo_nco)
    medical_supervisor = (random.choice(fiveplatoon))
    print "Medical supervisor: "+medical_supervisor
    fiveplatoon.remove(medical_supervisor)
    ic_butts = (random.choice(fiveplatoon))
    print "IC Butts/Console: "+ic_butts
    fiveplatoon.remove(ic_butts)
    return range_staff

似乎我在这里遗漏了一些基本的东西。如何让python识别?

【问题讨论】:

  • 你需要真正调用你的函数...

标签: python function variables return


【解决方案1】:

变量只存在于你声明的范围内

def fun():
    x = 5
    return x

>>> x
Traceback (most recent call last):
  File "<pyshell#4>", line 1, in <module>
    x
NameError: name 'x' is not defined

如果您想使用函数中的return 值,则调用该函数并将其分配给这样的变量

>>> x = fun()
>>> x
5

【讨论】:

  • 正确。如果您想使用多个返回值,只需用逗号分隔它们。
【解决方案2】:

这看起来像是 范围 问题。在函数内声明的变量仅在该函数内定义。要修复它,请将变量的声明放在与使用它的位置相同的 范围 上。示例代码见下文

number_of_details = 0

def detailformation():
    number_of_details = number_of_firers / number_of_lanes
    return number_of_details

file_text = """%s SHOOT DETAILS\n
Number of shoots:\t %s
Maximum range:\t %s
Number of firers:\t %s
Number of lanes active:\t %s
Number of details:\t %s
Troops per detail:\t %s
\n 
RANGE STAFF
Ammo NCO:\t %s
Medical Supervisor:\t %s
IC Butts:\t %s""" % (shoot_name, number_of_shoots, max_range, number_of_firers, number_of_lanes, number_of_details, size_of_details, ammo_nco, medical_supervisor, ic_butts)

请注意,这只是一个快速的解决方案(将变量放在全局范围内)。

【讨论】:

    【解决方案3】:

    调用你的函数以获得它们返回的值

    size_of_details = detailsizer() 
    

    【讨论】:

      猜你喜欢
      • 2021-10-18
      • 2013-01-26
      • 2021-03-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-01
      • 2014-03-23
      相关资源
      最近更新 更多