为什么我的嵌套 for 循环提前结束? (python)
Why is my nested for loop ending early? (python)
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
感谢任何帮助。
pythons range(1,5)
不包括尾数 - 这意味着它只会从 1 循环到 4。阅读有关此主题的更多信息 here :-)
@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))
我的解释:
range
包括第一个值
range
排除第二个值
参见:this
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
感谢任何帮助。
pythons range(1,5)
不包括尾数 - 这意味着它只会从 1 循环到 4。阅读有关此主题的更多信息 here :-)
@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))
我的解释:
range
包括第一个值range
排除第二个值
参见:this