Python from rookie to Master (10): Loop

Source: Internet
Author: User
Tags keywords list terminates

We now know how to use the IF statement to get the program to run along a different path, but the best thing about the program is to use the CPU and GPU's powerful execution to repeatedly execute a piece of code, think of Google's Alphago and Ke Jie's man-machine war, despite the apparent triumph of artificial intelligence, In fact, artificial intelligence is only an algorithm, artificial only algorithm will be able to quickly complete the huge amount of data sharing, the role of the cycle in which can not be.

Readers of first-contact programming may not yet understand what the loop is. Let's look at the pseudo-code of the loop.

    1. View Bank card Balances
    2. No payroll, wait 1 minutes, continue to execute 1
    3. Oh,yeah, has been paid, continue to carry out the 4.
    4. To spend

As we can see, this pseudo-code repeats itself to show what a loop really is. For a loop, there must be a loop condition first. If the condition is true, the loop resumes, and if the condition is false, exits the loop and resumes execution of the statement following the loop. For this pseudo-code, the loop condition is "whether the wage has been paid to the bank card", if there is no wage in the card, then the cycle condition is true, continue to perform the 1th step (continue to view the bank card balance), the period will require waiting for 1 minutes, in fact, this process can be understood as the loop to execute time. If you find that the wages have been hit on the bank card, then the cycle condition is false, then exit the cycle, to consume.

In the Python language, there are two types of statements that can implement this looping operation, which is the while loop and for loop, and this article will explain in detail how these two types of loops are used.

1. While loop

To make it easier to understand the while loop, the following first uses the "dumb" method to output a total of 10 numbers from 1 to 10 in the Python console.

Print (1)

Print (2)

Print (3)

Print (4)

Print (5)

Print (6)

Print (7)

Print (8)

Print (9)

Print (10)

We can see that in the above code, 10 times the print function output 1 to 10 a total of 10 numbers, but this just output 10 numbers, if you want to output 10,000 or more numbers? Obviously the way to write code in such a line is quite cumbersome, and the following is our protagonist while loop.

Now explain the use of the while loop directly in Python code.

x = 1while x <= 10:    print(x)    x += 1

We can see that the while keyword is followed by a conditional expression, ending with a colon (:), which indicates that the while loop is also a block of code, so the statement inside the while loop needs to be indented.

In the preceding code, you first define an X variable in front of the while loop, with an initial value of 1. Then start entering the while loop. When the statement in the while loop is executed for the 1th time, the value of the x variable is output with the print function, and the value of the x variable is added 1, the last statement in the while loop is executed for the 1th time, and then the condition after the while is re-judged, when the value of the x variable is 2,x <= 10 still satisfies , the while loop will continue execution (2nd execution) until the while loop executes 10 times, when the value of the x variable is 11,x <= 10 is no longer satisfied, so the while loop ends and the statement after the while is resumed.

is the while loop simple? In fact, the for loop introduced in the next sectionto is not complicated, but the usage is somewhat different from the while loop.

2. For loop

The while loop is very powerful, it can do any kind of loop, technically, there is a while loop is enough, then why add a For loop? In fact for some loops, while still need to write some more code, in order to further simplify the loop of code, the Python statement introduced a for loop.

The For loop is used primarily to loop through a collection (sequences and other objects that can iterate), and each time a loop is taken, an element is obtained from the collection and a block of code is executed once. The For loop ends (exits the loop) until all the elements in the collection are enumerated (the process of getting each element in the collection is called an enumeration).

The concept of a collection is used when using a for loop, and since the collection is not yet mentioned, this section gives the simplest set (list) as an example, and in later chapters, the use of collections and for loops is described in detail.

Before using a For loop, define a keywords list with the elements of the list as strings. Then use the For loop to output all the element values in the keywords list.

>>> keywords = [‘this‘, ‘is‘, ‘while‘, ‘for‘,‘if‘]     # 定义一个字符串列表>>> for keyword in keywords:                        # 用for循环输出列表中的元素...     print(keyword)... thisiswhileforif

The code for this for loop is very well understood, and the for statement separates the variables and collection variables that hold the collection elements from the IN keyword. In this case, keywords is a collection, and when the For loop executes, it takes one element value from the keywords list in turn, until the iteration (another statement of the loop) is to the last element in the list "if".
Some readers may find that the for loop is convenient for iterating through collections, but can you implement a while loop to loop a variable? In other words, the variable sets an initial value outside the loop, and within the loop, controls the execution of the loop by changing the value of the variable. In fact, for the loop can be used in a flexible way to implement this function, we can imagine that if you define a list of numeric types, the list of element values is 1 to 10, then not the equivalent of the variable x from 1 to 10!

>>> numbers = [1,2,3,4,5,6,7,8,9,10]>>> for number in numbers:...     print(number, end=" ")          # 输出1到10共10个数字... 1 2 3 4 5 6 7 8 9 10 >>>

If this is the way it's technically possible to do this, it's too cumbersome to fill in all the numbers manually, so we can use a range function to do this work. The range function has two parameters, namely the minimum and maximum values of the range of values plus 1, to note that the range function returns a list of half-open half-closed intervals, and if you want to generate a 1 to 10 list, you should use range (1, 11).

>>> for num in range(1,11):  # 用range函数生成元素值为1到10的列表,并对这个列表进行迭代...     print(num, end=" ")... 1 2 3 4 5 6 7 8 9 10 >>>

This example demonstrates the use of a sequential structure, while loops and a for loop to output adjacent numbers, where the for loop uses the range function to quickly generate a list of many adjacent numbers and iterate over the lists.

print(1,end=" ")print(2,end=" ")print(3,end=" ")print(4,end=" ")print(5,end=" ")print(6,end=" ")print(7,end=" ")print(8,end=" ")print(9,end=" ")print(10)# 用while循环输出1到10print("用while循环输出1到10")x = 1while x <= 10:    print(x,end=" ")    x += 1#  定义一个列表numbers = [1,2,3,4,5,6,7,8,9,10]print("\n用for循环输出列表中的值(1到10)")for num in numbers:    print(num, end= " ")# 用range函数生成一个元素值从1到9999的列表numbers = range(1,10000)        print("\n用for循环输出列表中的值(1到9999)")for num in numbers:    print(num, end= " ")print("\n用for循环输出列表中的值的乘积(1到99)")# 用range函数生成一个元素值为0到99的的列表,并对该列表进行迭代for num in range(100):          # range函数如果只指定一个参数,产生的列表元素值从0开始    print(num * num, end= " ")

The program runs as shown in the results.

"Python from rookie to master" began to reprint, please pay attention to

3. Jump out of the loop

In the while loop that is described earlier, the value of the conditional expression after the while is used to determine whether to end the loop, but in many cases it is necessary to jump out of the loop between the inside of the body, which uses the break statement.

>>> x = 0>>> while x < 100:...     if x == 5:...         break;...     print(x)...     x += 1... 01234

In the preceding code, the condition statement for the while loop is x < 100, and the initial value of the x variable is 0, so if in the while loop each loop has a value of x variable plus 1, then the while loop loops 100 times. However, the IF statement is judged in the while loop, and when the value of X is 5 o'clock, the break statement exits the loop. So the while loop executes only 6 times (x from 0 to 5), and when it is executed to the last time, the break statement is rolled out while the statement is not invoked, so the program will only output a total of 4 numbers from 0 to 5.

There is another continue statement corresponding to the break statement, unlike the break statement, where the continue statement terminates the loop, and the break statement is used to completely exit the loop. After the continue statement terminates the loop, the next loop is immediately started.

>>> x = 0>>> while x < 3:...     if x == 1:...         continue;...     print(x)...     x += 1... 0

In the preceding code, when x equals 1 o'clock executes the CONTINUE statement, all statements following the IF condition statement are not executed and the while loop continues the next loop. But here's a question, when we execute this code, we find ourselves in a dead loop. The so-called dead loop, which means that the value of the condition expression of the while loop is always true, that is, the loop never ends. A dead loop is a mistake that is often easily made when using loops.

Now let's take a look at this piece of code. If you want the while loop to end normally, x must be greater than or equal to 3, but when x equals 1 o'clock executes the CONTINUE statement, all statements following the IF statement will not be executed in this loop, but the last statement of the while loop is x + = 1, this statement is used to add 1 to the value of the x variable in each loop. But this time does not add 1, so the next cycle, the value of the x variable is still 1, that is, if the condition of the statement is always satisfied, therefore, the continue statement will be executed forever, so the value of the x variable can never be greater than or equal to 3. The end result is that the statements in the while loop will be executed forever, which is the dead loop mentioned earlier.

The workaround is also simple, just make sure the variable x is 1 before executing the Continue statement. or put x + = 1 in front of the if statement, or in the IF statement.

>>> x = 0>>> while x < 3:...     if x == 1:...         x += 1              #  需要在此处为x加1,否则将进入死循环...         continue...     print(x)...     x += 1... 02

The break and continue statements also support a For loop, and nested loops are supported. Note, however, that if you use the break statement in a nested loop, you can only exit the loop of the current layer and not exit the outermost loop. In instance 3.8, the reader is shown a more complex way to use the loop.

In addition to demonstrating the basic usage of while and for loops, this example terminates the entire while and for loop through the break statement and terminates the loop of the while and for statements using the Continue statement, as well as satisfying certain conditions. Finally, a for loop is nested within the while loop to form a nested loop in which all the element values in the two-dimensional list are output. In Python statements, nested loops can nest any number of loops.

x = 0while x < 100:                              # 开始while循环    if x == 5:                              # 当x == 5时终止循环        break;    print(x, end=" ")     x += 1names = ["Bill", "Mike", "Mary"]            # 定义一个列表变量print("\nbreak语句在for循环中的应用")for name in names:                          # 对names列表进行迭代    if not name.startswith("B"):                # 遇到列表元素值不是以B开头的,就终止for循环        break;    print(name)print("break语句在for循环中的应用")for name in names:                          #  对names列表进行迭代    #  遇到列表元素值以B开头的,会跳过本次循环,继续执行下一次循环    if name.startswith("B"):                continue;    print(name, end=" ")print("\n嵌套循环")arr1 = [1,2,3,4,5]arr2 = ["Bill", "Mary", "John"]arr = [arr1, arr2]                          #  定义一个二维列表变量i = 0;while i < len(arr):                     #  使用嵌套循环枚举二维列表中的每一个元素值    for value in arr[i]:        print(value, end = " ")         #  输出二维列表中的元素值    i += 1    print()

The program runs as shown in the results.

"Python from rookie to Master" has been published, began to serial, buy send video lessons

Python from rookie to Master (10): Loop

Related Article

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.