Python basic notes 7

Python basic syntax 7

In the Python world, two loop statements are provided, for…in loop statement and while Loop statement.

for…in loop

1. for…in loop structure

for i in [1,2,3,4,5,6]:  #注意冒号“:”,不要丢掉
    print(str(i)+'取钱')  #注意循环体前面要缩进

There is a group of people queuing up to withdraw money in the structure, which is a list[1,2,3,4,5,6], When each of them is called(for i in), they begin to take turns to withdraw money.
Every time a person enters, they will give their number to the computer and then say "withdraw money", that is, print(str(i)+"withdraw money") , and finally computers provided services for everyone.

  • The for loop has three main points:
    1. A group of people waiting to withdraw money
    2. Calling number
    3.Service process

After the loop endsi stores the value of the last element
Sunflower Collection: Strings, lists, and dictionaries can all be "a group of people queuing up to withdraw money"

In addition to the three data types of string, list, and dictionary, we can also traverse in combination with other data.

2. range() function

for loop is often used together with the range() function.

for i in range(5):
    print(i)
for i in range(5,10):
    print(i)
for i in range(0,10,2):
    print(i)

Output:
0 1 2 3 4
5 6 7 8 9
0 2 4 6 8< /span>

  • Instructions:
    1. Use the range(n) function to generate a range from The sequence of integers from a>0 ton-1.
    2. Using the range(x,y) function, you can generate the range from The sequence of integers from x toy-1.
    3. Use the range(0,n,step) function: you can generate from 0 ton-1, the interval between numbers is step integer sequence.

The proper name of the service processfor loop body: The format iscolonThen start a new line,indentationwrite command

while loop

1. while loop structure

x = 0
while x < 6:
    x = x+1
    print(x)
  • The while loop only requires two steps:
    1. Set conditions
    2. Work process
  • The while loop means "when" in English. While is followed by a condition. When the condition is met, the loop body inside the while will be executed.

In the above example, as long as the condition x<6 is met, x=x+1 will be executed continuously, and print(x+1) will be printed out. When the condition is not met, the service process will be stopped.
while sets the condition: the following loop body statements must be indented. Only when indented is the loop body of the while loop, which can be executed over and over again.

Comparison between for loop and while loop

  • Both the for loop and the while loop can repeat one thing N times
  • The for loop is suitable for situations where the number of loops is clear
  • while loop is suitable for situations where the number of loops is unclear

Previous article:Python basic notes 6
Next article:Python basic notes 8 a>

Guess you like

Origin blog.csdn.net/weixin_44131612/article/details/129133313