Python 嵌套for循环不';我不能给出所有的结果
我应该得到16个输出,其中来自每个for循环的每个值彼此相乘,但出于某种原因,我只得到4个输出,其中只有Python 嵌套for循环不';我不能给出所有的结果,python,for-loop,if-statement,nested-loops,Python,For Loop,If Statement,Nested Loops,我应该得到16个输出,其中来自每个for循环的每个值彼此相乘,但出于某种原因,我只得到4个输出,其中只有K的4000个值与D的所有值相乘。谁能告诉我哪里出了问题 def main(): for i in range(0,4): for j in range(0,4): if j==0: K=1000 elif j==1: K=2000 e
K
的4000个值与D
的所有值相乘。谁能告诉我哪里出了问题
def main():
for i in range(0,4):
for j in range(0,4):
if j==0:
K=1000
elif j==1:
K=2000
elif j==2:
K=2500
else:
K=4000
if i==0:
D=2
elif i==1:
D=4
elif i==2:
D=5.5
else:
D=10
print("The year with depth",D,"and K as",K,"is",K*D)
main()
由于
print()
在第二个循环之外,因此您只能获得4个输出。欢迎使用python缩进噩梦:)您必须重新安排代码,先声明后打印:
def main():
for i in range(0,4):
if i==0:
D=2
elif i==1:
D=4
elif i==2:
D=5.5
else:
D=10
for j in range(0,4):
if j==0:
K=1000
elif j==1:
K=2000
elif j==2:
K=2500
else:
K=4000
print("The year with depth",D,"and K as",K,"is",K*D)
另外,一种类似蟒蛇的方法是:
for D in (2, 4, 5.5, 10):
for K in range(1000, 5000, 1000):
print("The year with depth",D,"and K as",K,"is",K*D)
顺序很重要,打印语句必须位于内部for循环中
def main():
for i in range(0,4):
if i==0:
D=2
elif i==1:
D=4
elif i==2:
D=5.5
else:
D=10
for j in range(0,4):
if j==0:
K=1000
elif j==1:
K=2000
elif j==2:
K=2500
else:
K=4000
print("The year with depth",D,"and K as",K,"is",K*D)
main()
如果s使用字典列表和
i
,j
作为索引,而不是大量的if
。并且您的打印应该在de内环内,否则所有K
s将打印为4000