为什么嵌套for循环提前结束?(Python)

2024-04-24 02:52:53 发布

您现在位置: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(开始内部),3(结束内部),1(开始外部),2(结束外部)

我应该得到:

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

相反,我得到:

1 1
1 2

谢谢你的帮助。你知道吗


Tags: thenameloopformatforinputvaluestart
2条回答

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

我的解释:

  1. range包括第一个值

  2. range排除第二个值

见:this

相关问题 更多 >