python - 当我在函数中定义变量名时,为什么会出现 NameError?
问题描述
我正在尝试基于输入语句和我定义的函数构建 if/elif/else 语句。当我运行代码时,输入语句和函数定义和调用运行良好,但随后我进入我的 if/elif/else 语句并得到一个 NameError,告诉我我在 if/elif/ 中调用了一个变量else 语句未定义(即使我认为我在函数中定义了它)。
对于上下文,我是 Python 新手,我正在 Atom 中构建代码并在命令提示符中运行它。
我的输入、函数定义和 if 语句代码如下所示:
h, m, s, t = input('Rate each of the following Emotions and hit enter:\nHappiness (1-7):'), input('Meaningfulness (1-7):'), input('Stressfulness (1-7):'), input('Tiredness (1-7):')
h_int=int(h)
m_int=int(m)
s_int=int(s)
t_int=int(t)
def na():
add_h_m = h_int + m_int
div_h_m = add_h_m/2
add_s_t = s_int + t_int
div_s_t = add_s_t/2
net_affect = div_h_m - div_s_t
print(net_affect)
na()
if net_affect >= 3:
print("Doing Well")
elif net_affect <3 and net_affect >0:
print("Doing Okay")
else:
print("Not Good")
这是命令提示符输出:
C:\Users\mrkev\Desktop\PAI 724>python ex2.py
Rate each of the following Emotions and hit enter:
Happiness (1-7):6
Meaningfulness (1-7):7
Stressfulness (1-7):4
Tiredness (1-7):3
3.0
Traceback (most recent call last):
File "C:\Users\mrkev\Desktop\PAI 724\ex2.py", line 16, in <module>
if net_affect >= 3:
NameError: name 'net_affect' is not defined
我哪里错了?我认为通过在函数中定义 net_affect,我可以在我的程序中将它用作变量。
感谢您的帮助!
解决方案
在您的文档或教程中查找“变量范围”。
该net_affect
变量是局部na
函数。您无法从外部访问它,并且在函数返回时将其删除。
您也可以:
在函数外部定义变量,并表明你在函数中使用它
net_affect = None def na(): ... global net_affect net_affect = div_h_m - div_s_t
从函数返回值并捕获返回值
def na(): ... net_affect = div_h_m - div_s_t ... return net_affect # return the value ... net_affect_new = na() # catch the value
注意:
net_affect_new
可以调用net_affect
但它们不是相同的变量,它们在两个不同的范围内。
推荐阅读
- wordpress - 使用购买的产品的术语 ID 更新 ACF 字段 - WooCommerce
- python - 如何在多个进程之间共享全局列表变量?
- android - Android 和 Xamarin.Android 中的常见动画静态类不会停止动画
- java - 尽管清除它,实体中的列表对象仍返回到以前的状态
- autodesk-forge - 对 Forge/BIM360 Docs 文件列表进行排序的最佳方法是什么?
- r - r - 将数据帧拆分为多个数据帧并保存在环境中
- node.js - 无法在节点 js 的控制器中获取表单发布数据
- unity3d - 在玩家不动时在玩家身后绘制轨迹
- c# - C# MSChart 添加悬停线
- javascript - 单击扩展图标时,在新选项卡中打开扩展的 options.html 页面