Second, Continue/break usage and difference:
Continue and break are used to control the loop structure, mainly to stop the loop
1. Break: End the entire loop body
Sometimes we want to terminate a loop when a condition arises, rather than wait for the loop condition to be false, and then we can do it with a break, which is used to completely end a loop and jump out of the loop body to execute the subsequent statement.
2, continue: End a single cycle
Continue and break are somewhat similar, except that continue terminates the loop, and then executes the subsequent loop body, and break terminates the loop completely.
It can be understood that continue is jumping out of the remaining statements in the secondary loop, performing the Next loop
3. Example:
I=1
While I < 10:
i + = 1
If i%2 > 0: #非双数时跳过输出
Continue
Print I #输出双数2, 4, 6, 8, 10
I=1
While 1: #循环条件为1必定成立
Print I #输出1 ~
I+=1
If I >: #当i大于10时跳出循环
Break
Third, Case practice
1. Simple while loop (infinite loop)
Count = 0
While True:
Print ("Count:", count)
Count + = 1
2, while loop guessing age, guess right after the end of the loop
My_age = 25
While True:
guess_age = Int (Input ("Age:"))
if guess_age = = My_age:
Print ("Yes,you got It!")
Break
Elif guess_age > My_age:
Print ("Bigger ...")
Else
Print ("smaller ...")
3, while judging three times to exit
Method One:
My_age = 25
Count = 0
While True:
if Count = = 3:
Print ("Your guess just only 3 times")
Break
guess_age = Int (Input ("Age:"))
if guess_age = = My_age:
Print ("Yes,you got It!")
Break
Elif guess_age > My_age:
Print ("Bigger ...")
Else
Print ("smaller ...")
Count + = 1
Method Two:
My_age = 25
Count = 0
While Count < 3:
guess_age = Int (Input ("Age:"))
if guess_age = = My_age:
Print ("Yes,you got It!")
Break
Elif guess_age > My_age:
Print ("Bigger ...")
Else
Print ("smaller ...")
Count + = 1
if Count = = 3:
Print ("Your guess just only 3 times")
Method Three: (The optimized version while loop uses the Else statement)
My_age = 25
Count = 0
While Count < 3:
guess_age = Int (Input ("Age:"))
if guess_age = = My_age:
Print ("Yes,you got It!")
Break
Elif guess_age > My_age:
Print ("Bigger ...")
Else
Print ("smaller ...")
Count + = 1
Else
Print ("Your guess just only 3 times")
Python-while Loop Statement-007