Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python3 loop statements

Python3 loop statements

This chapter introduces the use of Python loop statements.

The loop statements in Python are for and while.

The control structure diagram of Python loop statements is shown below:

Loop control keywords and methods

Keyword / function Description Example
for Iterative loop, used to traverse a sequence or iterable for i in list:
while Conditional loop, keeps executing while the condition is True while x > 0:
break Immediately terminate the current loop break
continue Skip the remaining code of this iteration and move to the next one continue
else(循环) Executed when the loop ends normally (without break) for i in range(3): ... else: ...
pass Placeholder statement in a loop (no operation) for i in range(5): pass
range() Generate a sequence of integers, often used with for loops range(0, 5)
enumerate() Get both the index and the value while traversing for i, v in enumerate(list):

while loop

The general form of the while statement in Python:


while 判断条件(condition):
    执行语句(statements)……

The execution flow diagram is as follows:

Gif demonstration of execution:

Again, pay attention to the colon and indentation. Also, there is no do..while loop in Python.

The following example uses while to compute the sum from 1 to 100:

Example

#!/usr/bin/env python3

n

=

100

sum

=

0

counter

=

1

while

counter

<=

n

:

sum

=

sum

counter

counter

+=

1

print

(

"

The sum from 1 to %d is: %d

"

%

(

n

,

sum

)

)

The result is as follows:


1 到 100 之和为: 5050

Infinite loop

We can create an infinite loop by making the conditional expression never false, as in the following example:

Example

#!/usr/bin/python3

var

=

1

while

var

==

1

:

The expression is always true

num

=

int

(

input

(

"

Enter a number :

"

)

)

print

(

"

The number you entered is:

"

,

num

)

print

(

"

Good bye!

"

)

Running the above script produces the following output:


输入一个数字  :5
你输入的数字是:  5
Enter a number:

You can use ** CTRL+C** to exit the current infinite loop.

Infinite loops are very useful for real-time client requests on a server.

Using else with a while loop

If the condition after while becomes false, the else block is executed.

The syntax format is as follows:

while :
    
else:
    

If the expr condition is true, the statement(s) block is executed; if false, additional_statement(s) is executed.

Loop over numbers and compare their size:

Example

#!/usr/bin/python3

count

=

0

while

count

<

5

:

print

(

count

,

"

Less than 5

"

)

count

=

count

1

else

:

print

(

count

,

"

Greater than or equal to 5

"

)

Running the above script produces the following output:


0  小于 5
1  小于 5
2  小于 5
3  小于 5
4  小于 5
5  大于或等于 5

Simple statement group

Similar to the syntax of the if statement, if your while loop body has only one statement, you can write it on the same line as the while, as shown below:

Example

#!/usr/bin/python

flag

=

1

while

(

flag

)

:

print

(

'

Welcome to Runoob Tutorial!

'

)

print

(

"

Good bye!

"

)

**Note:** You can use CTRL+C to interrupt the infinite loop above.

Running the above script produces the following output:


欢迎访问Runoob Tutorial!
欢迎访问Runoob Tutorial!
欢迎访问Runoob Tutorial!
欢迎访问Runoob Tutorial!
欢迎访问Runoob Tutorial!
……

The for statement

A Python for loop can traverse any iterable, such as a list or a string.

The general form of a for loop is as follows:

for

<

variable

in

<

sequence

: <

statements

else

: <

statements

Flow diagram:

Python for loop example:

Example

#!/usr/bin/python3

sites

=

[

"

Baidu

"

,

"

Google

"

,

"

Runoob

"

,

"

Taobao

"

]

for

site

in

sites

:

print

(

site

)

The output of the above code is:

Baidu
Google
Runoob
Taobao

It can also be used to print every character in a string:

Example

#!/usr/bin/python3

word

=

'

runoob

'

for

letter

in

word

:

print

(

letter

)

The output of the above code is:

r
u
n
o
o
b

A range of integer values can be used with the range() function:

Example

#!/usr/bin/python3

All the numbers from 1 to 5:

for

number

in

range

(

1

,

6

)

:

print

(

number

)

The output of the above code is:

1
2
3
4
5

for...else

In Python, the for...else statement is used to execute a block of code after the loop ends.

The syntax format is as follows:

for item in iterable:
    # Loop body
else:
    # Code executed after the loop

When the loop completes (that is, after all elements of the iterable have been traversed), the code in the else clause is executed; if a break statement is encountered during the loop, the loop is interrupted and the else clause is not executed.

Example

for

x

in

range

(

6

)

:

 

print

(

x

)

else

:

 

print

(

"Finally finished!"

)

After running the script, the output is:

0
1
2
3
4
5
Finally finished!

The following for example uses the break statement, which exits the current loop body so the else clause is not executed:

Example

#!/usr/bin/python3

sites

=

[

"

Baidu

"

,

"

Google

"

,

"

Runoob

"

,

"

Taobao

"

]

for

site

in

sites

:

if

site

==

"

Runoob

"

:

print

(

"

Runoob Tutorial!

"

)

break

print

(

"

Loop data

"

site

)

else

:

print

(

"

No loop data!

"

)

print

(

"

Loop complete!

"

)

After running the script, the loop body is exited when it reaches "Runoob":


循环数据 Baidu
循环数据 Google
Runoob Tutorial!
完成循环!

The range() function

If you need to traverse a sequence of numbers, you can use the built-in range() function. It generates a sequence of numbers, for example:

Example

for

i

in

range

(

5

)

: ...

print

(

i

)

...

0

1

2

3

4

You can also use range() to specify an interval:

Example

for

i

in

range

(

5

,

9

)

:

print

(

i

)

5

6

7

8

You can also make range() start at a specified number and use a different increment (it can even be negative, sometimes called the 'step'):

Example

for

i

in

range

(

0

,

10

,

3

)

:

print

(

i

)

0

3

6

9

Negative numbers:

Example

for

i

in

range

(

10

, -

100

, -

30

)

:

print

(

i

)

10

40

70

You can combine range() and len() to traverse the indices of a sequence, as shown below:

Example

a

=

[

'

Google

'

,

'

Baidu

'

,

'

Runoob

'

,

'

Taobao

'

,

'

QQ

'

]

for

i

in

range

(

len

(

a

)

)

: ...

print

(

i

,

a

[

i

]

)

...

0

Google

1

Baidu

2

Runoob

3

Taobao

4

QQ

You can also use the range() function to create a list:

Example

list

(

range

(

5

)

)

[

0

,

1

,

2

,

3

,

4

]

For more on the use of the range() function, see:https://www.runoob.com/python3/python3-func-range.html


The break and continue statements and the else clause in loops

break execution flow diagram:

continue execution flow diagram:

Execution process of the while statement:

Execution process of the for statement:

break statement can exit the body of a for or while loop. If you terminate from a for or while loop, any corresponding loop else block will not be executed.

continue statement is used to tell Python to skip the remaining statements in the current loop block and continue with the next iteration.

Example

Using break in while:

Example

n

=

5

while

n

0

:

    n -

=

1

   

if

n

==

2

:

       

break

   

print

(

n

)

print

(

'Loop ends.'

)

The output is:

4
3
循环结束。

Using continue in while:

Example

n

=

5

while

n

0

:

    n -

=

1

   

if

n

==

2

:

       

continue

   

print

(

n

)

print

(

'Loop ends.'

)

The output is:

4
3
1
0
循环结束。

More examples are as follows:

Example

#!/usr/bin/python3

for

letter

in

'

Runoob

'

:

First Example

if

letter

==

'

b

'

:

break

print

(

'

Current letter is :

'

,

letter

)

var

=

10

Second example

while

var

0

:

print

(

'

Current variable value is :

'

,

var

)

var

=

var

1

if

var

==

5

:

break

print

(

"

Good bye!

"

)

Running the above script produces the following output:


当前字母为 : R
当前字母为 : u
当前字母为 : n
当前字母为 : o
当前字母为 : o
当前变量值为 : 10
当前变量值为 : 9
当前变量值为 : 8
当前变量值为 : 7
当前变量值为 : 6
Good bye!

The following example loops over the string Runoob and skips output when the letter o is encountered:

Example

#!/usr/bin/python3

for

letter

in

'

Runoob

'

:

First Example

if

letter

==

'

o

'

:

Skip output when the letter is o

continue

print

(

'

Current letter :

'

,

letter

)

var

=

10

Second example

while

var

0

:

var

=

var

1

if

var

==

5

:

Skip output when the variable is 5

continue

print

(

'

Current variable value :

'

,

var

)

print

(

"

Good bye!

"

)

Running the above script produces the following output:


当前字母 : R
当前字母 : u
当前字母 : n
当前字母 : b
当前变量值 : 9
当前变量值 : 8
当前变量值 : 7
当前变量值 : 6
当前变量值 : 4
当前变量值 : 3
当前变量值 : 2
当前变量值 : 1
当前变量值 : 0
Good bye!

Loop statements can have an else clause, which is executed when the loop terminates because the list is exhausted (with a for loop) or the condition becomes false (with a while loop), but not when the loop is terminated by break.

The following example shows a loop that checks for prime numbers:

Example

#!/usr/bin/python3

for

n

in

range

(

2

,

10

)

:

for

x

in

range

(

2

,

n

)

:

if

n

%

x

==

0

:

print

(

n

,

'

Equal

'

,

x

,

'

'

,

n

//

x

)

break

else

:

No element was found in the loop

print

(

n

,

'

is a prime number

'

)

Running the above script produces the following output:


2  是质数
3  是质数
4 等于 2 * 2
5  是质数
6 等于 2 * 3
7  是质数
8 等于 2 * 4
9 等于 3 * 3

The pass statement

Python pass is an empty statement used to keep the program structure complete.

pass does nothing and is generally used as a placeholder statement, as in the following example

Example

while

True

: ...

pass

Wait for a keyboard interrupt (Ctrl+C)

The smallest class:

Example

class

MyEmptyClass

: ...

pass

The following example executes the pass block when the letter is o:

Example

#!/usr/bin/python3

for

letter

in

'

Runoob

'

:

if

letter

==

'

o

'

:

pass

print

(

'

Execute the pass block

'

)

print

(

'

Current letter :

'

,

letter

)

print

(

"

Good bye!

"

)

Running the above script produces the following output:


当前字母 : R
当前字母 : u
当前字母 : n
执行 pass 块
当前字母 : o
执行 pass 块
当前字母 : o
当前字母 : b
Good bye!