<p>不用担心:)欢迎来到Python!它抛出这个错误是因为它正在寻找一个不存在的全局变量——而它不存在的原因是因为您没有达到<code>if type == "accounts"</code>条件!</p>
<p>试试这个:</p>
<pre><code>for i in included:
global signs,accounts, regions
global sign_name, acc_name, rg_name
regions = "no region yet"
acc_name = "no acc_name yet"
if type == "regions"
regions = i
rg_name = regions['data']['region']
if type == "accounts"
accounts = i
acc_name = accounts['data']['account']
print("Stopping account " + acc_name + " in region " + rg_name)
</code></pre>
<p>这将清除错误,至少让您看到可能出现的其他错误:)</p>
<p>我还将指出,我相信您会从其他人那里听到,您没有理由在这个上下文中声明全局变量。它最初的意思是“找不到全局变量”,因为在您输入<code>global</code>关键字之前,它没有触发<code>if</code>语句,因此它首先检查<code>locals()</code>变量,没有找到它,搜索<code>globals()</code>变量,没有发现它被踢出并出错。</p>
<p>您可以删除<code>global</code>变量,它的工作原理如下:</p>
<pre><code>for i in included:
regions = "no region yet"
acc_name = "no acc_name yet"
if type == "regions"
regions = i
rg_name = regions['data']['region']
if type == "accounts"
accounts = i
acc_name = accounts['data']['account']
print("Stopping account " + acc_name + " in region " + rg_name)
</code></pre>
<p>另一个简短的提示,永远不要将<code>type</code>作为变量。。。改用<code>type_</code>。原因是<code>type</code>是一个<code>builtin</code>Python函数,如果使用<code>type</code>作为变量,则会意外地给该内置名称起别名。</p>
<p>最后,再把剧本整理一下:</p>
<pre><code># only use "i" when you're using numbers, otherwise just call it
# the name of the data you're using :)
for account_data in included:
regions = "no region yet"
acc_name = "no acc_name yet"
if type_ == "regions"
rg_name = account_data['data']['region']
if type_ == "accounts"
acc_name = account_data['data']['account']
# here's an example of Pythonic string formatting :)
print("Stopping account {} in region {}".format(acc_name, rg_name))
</code></pre>