循环访问变量

时间:2014-01-09 03:33:43

标签: python variables while-loop global-variables counter

我正在编写一个简单的python程序,使用双循环打印出一个带有一组唯一坐标的html页面。我收到错误,因为它无法识别循环中的变量(跨越+ node_counter)。我该怎么做才能获得在顶部声明的变量?

game_counter = 0

across0 = '72,70,97,70,97,61,116,71,97,83,97,75,72,75'
across1 = '143,70,168,70,168,61,187,71,168,83,168,75,143,75'
across2 = '212,70,237,70,237,61,256,71,237,83,237,75,212,75'
across3 = '283, 70, 308, 70, 309, 61, 327, 71, 308, 83, 308, 75, 283, 75'

while game_counter <60:
    text_file.write("<!-- These are the image maps for game " + str(game_counter) + " -->\n\n")
    node_counter = 0

    while node_counter < 15:
        placeholder_string = ""
        placeholder_string += '<area shape="poly" coords = "' + (across + node_counter) + '" href="#"/>\n'
        text_file.write(placeholder_string)
        node_counter += 1
        if node_counter == 15:
            game_counter += 1

3 个答案:

答案 0 :(得分:1)

看起来你正试图迭代你的“跨越”变量。也许你的意思是这样的:across = ['72...', '143...']。然后,您可以使用across循环遍历for

for a in across:
    print(a)

我使用print作为for循环的示例。此外,如果您使用的是python 2,则可以使用print a代替print(a)

答案 1 :(得分:0)

我认为您的意思是添加across0across1across2across3,而不仅仅是across

另外,您不需要那些continue语句。

答案 2 :(得分:0)

您正在尝试将变量across添加到node_counter,但您只定义了变量across0across1,...这就是您获取变量的原因错误。

还有一些其他错误

  • 将跨值存储在数组数组中
  • 将外环中的60更改为4(更好的是跨越的长度)
  • 更改内部循环以使用数组长度也是明智的
  • 使用问题专栏上的across更改要game_counter的索引。
  • 永远不会执行if行,因此您将陷入无限循环。将game_counter增量移到内循环之外。

这给出了以下代码

across = [[72,70,97,70,97,61,116,71,97,83,97,75,72,75],
    [143,70,168,70,168,61,187,71,168,83,168,75,143,75],
    [212,70,237,70,237,61,256,71,237,83,237,75,212,75],
    [283, 70, 308, 70, 309, 61, 327, 71, 308, 83, 308, 75, 283, 75]]

while game_counter < len(across):
    text_file.write("<!-- These are the image maps for game " + str(game_counter) + " -->\n\n")
    node_counter = 0

    while node_counter < len(across[game_counter]):
        placeholder_string = ""
        placeholder_string += '<area shape="poly" coords = "' + (across[game_counter][node_counter] + node_counter) + '" href="#"/>\n'
        text_file.write(placeholder_string)
        node_counter += 1

    game_counter += 1

但是你可能会更好地使用for循环,至少对于内循环:

for item in across[game_counter]:
    ...
    ... (item + node_counter) ...
相关问题