为什么我的for循环嵌套会提前结束? (蟒蛇)

时间:2018-08-30 09:50:44

标签: python for-loop nested-loops

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: "))
for outer in range(start_outer, end_outer):
    for inner in range(start_inner, end_inner):
        print("{:^2} {:^2}".format(outer, inner))

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

我应该得到:

1 1
1 2
1 3
2 1
2 2
2 3

相反,我得到了:

1 1
1 2

感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

python range(1,5)在结束时不包含在内-意味着它只会从1循环到4。有关此主题的更多信息here:-)

答案 1 :(得分:1)

@ Cut7er是正确的,但这是他的解决方案:

...
for outer in range(start_outer, end_outer+1):
    for inner in range(start_inner, end_inner+1):
        print("{:^2} {:^2}".format(outer, inner))

我的解释:

  1. range包含第一个值

  2. range排除第二个值

请参阅:this