cycle
- Can execute the same thing multiple times ###while loop
whileCondition: Something to be done repeatedlyCopy the code
- Example 1: Print 10 times I like you
i = 1
while i <= 10:# loop condition
print("I like you.")
i+=1# I is incremented by 1 each time through the loop. Until I is equal to 11, it doesn't satisfy the loop condition. Cycle to stop
Copy the code
The above code runs as follows:
The while loop is nested
- There’s a while loop inside a while loop
i = 1# Control the outside while loop
while i <= 9:
j = 1# Control the while loop inside
while j <= i:#while loop inside a while loop
print("%d*%d=%d"%(j,i,i*j),end="\t")# add an end to print without newlines
j+=1
print("")# print empty for line feed
i+=1
Copy the code
The above code runs as follows:
Infinite loop
- It goes on and on and on
while True: Something to do over and over againCopy the code
The for loop
- Like the while loop, for can also be a loop. Simpler than while
for i inStrings, tuples, lists, ranges (): Things to do over and over againelse: The loop condition is not metCopy the code
- Loop over the string
name = "python"
for i in name:
print(i)# prints every character in the string
Copy the code
The above code runs as follows:
-
With the range (start, end, step)
- Start: the start value. The loop includes the start value
- End: Termination value, loop does not include termination value
- Step: step length
-
Step 1
for i in range(1.5.1) :# Start value :1 End value :5 Step size :1
print(i)
Copy the code
The above code runs as follows:
- Step 2
for i in range(1.5.2) :# Start value :1 End value :5 Step size :2
print(i)Print every 2
Copy the code
The above code runs as follows:
The for loop is nested
- There’s a for loop inside a for loop
for i in range(1.10) :The default step size is 1
for j in range(1,i+1) :# I is 9 at most, 9 times 9 so I have to add 1
print("%d*%d=%d"%(j,i,i*j),end="\t")
print("")# a newline
Copy the code
The above code runs as follows:
Break and continue
- Can only be used in loops, break to end a loop
- Used only in loops, continue terminates the current loop, followed by the next loop
- break
for i in range(1.10) :if i == 6:# The loop ends when I is equal to 6
break
print(i)
While I < 10: if I == 6: break print(I) I +=1"
Copy the code
The above code runs as follows:
- continue
for i in range(1.10) :if i == 6:# loop this loop when I is equal to 6, and then the next loop
continue
print(i)
While I < 9: I +=1 if I == 6: continue print(I)"
Copy the code
The above code runs as follows: