Python Loop statement

Source: Internet
Author: User

Loops in Python

The looping statements in Python have two for...in loops and a while loop. loop control statements, similar to other languages, also have break and continue. Unlike other languages, the for...in loop and the while loop can be followed by an else statement, which is described in turn

The control structure diagram of the loop statement is as follows:

For In loop

The syntax for the in loop is as follows:

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

Where <sequence> can be a string, or it can be a list, etc...

for i in ‘hello‘:                  # 遍历字符串    print(i)输出结果:hello######for i in [‘a‘, ‘b‘, ‘c‘, ‘d‘]:      # 遍历列表    print(i)输出结果:abcd######d = {‘a‘: 1, ‘b‘: 2, ‘c‘: 3} for k, v in d.items():         # 遍历字典,可同时迭代key和value    print(k, v)输出结果:a 1b 2c 3

These objects, which can be iterated directly, are called iterative objects: iterable (the iterable type of the collections module), as long as the Iterable object can be used for a for loop. You can use Isinstance () to determine whether an object is an Iterable object, as shown in the following example:

lst = (1, 2, 3)                                 # 元组类型flag = isinstance(lst, Iterable)print(flag)输出结果:True                                             # 元组为可迭代对象

The following two types of data can always be used in A For loop:
1) collection data types, such as list, tuple, dict, set, str ...
2) generator (generator) and generator function with yield

Range () function

The range () function is a python built-in function that can generate a sequence of numbers.

hello_range = range(3)print(isinstance(hello_range, Iterable))            for i in hello_range:       # 循环遍历 数列    print(i)输出结果:True                              #  range(3) 所生成的对象为 可迭代对象012

Use range to specify the interval of the series:

>>> for i in range(2,5):...     print(i)...234

In addition to specifying intervals, you can also specify the step size:

>>> for i in range(2, 10, 3):...     print(i)...258

The range () function can also be used to create a list or tuple in addition to the For loop:

hello_list = list(range(10))           # 生成 listprint(hello_list)hello_tuple = tuple(range(10))    # 生成 tupleprint(hello_tuple)
Else statements in the for...in loop

For...in can also have an else statement later, with the following syntax:

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

The statement in else will be executed after the For loop ends:

>>> for i in range(5):...     print(i)... else:...     print(‘end...‘)...01234end...

Tip: If the For loop is terminated by break, the statement in else is not executed, and the following describes ~

While loop

The syntax for the while loop in Python is as follows:

while <condition>:    <statements>

If the condition is met, the loop is kept, knowing that the condition is not satisfied, exiting the Loop ~

Example below, ask for 1 ... Sum of 100:

sum = 0n = 1while n <= 100:    sum += n    n += 1print(sum)                # 输出结果:5050
Else statements in a while loop

Similar to the for...in loop, the while loop can have an else statement after it, with the following syntax:

while <condition>:    <statements>else:    <statements>

When the return value of the judgment statement after the while is false, the loop terminates and the statement in the else is executed. As with the for...in loop, if the loop is terminated by a break, the statement in the else is not executed.

sum = 0n = 1while n <= 100:    sum += n    n += 1else:    print(‘end...loop‘)print(sum)输出结果:end...loop5050
Infinite loops

You can make the judgment statement after the while return to True so that the loop will not be terminated and the statement in the loop body is executed:

while True:    username = input(‘请输入用户名:‘)    print(‘welcome %s‘ % username)输出结果:请输入用户名:Obamawelcome Obama请输入用户名:Trumpwelcome Trump请输入用户名:............

For example, the Linux terminal user login, if the user entered the user name and password is incorrect, will always ask the user to re-enter, until the input is correct ~
Under Simple simulation:

username = ‘baby‘passwd = ‘123456‘flag = Truewhile flag:    login_username = input(‘请输入用户名:‘)    login_passwd = input(‘请输入密码:‘)    if login_username == username and login_passwd == passwd:        flag = Falseelse:    print(‘Welcome %s‘ % username)输出结果:请输入用户名:Obama请输入密码:abc请输入用户名:Trump请输入密码:123请输入用户名:baby请输入密码:123456Welcome baby
Break and Continue statements

You can also use break, Contiune, in a looping statement to control the loop flow.

Continue statements

Continue is used to skip the remaining statements in this cycle and go directly to the next loop, as shown in the following example:

# 计算1...100的奇数和sum =0count = 0while count < 100:    count += 1    if count % 2 != 1:              # 若不是奇数,直接进入下一次循环        continue    sum += countprint(‘sum=%s‘ % sum)输出结果:sum=2500
Break statement

Break is used to jump out of a recent loop, as in the following example:

sum =0count = 1while count <= 100:    if count == 51:        break    sum += count    count += 1print(‘sum=%s‘ % sum)输出结果:sum=1275

When Count is 51 o'clock, the loop is terminated, and Sum calculates the sum of the 1...50

Tip:break jumps out of the loop and only jumps out of the nearest loop, and if the loop is only one layer, the loop ends when the break is executed, and if the loop has 2 layers, the outer loop will continue

lst_1 = [‘a......‘, ‘b......‘, ‘c......‘]lst_2 = [1, 2, 3]for i in lst_1:    print(i)    for j in lst_2:        print(j)输出结果:a......123b......123c......123

As shown above, there are two layers of loops, and now, when the inside loop to 2 o'clock, use break to terminate the loop (see example below), you can see that the inner loop terminates after 2 in the output lst_2, but the outer loop continues:

lst_1 = [‘a...‘, ‘b...‘, ‘c...‘]lst_2 = [1, 2, 3]for i in lst_1:    print(i)    for j in lst_2:        print(j)        if j == 2:            break输出结果:a...12b...12c...12

Break also has a point of note that the else statement after the loop is not executed when the loop is terminated by break

lst_1 = [‘a...‘, ‘b...‘, ‘c...‘]for i in lst_1:    print(i)else:    print(‘end...‘)输出结果:a...b...c...end...        # 正常执行else中的内容lst_1 = [‘a...‘, ‘b...‘, ‘c...‘]for i in lst_1:    print(i)    if lst_1.index(i) == 1:      # 当循环值lst_1下标为1的元素时,终止循环        breakelse:    print(‘end...‘)输出结果:                       # 没有 c... 和 end... 输出a...b...

The while loop is the same, here is the example directly used:

sum = 0count = 1while count <= 100:    if count == 51:        break    sum += count    count += 1else:    print(‘end loop...‘)print(‘sum=%s‘ % sum)输出结果:sum=1275                  # else 中的 end loop... 并没有输出

.................^_^

Python Loop statement

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.