在编程中,`continue` 语句用于跳过当前循环的剩余部分,并立即开始下一次循环。它通常与 `if` 语句结合使用,以便在满足特定条件时跳过循环的某些迭代。以下是 `continue` 语句的一些用法示例:
基本语法
```python
for i in range(10):
if i == 5:
continue
print(i)
```
输出结果:
```
0, 1, 2, 3, 4
```
嵌套循环中的使用
```python
for i in range(3):
for j in range(3):
if j == 1:
continue
print(i, j)
```
输出结果:
```
0 0, 0 2, 2 0 2 2
```
跳过循环体中剩余的语句
```python
for n in range(1, 11):
if n % 3 == 0:
continue
print(n)
```
输出结果:
```
1, 2, 4, 5, 7, 8, 10
```
在循环结构中跳过本次循环中剩余的代码并在条件求值为真时开始执行下一次循环
```python
while (list($key, $value) = each($arr)):
if (!($key % 2)):
continue;
do_something_odd($value);
```
在多层循环中使用
```python
$i = 0;
while($i++):
echo "Outer\n";
while(1):
echo "Middle\n";
while(1):
echo "Inner\n";
continue 3;
echo "This never gets output.\n";
echo "Neither does this.\n";
```
注意:`continue 3;` 在这里表示跳过循环体中剩余的语句,并继续执行下一次外层循环。
建议
`continue` 语句应谨慎使用,因为它会跳过当前循环的剩余部分,可能会导致逻辑上的错误,特别是在复杂的循环结构中。
在需要跳出多重循环时,可以考虑使用 `goto` 语句,但应尽量避免,以保持代码的可读性和可维护性。
通常,通过优化循环条件和逻辑,可以减少对 `continue` 语句的依赖。