Python 在循环外获取变量 [英] Python Get variable outside the loop

查看:43
本文介绍了Python 在循环外获取变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 python 代码,我需要在 for 循环和 if 语句之外获取它的值并进一步使用该变量:

I have a python code ,i need to get its value outside the for loop and if statements and use the variable further:

我的代码:

with open('text','r') as f:
  for line in f.readlines():
      if 'hi' in line
         a='hello'

print a  #variable requires outside the loop

但是我得到 Nameerror: 'a' is not defined

推荐答案

该错误消息意味着您从未分配给 a(即 if 条件从未评估为 ).

The error message means you never assigned to a (i.e. the if condition never evaluated to True).

为了更优雅地处理这个问题,您应该在循环之前为 a 分配一个默认值:

To handle this more gracefully, you should assign a default value to a before the loop:

a = None
with open('test', 'r') as f:
   ...

然后您可以在循环后检查它是否为None:

You can then check if it's None after the loop:

if a is not None:
   ...

这篇关于Python 在循环外获取变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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