为什么for循环未附加列表

时间:2018-07-10 10:34:13

标签: python list loops

在下面的代码中,循环似乎不起作用。

powers = []
x = 0
y = 0
z = 1

for x in powers:
powers.append([])
for y in powers[x]:
    powers[x].append(z ** y)
    z = z + 1
    if z < 1001:
        continue
    else:
        break
x = x + 1
y = y + 1
z = 1
print(powers)

但是,当我在终端中运行此命令时,它只是返回一个空列表以显示电源。它没有显示错误消息。

请帮助。

1 个答案:

答案 0 :(得分:1)

您的代码格式错误,因此请考虑设置格式,无论如何,您的某些错误都是代码注释。

powers = []
x = 0
y = 0
z = 1

for x in powers: #here you're overriding former declaration of x, also powers is empty so for doesn't have a single run
powers.append([]) ##code is not indented so this istruction execute only once
for y in powers[x]: ##powers[x] is an empty list
        powers[x].append(z ** y)
        z = z + 1
        if z < 1001:
            continue
        else:
            break
z = 1 ## this is outside the cycle 
x = x + 1 
y = y + 1 

print(powers)