[Introduction to Python] Python loop statement (basic syntax of for loop)

insert image description here
foreword


1. Basic grammar of for loop

1.1 for loop

In addition to the while loop statement, Python also provides a for loop statement.
The functions that can be completed by the two are basically the same, but there are still some differences:

  1. The loop condition of the while loop is custom, control the loop condition by yourself
  2. The for loop is a "polling" mechanism that "processes" a batch of content one by one

The for loop is a loop mechanism that completes the "to-do items" one by one

1.2 for loop in the program

for 临时变量 in 待处理数据集: 
        循环满足条件时执行的代码

From the data set to be processed: take out the data one by one and assign them to temporary variables

1.3 for loop statement

iterate over the string

# 定义字符串name
hopy = ”reaipaobu”
# for循环处理字符串
for x in hopy: 
       print(x)

The result of the operation is as follows:

r
e
a
i
p
a
o
b
u

It can be seen that the for loop is the content of the string:Take out one by one
So, the for loop is also called:loop through

1.4 For loop attention points

# 定义字符串name
name = ”itheima”
# for循环处理字符串
for x in name: 
       print(x)

Unlike the while loop, the for loop cannot define loop conditions.
The content can only be taken out sequentially from the processed data set for processing.

Therefore, in theory, Python's for loop cannot build an infinite loop (the data set being processed cannot be infinitely large)

1.5 Summary

  1. The syntax for a for loop is:insert image description here
  2. Notes on for loop
  • Unable to define loop conditions, only passive data processing
  • It should be noted that the statements in the loop need to be indented with spaces

1.6 Practice case: count how many a

Define the string variable name, the content is: "iheima is a brand of itcast"
Through the for loop, traverse this string, and count how many English letters there are: "a"
Tip:

  1. Counting can define an integer type variable outside the loop for cumulative counting
  2. Judging whether it is the letter "a" can be done by combining the if statement with the comparison operator

Exercises demonstrating for loops:count how many a

# 统计如下字符串中,有多少个字母a
name = "reaipaobu is a brand of itcast"

# 定义一个变量,用来统计有多少个a
count = 0

# for 循环统计
# for 临时变量 in 被统计的数据:
for x in name:
    if x == "a":
        count += 1

print(f"被统计的字符串中有{
      
      count}个a")

Code result:

There are 5 a's in the counted string.

2. range statement

2.1 Explanation of range statement

or 临时变量 in 待处理数据集(可迭代对象): 
        循环满足条件时执行的代码

In the grammar: data set to be processed, strictly speaking, it is called: iterable type
Iterable type refers to a type whose contents can be taken out one by one, including:

  • string
  • the list
  • tuple
  • wait

At present, we have only studied the string type, and the rest of the types will be studied in detail in subsequent chapters
. For loop statements are essentially traversal: iterable objects.
Although other iterable types are not currently learned except strings, it does not prevent us fromObtain a simple sequence of numbers (a type of iterable) by learning the range statement
Syntax 1:
Obtain a sequence of numbers starting from 0 and ending with num (excluding num itself).
The data obtained by range(5) is: [0, 1, 2, 3, 4]
as shown in the code:

# range语法1 range(num)
for x in range(10):
    print(x)

Code result:

0
1
2
3
4
5
6
7
8
9

Grammar 2:
Obtain a sequence of numbers starting from num1 and ending with num2 (excluding num2 itself)
. For example, the data obtained by range(5, 10) is: [5, 6, 7, 8, 9]
as shown in the code:

# range 语法2 range(num1, num2)
for x in range(5, 10):
#     # 从5开始,到10结束(不包含10本身)的一个数字序列,数字之间间隔是1
    print(x)

Code result:

5
6
7
8
9

Syntax 3:

Obtain a step size between numbers starting from num1 and ending with num2 (excluding num2 itself) , based on step (step defaults to 1)
. For example, the data obtained by range(5, 10, 2) is: [5, 7, 9]
The code shows:

# range 语法3 range(num1, num2, step)
for x in range(5, 10, 2):
#     # 从5开始,到10结束(不包含10本身)的一个数字序列,数字之间的间隔是2
    print(x)

Code result:

5
7
9

2.2 The for loop traverses the range sequence

insert image description here
The result of the operation is as follows:
insert image description here

2.3 Summary

  1. The function of the range statement is:
    to obtain a sequence of numbers (one of the iterable types)
  2. The syntax format of the range statement:
    Syntax 1:
    Syntax 2:
    Syntax 3:
  3. Notes on the range statement:
  • Syntax 1 starts from 0 and ends with num (excluding num itself)
  • Grammar 2 starts from num1 and ends with num2 (excluding num2 itself)
  • Syntax 3 starts from num1 and ends with num2 (excluding num2 itself), the step size is based on the step value

Range has many uses, most of which are used in for loop scenarios

2.4 Exercise case: How many even numbers are there

Define a numeric variable num with random content
and use the range() statement to get the sequence from 1 to num, and use the for loop to traverse it.
In the process of traversal, count how many even numbers appear
prompts:

  1. The sequence can be obtained using: range(1, num)
  2. The even number is judged by if, and it is enough to judge whether the remainder 2 of the number is 0

3. Variable scope

3.1 Thinking

insert image description here

As shown in the code, think about it:
Can the print statement in the red box access the variable i?
Specification: Not allowed
Practically: Yes

3.2 Variable scope of for loop

insert image description here
Looking back at the syntax of the for loop, we will find that the data taken from the data set (sequence) is assigned to: temporary variable
Why is it temporary?

Temporary variables, in terms of programming specifications, scope (scope), only limited to inside the for loop

If the temporary variable is accessed outside the for loop:

  1. actually accessible
  2. In terms of programming specifications, it is not allowed or recommended to do so.

If you really need to access the temporary variables in the loop outside the loop, you can pre-define them outside the loop

insert image description here
As shown in the figure, every time the loop is performed, the value taken out will be assigned to the i variable.

  1. Since the i variable is defined before (outside) the loop
  2. It is reasonable and permissible to access the i variable outside the loop

3.3 Summary

  1. Temporary variables in the for loop, its scope is limited to:
    within the loop
  2. This limitation:
  • It is a limitation of programming specifications, not a mandatory limitation
  • It will work without compliance, but it is not recommended
  • To access a temporary variable, it can be pre-defined outside the loop

Guess you like

Origin blog.csdn.net/m0_75058342/article/details/130140176