简体   繁体   English

嵌套的for循环不会提供所有输出

[英]nested for loop doesn't give all outputs

I'm supposed to get 16 outputs where each of the values from each of the for loops are multiplied each other but for some reason I'm getting only 4 out puts where only the 4000 value of K is being multiplied with all values of D . 我应该得到16个输出,其中每个for循环的每个值彼此相乘,但是由于某种原因,我只得到4个输出,其中仅4000的K值与D所有值相乘。 Can some one tell me where I went wrong? 有人可以告诉我我哪里出问题了吗?

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()

The order is important and your print statement must be in the inner for loop. 顺序很重要,并且您的打印语句必须位于内部的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()

You have to re-arrange your code, first declarations last print : 您必须重新排列代码,首先声明最后print

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)

Also, one pythonic way of doing that would be: 同样,一种pythonic的方式是:

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)

You are getting 4 outputs only, becasue your print() is outside second loop. 您仅获得4个输出,因为您的print() 第二个循环之外 Welcome to python indentation nightmare :) 欢迎来到python缩进梦night :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM