个性化阅读
专注于IT技术分析

Python continue语句用法示例

点击下载

本文概述

python中的continue语句用于将程序控制带到循环的开始。 Continue语句跳过循环内的其余代码行, 并从下一次迭代开始。它主要用于循环内的特定条件, 因此我们可以针对特定条件跳过某些特定代码。

Python继续语句的语法如下。

#loop statements
continue;
#the code to be skipped

例子1

i = 0;
while i!=10:
    print("%d"%i);
    continue;
    i=i+1;

输出

infinite loop

例子2

i=1; #initializing a local variable
#starting a loop from 1 to 10
for i in range(1, 11):
    if i==5:
        continue;
    print("%d"%i);

输出

1
2
3
4
6
7
8
9
10

通过声明

pass语句是一个空操作, 因为在执行时什么也没有发生。它在语法上需要语句但我们不想在其位置使用任何可执行语句的情况下使用。

例如, 可以在重写子类中的父类方法时使用它, 但不想在子类中提供其特定的实现。

如果代码将写入某处但尚未写入程序文件中, 则也使用Pass。

下面给出了pass语句的语法。

例子

list = [1, 2, 3, 4, 5]
flag = 0
for i in list:
    print("Current element:", i, end=" ");
    if i==3:
        pass;
        print("\nWe are inside pass block\n");
        flag = 1;
    if flag==1:
        print("\nCame out of pass\n");
        flag=0;

输出

Current element: 1 Current element: 2 Current element: 3 
We are inside pass block


Came out of pass

Current element: 4 Current element: 5
赞(0)
未经允许不得转载:srcmini » Python continue语句用法示例

评论 抢沙发

评论前必须登录!