In process control, it is inevitable that there will be some repetitive work, such as copying 100 variables, printing every element in the list, etc.,...
Python Basics - Loop Statements
Published: 2025-07-21 (a year ago)
Python

In process control, it is inevitable that there will be some repetitive work, such as copying 100 variables, printing every element in the list, etc., if we have to operate every sentence by ourselves, the workload is very large

r[-1] # takes the last element, which is done on top of range(0,20,2).

In Python, there are two loop statements, 'while' and 'for', the principle of the two is similar, first judge the condition, execute the statement in the loop if the condition is true, then judge whether the condition is true, and execute the statement in the loop again until the condition is not true

While loop

Syntax

In Python programming, the while statement is used to execute a program in a loop, that is, under certain conditions, a certain segment of the program is executed in a loop to handle the same task that needs to be processed repeatedly. Its basic form is:

Python Copy
while condition is met:
Statement 1...
else:
The statement to be executed after the loop is complete

An execution statement can be a single statement or a block of statements. The judgment condition can be any expression, and any non-zero or non-null value is true

When the judgment condition is False, the loop ends

Dead Loop

When the condition is always true, it will continue to cycle, and it will always be in the loop, and the statement that cannot get out of the cycle is called "dead loop" or "infinite loop"

Python Copy
# The simplest dead loop statement
while True:
print('It's a dead loop')

Cycle through else statements

In python, while ... else executes the else statement block when the loop condition is false:

Python Copy
count = 0
while count < 5:
print (count, " is  less than 5")
count = count + 1
else:
print (count, " is not less than 5")

When the condition is true, execute the first print statement, then count+1 until the count is added to 5, and if the condition is not satisfied, execute the print statement under else

It can be used to determine whether the loop structure is over

Simple statement sets

Similar to the syntax of an if statement, if you have only one statement in your while loop, you can write that statement on the same line as while, like this:

Python Copy
flag = 1
while (flag): print 'Given flag is really true!'
print "Good bye!"

Use the while loop to calculate the value of 1+2+......+99+100:

Python Copy
i=1
sum=0
while i<=100:
sum+=i
i+=1
print(sum)
# 5050

for loop

It is commonly used to iterate through sequence types such as strings, lists, tuples, dictionaries, collections, etc., to obtain individual elements in the sequence one by one

The syntax format for loop is as follows:

Python Copy
for iterative variable in string|list|tuple|dictionary|collection:
Code blocks

In format, iterative variables are used to store elements read from sequence-type variables, so iteration variables are generally not manually assigned in a loop

A code block is a multi-line code with the same indentation format (like while), which is also called a loop because it is coupled with a loop structure

Python Copy
add = "https://www.baidu.com"
#for 循环, iterate through the add string
for ch in add:
print(ch,end="")
# Output: https://www.baidu.com

As you can see, when using a for loop to traverse the add string, the iterative variable ch is assigned to each character in the add string and substituted into the loop. However, the loop body in the example is relatively simple, with only one output statement

Implement the calculation of values of 1+2+......+99+100

Python Copy
print("The result of calculating 1+2+...+100 is:")
#保存累加结果的变量
result = 0
#逐个获取从 these values from 1 to 100 and add them up
for i in range(101):
result += i
print(result)
# The result of calculating 1+2+...+100 is:
# 5050

At this time, an unfamiliar function appeared in our code - the range( ) function

Use of range( ).

In the above code, the range() function is used, which is a Python built-in function used to generate a series of continuous integers, mostly used in for loops

We just need to understand that the range() function can be iteratively generated

for loop through lists and tuples

When a list or tuple tuple is iterated through a for loop, its iterative variables are assigned to each element in the list or tuple and execute the loop once

Python Copy
# Traverse the list
my_list = [1,2,3,4,5]
for ele in my_list:
     
print('ele =', ele)

ele = 1
ele = 2
ele = 3
ele = 4

ele = 5

Python Copy
# Traverse the tuple
my_list = (1,2,3,4,5)
for ele in my_list:
     
print('ele =', ele)

You can see that the results are exactly the same for both

ele = 1
ele = 2
ele = 3
ele = 4

ele = 5

for Loop through the dictionary

When using a for loop to traverse a dictionary, three dictionary-related methods are often used, namely items(), keys(), and values(), each of which has been discussed in the previous section and will not be repeated here. Of course, if you use a for loop to traverse the dictionary directly, the iterative variables will be assigned to the keys in each key-value pair.

Python Copy
dic={'name':'Xiao Ming','age':22,'score':100}
for di in dic:
print(di)
# Get the default for each key in the dictionary
for di in dic.items():
print(di)
# Get each set of data in the dictionary, the result of which is a tuple
for di in dic.values():
print(di)
# Get the value corresponding to each set of keys in the dictionary
for di in dic.keys():
print(di)
#得到字典的每一键(key) default

The usage of items( ), keys( ) and values ( ) in the dictionary

items(): Returns an array of tuples that can be traversed (key, value) as a list

Traversal of items() method: The items() method forms a tuple for each pair of key and value in the dictionary and returns it in a list

Python Copy
d = {'one': 1, 'two': 2, 'three': 3}
>>> d.items()
dict_items([('one', 1), ('two', 2), ('three', 3)])


>>> type(d.items())
>>> for key,value in d.items():#当两个参数时
print(key + ':' + str(value))
one:1
two:2

three:3
>>> for i in d.items(): #当参数只有一个时
print(i)
('one', 1)
('two', 2)
('three', 3)

keys(): Returns all keys in a dictionary as a list

values(): Returns all values in a dictionary as a list

for practice

  • Find the sum of even numbers within 1~100
Python Copy
sum = 0
for i in range(2,101,2):
sum += i
print(sum)
  • Find factorials
Python Copy
# Find factorial
num = int(input('Please enter a number:'))
res = 1
for i in range(1, num + 1):
res*=i
print(factorial of '%d:%d' %(num,res))
  • 9*9 multiplication table
Python Copy
for i in range(1,10):
for j in range(1,i+1):
print('%d * %d = %d\t' %(i,j,i*j),end='')
print()
  • Find the greatest common divisor and least common multiple
Python Copy
# Enter two numbers
num1=int(input('Num1:'))
num2=int(input('Num2:'))
# Find the smaller of the two numbers
min_num = min(num1,num2)
# Determine the greatest common divisor
for i in range(1,min_num+1):
if num1 % i ==0 and num2 % i ==0:
max_commer = i
# Find the least common multiple
min_commer =int(num1 * num2)/max_commer
print('%s and %s greatest common divisor is %s' %(num1,num2,max_commer))
print('The minimum common multiple of %s and %s is %s' %(num1,num2,min_commer))

Use of break

Python break statements, like in C, break the minimum closed for or while loop.

The break statement is used to terminate the loop statement, that is, if the loop condition does not have a false condition or the sequence has not been fully recursive, the execution of the loop statement will also be stopped.

The break statement is used in the 'while' and 'for' loops.

If you use nested loops, the break statement will stop executing the deepest loop and start executing the next line of code.


We know that when executing a while loop or for loop, the program will continue to execute the loop body as long as the loop conditions are met. However, in some scenarios, we may want to manually leave the loop before the loop ends, and Pyhton provides 2 ways to force the current loop to leave:

  1. Use the continue statement to skip executing the remaining code in the loop and execute the next loop instead.

  2. Use only the break statement to completely terminate the current loop.

Let's first understand the 'break' statement

In some scenarios, break can be used to accomplish this function if you need to forcibly abort a loop when a condition occurs, rather than waiting until the loop condition is False to exit the loop.

Break is used to completely end a loop and jump out of the loop. Regardless of the loop, once a break is encountered in the loop, the system will completely end the loop and start executing the code after the loop.

This is like running on the playground, originally planning to run 10 laps, but when it comes to the second lap, you suddenly remember that there is an urgent matter to do, so you decisively stop running and leave the playground, which is equivalent to using the break statement to end the loop early.

The break statement is generally used in conjunction with the if statement, indicating that under certain conditions, the break statement will jump out of the current loop, and if a nested loop is used, the break statement will jump out of the current loop.

The syntax of the break statement is very simple, just add it directly to the corresponding while or for statement. For example, the following procedure:

Python Copy
# A simple for loop
for i in range(0, 10) :
print("The value of i is: ", i)
if i == 2 :
# The loop ends when the statement is executed
break

The system ends the loop when i is equal to 2

The break statement causes the execution to end when i==2 because when i==2, a break statement is encountered in the loop and the program jumps out of the loop.

Note that for a loop with an else block, if you use break to forcibly abort the loop, the program will not execute the else block. For example:

Python Copy
# A simple for loop
for i in range(0, 10) :
print("The value of i is: ", i)
if i == 2 :
# The loop ends when the statement is executed
break
else:
print('else block: ', i) # This else statement is not executed

The above program will also jump out of the loop at i==2, and the for loop will not execute else blocks at this time.

In the case of using a break statement, there is a difference between a loop's else block and a loop directly after the loop, i.e., if you place a code block in an else block, the loop will not execute the else block when the program aborts the loop using break; if the code block is placed directly behind the loop body, when the program uses break to abort the loop, the program will naturally execute the code block after the loop.

In addition, for nested loop structures, Python's break statement can only end the loop body in which it resides, but cannot end the outer loop of the nested loop. For example:

Python Copy
for i in range(0,4) :
print("The value of i is:",i)
for j in range(5):
print(" The value of j is:",j)
break
print("Jump out of the inner loop")

It is not difficult to see that every time the inner loop is executed, the first loop will encounter a break statement, that is, do the operation of jumping out of the loop and execute the code of the outer loop instead.

If you want to achieve the goal of not only jumping out of the loop before the single but also jumping out of the outer loop, you can first define a variable of the bool type to indicate whether you need to jump out of the outer loop, and then use two break statements in the inner loop and the outer loop respectively. For example, the following program:

Python Copy
exit_flag = False
# Outer circulation
for i in range(0, 5) :
# Inner Circulation
for j in range(0, 3 ) :
print("i has a value: %d, j has a value: %d" % (i, j))
if j == 1 :
exit_flag = True
# Jump out of the inner loop
break
# If the exit_flag is True, it jumps out of the outer loop
if exit_flag :

break

The above program determines whether j is equal to i in the inner loop, and when j is equal to i, the program sets exit_flag to True and jumps out of the inner loop. Next, the program starts executing the rest of the outer loop, and since exit_flag is true, it will also execute the break statement of the outer loop to jump out of the outer loop.

After the program enters the inner loop from the outer loop, when j is equal to i, the program sets exit_flag to True and jumps out of the inner loop. Next, the program executes the break statement of the outer loop, thus jumping out of the outer loop.

Use of continue

Compared to the break statement, the continue statement is less powerful and will only terminate the execution of the remaining code in the current loop and continue directly from the next loop.
Still taking the operation run as an example, I originally planned to run 10 laps, but when I ran 2 and a half laps, I suddenly received a call, at this time I stopped running, and when I hung up the phone, I did not continue to run the remaining half lap, but started directly from the 3rd lap.

The use of the continue statement is the same as that of the break statement, as long as it is added to the corresponding position in the while or for statement. For example:

Python Copy
add = "https://baidu.com,https://zhihu.com"
# A simple for loop
for i in add:
if i == ',' :
# Ignore the rest of the loop
print('\n')
continue
print(i,end="")
#  https://baidu.com
https://zhihu.com

When the program encounters ',', it skips this cycle and proceeds to the next loop

The role of continue

Combined with exception handling (try), find the exception report and skip the exception

range is used

range syntax

Python Copy
range(start,stop,step)

start: Start
stop: end (stop value is not included)

step: step length

python2.x range() function creates a list of integers, which is commonly used in for loops
Note: Python3 range() returns an iterable object (type is an object), not a list type, so the list will not be printed when printing, please refer to the usage instructions of Python3 range().
print(range(1,100),type(range(1,100)))
# range(1, 100)

We can use the list function to return the list

Python Copy
print(list(range(1,10)))
# [1, 2, 3, 4, 5, 6, 7, 8, 9]

Some examples of range objects

list(range(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
list(range(1, 11))
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
list(range(0, 30, 5))
[0, 5, 10, 15, 20, 25]
list(range(0, 10, 3))
[0, 3, 6, 9]
list(range(0, -10, -1))
[0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
list(range(0))
[]
list(range(1, 0))

[]

The range object implements all operations of the normal sequence, except for splicing and repeating (this is because the range object can only represent sequences that conform to a strict pattern, and both duplication and stitching usually violate such a pattern)

[range] The advantage of the (https://docs.python.org/zh-cn/3/library/stdtypes.html?highlight=range#range) type over the regular 'list' or 'tuple' is that a 'range' object always takes up a fixed amount of (smaller) memory, regardless of the range it represents (because it only holds the 'start', 'stop' and 'step' values, and calculates the values of specific individual items or sub-ranges as needed)

range object implements collections.abc.Sequence ABC, which provides features such as inclusion detection, element index lookup, slicing, and supports negative indexing

Python Copy
r = range(0, 20, 2)
# 0 2 4 6 8 10 12 14 16 18
Copy
>> r
range(0, 20, 2)
>> 11 in r #包含检测
False
>> 10 in r
True
>> r.index(10) # Check the index value according to the content
5
>> r[5] # Check the content value according to the index
10
>> r[:5] # slice returns a new range object in the class
range(0, 10, 2)
18

[while loop] (https://www.wolai.com/jAADGpGH99vaQjNkA15fzF)