python return - “名称未定义" [英] python return - "name not defined"

查看:20
本文介绍了python return - “名称未定义"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to get this script to write information into a basic text file. I'm still learning python.

问题出在这里:

file_text = """%s SHOOT DETAILS

Number of shoots:	 %s
Maximum range:	 %s
Number of firers:	 %s
Number of lanes active:	 %s
Number of details:	 %s
Troops per detail:	 %s

 
RANGE STAFF
Ammo NCO:	 %s
Medical Supervisor:	 %s
IC Butts:	 %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' 未定义

The error message: NameError: name 'number_of_details' is not defined

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

The above is (supposedly) written into a file with this:

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

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

However I did define it earlier in the following function:

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

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

Identical problems occur for the size_of_details, defined:

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

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

And also with the range staff chooser function, sometimes it gives me a similar error. They come from this function that randomly selects them from a list:

def range_staff():
    print "
"
    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识别?

It seems like I'm missing something fundamental here. How can I get python to recognise?

推荐答案

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

The variables only exist in the scope you declare them

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值,那么调用这个函数并将它赋值给这样一个变量

If you want to use the return value from a function, then call the function and assign it to such a variable

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

这篇关于python return - “名称未定义"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆