Latest web development tutorials

Python3 loop

This chapter will introduce the use of Python loop statement.

Python in the loop and there for while.

Python loop control structure of the statement is as follows:


while loop

Python while statement in general form:

while 判断条件:
    语句

Also note the colon and indentation. Furthermore, no do..while loop in Python.

The following example uses a while to calculate the sum of 1-100:

#!/usr/bin/env python3

n = 100

sum = 0
counter = 1
while counter <= n:
    sum = sum + counter
    counter += 1

print("1 到 %d 之和为: %d" % (n,sum))

Execution results are as follows:

1 到 100 之和为: 5050

Infinite loop

We can never be realized as a false infinite loop by setting a conditional expression, examples are as follows:

#!/usr/bin/python3

var = 1
while var == 1 :  # 表达式永远为 true
   num = int(input("输入一个数字  :"))
   print ("你输入的数字是: ", num)

print ("Good bye!")

Implementation of the above script, the output results are as follows:

输入一个数字  :5
你输入的数字是:  5
输入一个数字  :

You can useCTRL + C to exit the current infinite loop.

Infinite loop in real time to client requests very useful on the server.

while recycling else statements

Else statement block execution of a conditional statement is false in a while ... else:

#!/usr/bin/python3

count = 0
while count < 5:
   print (count, " 小于 5")
   count = count + 1
else:
   print (count, " 大于或等于 5")

Implementation of the above script, the output results are as follows:

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

Simple statement group

The syntax is similar to the if statement, the while loop if you are only one statement, and while you can write the statement on the same line, as follows:

#!/usr/bin/python

flag = 1

while (flag): print ('欢迎访问本教程!')

print ("Good bye!")

Note: The above infinite loop you can use CTRL + C to interrupt the cycle.

Implementation of the above script, the output results are as follows:


for statement

Python for loop can iterate over any sequence of items, such as a list or a string.

The general format for circulation as follows:

for <variable> in <sequence>:
    <statements>
else:
    <statements>

Python loop cycle Example:

>>> languages = ["C", "C++", "Perl", "Python"] 
>>> for x in languages:
...     print (x)
... 
C
C++
Perl
Python
>>> 

The following example uses the break for statement, break statement to jump out of the current loop:

#!/usr/bin/python3

sites = ["Baidu", "Google","w3big","Taobao"]
for site in sites:
    if site == "w3big":
        print("本教程!")
        break
    print("循环数据 " + site)
else:
    print("没有循环数据!")
print("完成循环!")

After executing the script, in a loop to "w3big" will pop up when the loop:

循环数据 Baidu
循环数据 Google
本教程!
完成循环!

range () function

If you need to iterate over a sequence of numbers, you can use the built-in range () function. It will generate the number of columns, for example:

>>> for i in range(5):
...     print(i)
...
0
1
2
3
4

You can also use the value range specified range:

>>> for i in range(5,9) :
    print(i)

    
5
6
7
8
>>>

It is also possible to specify the range start number and specify a different increment (even negative, sometimes also called a 'step'):

>>> for i in range(0, 10, 3) :
    print(i)

    
0
3
6
9
>>> 

negative number:

>>> for i in range(-10, -100, -30) :
    print(i)

    
-10
-40
-70
>>> 

You can combine range () and len () function to traverse a sequence index, as follows:

>>> a = ['Google', 'Baidu', 'w3big', 'Taobao', 'QQ']
>>> for i in range(len(a)):
...     print(i, a[i])
... 
0 Google
1 Baidu
2 w3big
3 Taobao
4 QQ
>>> 

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

>>> list(range(5))
[0, 1, 2, 3, 4]
>>>

break and continue statements and loop else clause

break out of the for statement and the while loop. If you break out of a for or while loop, any corresponding loop else block is not executed. Examples are as follows:

#!/usr/bin/python3

for letter in 'w3big':     # 第一个实例
   if letter == 'b':
      break
   print ('当前字母为 :', letter)
  
var = 10                    # 第二个实例
while var > 0:              
   print ('当期变量值为 :', var)
   var = var -1
   if var == 5:
      break

print ("Good bye!")

Implementation of the above script output is:

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

continue statement is used to tell Python to skip the remainder of the current loop block statement, and then proceed with the next cycle.

#!/usr/bin/python3

for letter in 'w3big':     # 第一个实例
   if letter == 'o':        # 字母为 o 时跳过输出
      continue
   print ('当前字母 :', letter)

var = 10                    # 第二个实例
while var > 0:              
   var = var -1
   if var == 5:             # 变量为 5 时跳过输出
      continue
   print ('当前变量值 :', var)
print ("Good bye!")

Implementation of the above script output is:

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

Loops can have else clauses, it exhaustive list (with for loop) or the condition becomes false (with while loop) lead to the termination of the loop is executed, but the cycle is terminated when the break is not executed.

The following examples are for example query cycle primes:

#!/usr/bin/python3

for n in range(2, 10):
    for x in range(2, n):
        if n % x == 0:
            print(n, '等于', x, '*', n//x)
            break
    else:
        # 循环中没有找到元素
        print(n, ' 是质数')

Implementation of the above script output is:

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

pass sentence

Python pass an empty statement, in order to maintain the integrity of the program structure.

pass without doing anything, generally used as a placeholder statement following examples

>>> while True:
...     pass  # 等待键盘中断 (Ctrl+C)

Smallest categories:

>>> class MyEmptyClass:
...     pass

The following examples execute pass block of statements when letters o:

#!/usr/bin/python3

for letter in 'w3big': 
   if letter == 'o':
      pass
      print ('执行 pass 块')
   print ('当前字母 :', letter)

print ("Good bye!")

Implementation of the above script output is:

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