难以理解带有加法,范围和打印功能的嵌套循环

问题描述

当我将这条python代码与输入12一起使用时,答案是0、6、18。我不知道如何计算,我一直将其可视化为代码段2,答案为0、0、1、3, 6,6,8,12。

此循环如何工作?

 import React from 'react';
    import { browserRouter as Router,Route } from 'react-router-dom';
    import {name} from '../package.json';
    import HomePage from './Components/HomePage/index';
    import SearchResults from "./Components/SearchResults/index";

function App() {
    return (
        <Router basename={ `/${name}` }>
            <div>
                <Route exact path="/" component={HomePage} />
                <Route path="/resultspage" component={SearchResults} />
            </div>
        </Router>
    );
}

export default App;

我的计算结果

stop=int(input())
result=0
for a in range(5): 
  for b in range(4): 
    result += a * b
  print(result)
  if result > stop: 
    break 

picture of my calculations

解决方法

我将引导您完成for a in range(5)循环。

首先,a = 0,结果= 0。

  • 这将循环4次,结果仍为0,因为0 * b = 0
  • 0已打印

接下来,a = 1,结果= 0。

  • 结果+ = 1x0 + 1x1 + 1x2 + 1x3
  • 所以结果= 0 + 6
  • 已打印6张

最后,a = 2,结果= 6。

  • 结果+ = 2x0 + 2x1 + 2x2 + 2x3
  • 所以结果= 6 + 12 = 18
  • 已打印18张
  • if result > stop的计算结果为true,因此循环中断。