无法创建嵌套的while循环

时间:2019-09-20 04:19:17

标签: while-loop nested data-science

我应该“编写一个程序,该程序使用两个嵌套的while循环来打印3x3网格(编号1至3)的行和列,不包括沿对角线的单元(即行和列具有相同的值)。

我尝试通过在每次迭代中添加一个来打印行col = 1,1。

row, col = 1, 1

while row != 3 and col != 3:
    row += 1
    col += 1
print (row, col)

结果应如下所示: 1 2 1 3 2 1 垂直在顶部12,在中间13和在底部21。

1 个答案:

答案 0 :(得分:0)

嵌套 while循环通常意味着在第二个内部中的第一个。我不知道您使用的是哪种语言,但您应该考虑以下类似内容:

while row <= 3:
  while col <= 3:
    print (row, col)
    col++
  col = 1
  row++

这不会进行对角线检查,但是它演示了嵌套循环的想法:

  1. 外部循环以row = 1col = 1开头。
  2. 内部循环开始。
  3. 内部循环计数1-3列,然后退出;
  4. 外部循环将col重置为1并递增行
  5. 外循环的下一次迭代从新行开始。
  6. 重复步骤2-5,直到row = 4,此时外循环退出,您就完成了。

这是javascript中这种情况的一个示例,包括对角线检查:

let row = 1;
let col = 1;

// do this block until row > 3
while (row <= 3) {

  // declare a new array to collect this row's output
  let output = []; 

  // do this block until col > 3
  while (col <= 3) {

    // add the column or '-' to the end of the array
    output.push( row === col ? '-' : col );

    // increment the column
    col++;
  }
  
  // row finished. emit the collected
  // row with a space between the numbers
  console.log(output.join(' '));

  // reset column to 1
  col = 1;

  // do the next row
  row++;
}