虽然循环提前结束?

时间:2018-09-04 07:22:06

标签: python loops while-loop

first_name = input("Please enter your first name: ").capitalize()
start_inner = int(input("Hi {}, please enter the start value for the inner loop: ".format(first_name)))
end_inner = int(input("Please enter the end value for the inner loop: "))
start_outer = int(input("Please enter the start value for the outer loop: "))
end_outer = int(input("Please enter the end value for the outer loop: "))

while start_outer <= end_outer:
        while start_inner <= end_inner:
                print("{:>1} {:>1}".format(start_outer,start_inner))
                start_inner = start_inner +1
        start_outer = start_outer +1
print("After the loop")

如果我要输入1(start_inner),4(end_inner),1(start_outer),3(end_outer)

我应该得到

1 1
1 2
1 3
1 3
2 1
2 2
2 3
2 4
3 1
3 2
3 3
3 4

相反,我明白了

1 1
1 2
1 3
1 4

我问了一个关于for循环的非常类似的问题,在打印中添加+1似乎有帮助,但是while循环没有运气。

谢谢

3 个答案:

答案 0 :(得分:0)

您的start_inner并没有恢复为初始值。尝试使用中间变量进行迭代或更好地使用for循环。

start_inner = 1
end_inner = 4
start_outer = 1
end_outer = 3

while start_outer <= end_outer:
    iter_start_inner = start_inner
    while iter_start_inner <= end_inner:
            print("{:>1} {:>1}".format(start_outer,iter_start_inner))
            iter_start_inner += 1
    start_outer = start_outer +1
print("After the loop")

for循环替代

for i in range(start_outer,end_outer+1):
    for j in range(start_inner,end_inner+1):
            print("{:>1} {:>1}".format(i,j))

答案 1 :(得分:0)

您需要在一次内部循环之后再次重置“开始内部”

start_inner = 1
end_inner = 4
start_outer = 1
end_outer = 3    
while start_outer <= end_outer:
            while start_inner <= end_inner:
                    print("{:>1} {:>1}".format(start_outer,start_inner))
                    start_inner = start_inner +1
            start_inner = 1        
            start_outer = start_outer +1
    print("After the loop")

答案 2 :(得分:0)

OR:

...
print('\n'.join("{:>1} {:>1}".format(i,j) for i in range(start_outer,end_outer+1) for j in range(start_inner,end_inner+1)))
print("After the loop")