关于导入我错过了什么?

时间:2018-01-11 22:11:38

标签: python import

第一次问这里,我是Python的新手。我也开始使用import系统失去我的冷静。我有一个名为“moduuliharkka”的文件夹,其中包含main.py和country_data.py。 country_data只包含3个用于脚本的字典(main.py应该从那里获取数据)。我的问题是,main.py不想因某种未知原因导入country_data。

这是country_data.py:

countrycodes = ["fi","se","no"]
codemap = {
"fi":'finland', "se":'sweden', "no":'norway'
}
countries = {
'finland':{'head honcho':('Juha Sipila','54 years old'),'population':5.349},
'sweden':{'head honcho':('Stefan Lofven','58 years old'),'population':9.593},
'norway':{'head honcho':('Erna Solberg','54 years old'),'population':5.084}
}

这是main.py:

import country_data

for code in countrycodes:
    print (codemap[code], ':\n\t','Head honcho:', countries[codemap[code]]['head honcho'],'\n\t','Population:', countries[codemap[code]]['population'],'million')

我得到的错误如下:

Traceback (most recent call last):
File "E:\Kouluhommelit\Script-programming\moduuliharkka\main.py", line 3, in <module>
for code in countrycodes:
NameError: name 'countrycodes' is not defined

我现在已经挣扎了将近2个小时。当我将country_code的内容放在main.py中的脚本上方时,该程序有效。我错过了一些非常明显的东西吗我的问题是否与文件夹结构,语法或其他内容有关?

2 个答案:

答案 0 :(得分:1)

window.onload = function assign() { var C = document.querySelectorAll('.click'); for (i = 0; i < C.length; i++) { C[i].addEventListener('click', function() { alert('bob'); }); } }之后,您可以像这样访问该模块中的变量:

<div style="max-width: 960px; margin: 0px auto; background-color: green;">
  <section id="cal-container">
    <form name="calculator">
      <input type="text" name="answer">
      <br>

      <input class="click" id="1" type="button" value=" 1 ">
      <input class="click" id="2" type="button" value=" 2 ">
      <input class="click" id="3" type="button" value=" 3 ">
      <input class="click" id="+" type="button" value=" + ">
      <br>

      <input class="click" id="4" type="button" value=" 4 ">
      <input class="click" id="5" type="button" value=" 5 ">
      <input class="click" id="6" type="button" value=" 6 ">
      <input class="click" id="-" type="button" value=" - ">
      <br>

      <input class="click" id="7" type="button" value=" 7 ">
      <input class="click" id="8" type="button" value=" 8 ">
      <input class="click" id="9" type="button" value=" 9 ">
      <input class="click" id="*" type="button" value=" * ">
      <br>

      <input class="click" id="v" type="button" value=" C ">
      <input class="click" id="0" type="button" value=" 0 ">
      <input class="click" id="=" type="button" value=" = ">
      <input class="click" id="/" type="button" value=" / ">
      <br>
    </form>
  </section>

</div>

您的新import country_data将是:

country_data.countrycodes
country_data.codemap
country_data.countries

答案 1 :(得分:-2)

你不能循环其他文件的变量或列表或词典,图像country_data.py作为类和countrycodes,codemap,countries是字段,你不能循环它们,你必须使用点运算符调用它们示例country_data.countrycodes [2]为您提供&#34; no&#34;,但您不能循环使用它们,文件不是可迭代对象