Programs are generally executed in order. The programming language provides various control structures, allowing for more complex execution paths. The loop statements in Python have for and while but no do while
Loop statements allow us to execute a statement or statement group multiple times. The following is the general form of loop statements in most programming languages:
Python provides for loop and while loop (there is no do while loop in Python)
Cycle type | Description |
---|---|
[ while loop] "Python WHILE loop") | Execute the loop body when the given judgment condition is true, otherwise exit the loop body. |
[ for loop] "Python FOR loop") | Execute statement repeatedly |
[ Nested loop] "Python loop full set") | You can nest for loops in the body of the while loop |
The while statement in Python programming is used to execute a program in a loop, that is, to execute a program in a loop under certain conditions to handle the same task that needs to be processed repeatedly. The basic form is as follows:
Gif demonstrates the execution of Python while statement
A little more complicated
Example1
count =0while(count <9):print(count,"The count is:"),count
count = count +1print('Good bye!')0 The count is:1 The count is:2 The count is:3 The count is:4 The count is:5 The count is:6 The count is:7 The count is:8 The count is:
Good bye!
In the While statement, there are two other important commands continue, breadk to skip the loop, continue is used to skip the loop, break is used to exit the loop, and the "judgment condition" can also be a constant value, which means the loop must be established. , The specific usage is as follows:
count =0while(count <9):
count = count +1if count%2>0: #Skip output when not even
continueprint(count)print('Good bye!')
count =0while(count <9):
count = count +1if count >4: #Jump out of the loop when count is greater than 4.breakprint(count)print('Good bye!')
Infinite loop
var=1whilevar==1:
num =input('Enter a number ')print("You enterd:",num)print("Good bye!")
You enterd:
Enter a number
You enterd:
Enter a number
You enterd:
Enter a number
You enterd:
Enter a number
You enterd:
Enter a number
Loop using the else statement
count =0while count <5:print(count," is less than 5")
count = count +1else:print(count," is not less than 5")0 is less than 51 is less than 52 is less than 53 is less than 54 is less than 55 is not less than 5
Simple statement group
flag =1while(flag):print('Given flag is really true!')print("Good bye!")
Python for loop can facilitate any sequence of items, such as a list or a string
for iterating_var in sequence:statements(s)
for letter in'python':print('Current letter:',letter)
fruits =['banana','apple','mango']for fruits in fruits:print('Current fruit:',fruits)print("Good bye!")
# The results of the current instance operation are:
Current letter: p
Current letter: y
Current letter: t
Current letter: h
Current letter: o
Current letter: n
Current fruit: banana
Current fruit: apple
Current fruit: mango
Good bye!
fruits =['banana','apple','mango']for index inrange(len(fruits)):print('Current fruit:',fruits[index])print("Good bye!")
Current fruit: banana
Current fruit: apple
Current fruit: mango
Good bye!
# In the above example, we used the built-in function len()And range()Function len()Returns the length of the list, that is, the number of elements, range returns the number of a sequence.
Loop using the else statement** In python, for …else means this. The statement in for is no different from ordinary. The statement in else will be executed normally in the loop (that is, for is not interrupted by breaking out of break) ), the same is true for while… else. **
for i inrange(5):print(i)
# You can also use range to specify the value of the interval:for i inrange(5,9):print(i)5678
# You can also make the range start with a specified number and specify a different increment(It can even be negative, sometimes this is also called'Stride'):for i inrange(0,10,2):print(i)02468
# Can also be combined with range()And len()Function to traverse the index of a sequence,as follows:
a =['Google','Baidu','360','JinDong']for i inrange(len(a)):print(i,a[i])0 Google
1 Baidu
23603 JinDong
# You can also use range()Function to create a list
a=list(range(5))print(a)[0,1,2,3,4]
Break execution flow chart
Continue execution flowchart
Code execution process
**The Break statement can jump out of the for and while loops. If you terminate from a for or while loop, any corresponding else block will not be executed. The **Continue statement is used to tell Python to jump out of the remaining statements in the current loop block, and then Continue to the next cycle
Example****Use Break in While
n =5while n >0:
n -=1if n ==2:breakprint(n)print('End of loop')43
End of loop
Use continue in Whie
n =5while n >0:
n -=1if n ==2:continueprint(n)print('End of loop')4310
End of loop
for loop uses break and continue
for i in'YouMen':if i =='M':breakprint('The current letter is:',i)print('----------------------')for i in'YouMen':if i =='M':continueprint('The current letter is:',i)
The current letter is: Y
The current letter is: o
The current letter is: u
----------------------
The current letter is: Y
The current letter is: o
The current letter is: u
The current letter is: e
The current letter is: n
Python pass is an empty statement, in order to maintain the integrity of the program structure Pass does nothing, and is generally used as a placeholder statementThe smallest class****The syntax format of the Python language pass statement is as follows
pass
# Example
for letter in'python':if letter =='h':
pass
print('This is the pass block')print("Current letter:",letter)print("Good bye!")
# The result of the above example is:
Current letter: p
Current letter: y
Current letter: t
This is the pass block
Current letter: h
Current letter: o
Current letter: n
Good bye!
Exapmle's smallest class
classMyEmptyClass:
pass
Example1 Print a prime number
for num inrange(10,20):for i inrange(2,num):if num%i ==0:
j=num/i
print("%d is equal to%d * %d"%(num,i,j))breakelse:print(num)10 equals 2*51112 is equal to 2*61314 equals 2*715 equals 3*516 equals 2*81718 is equal to 2*919
Example2 Calculate the first 20 numbers within 1000 that are divisible by 7
count =0for i inrange(0,1000,7):print(i)
count +=1if count >=20:break
Example3 Given a positive integer with no more than 5 digits, determine how many digits it has, and print the number in turn, tens digit, hundreds digit, thousands digit. Ten thousand digit
Print isosceles triangle
rows =10for i inrange(0, rows):for k inrange(0, rows - i):print("*",end="") #Pay attention to here",", Must not be omitted, it can play the role of not wrapping
k +=1
i +=1print()
Print hollow diamond
rows =10for i inrange(rows):for j inrange(rows - i):print(" ", end=" ")
j +=1for k inrange(2* i -1):if k ==0 or k ==2* i -2:print("*", end=" ")else:print(" ", end=" ")
k +=1print("\n")
i +=1
# The lower part of the rhombus
for i inrange(rows):for j inrange(i):
# (1, rows-i)print(" ", end=" ")
j +=1for k inrange(2*(rows - i)-1):if k ==0 or k ==2*(rows - i)-2:print("*", end=" ")else:print(" ", end=" ")
k +=1print("\n")
i +=1
Recommended Posts