More , Please visit mine Personal blog .
What is a circular statement ? Let's take a look at the following flow chart .
When a program executes a loop statement , If the execution result is true , Then execute the statement 1; then , Program return , Continue to execute the loop statement , Until the execution result of the loop statement is false , The program will jump out of the loop , Execute statement 2, And then the program ends .
In this flowchart , We can see , If the execution result of the loop statement is always true , that , The program will loop through the statements 1, Unless memory overflows , Application error ; otherwise , The program never stops .
Just like a ninja Yixie Nami released by the weasel God in Naruto , Cycle forever , Until a breakthrough is found .
Python There are two kinds of loop statements for , One is while
, The other is for
.
while
The form of the statement is as follows :
while Judge the condition :
sentence 1
else:
sentence 2
If the judgment condition is true , Then execute the statement 1; otherwise , Execute statement 2.
The following example , It's circular computation 1+2+3…+100
n = 100
sum = 0
counter = 1
while counter <= n:
sum = sum + counter
counter += 1
print("1 To %d The sum is : %d" % (n,sum))
We can set the conditional expression to be always true , To achieve infinite loops .** Infinite loop real-time requests on the server are very useful .** Here is an example :
var = 1
while var == 1 :
# The expression is always true
strInput = input(" Please enter :")
print (" What you input is : ", strInput)
print (" end ")
for
The form of the statement is as follows :
for Variable in Sequence :
sentence 1
else:
sentence 2
Ergodic sequence , Get element item , And execute the statement 1; When the traversal ends , Execute statement 2.
The following example , Traverse the list , And print the element items of the list :
fruits = [' grapes ', ' watermelon ', ' Banana ', ' Apple ']
for ft in fruits:
print(ft)
There are three more important statements in the loop statement :break
、continue
、pass
.
break
It means to jump out of the whole cycle immediately , No more statements in the loop .
continue
It means to jump out of this cycle immediately , Do not execute the remaining statements in this loop , But it will continue to execute the next loop code .
pass
It's an empty statement , In order to maintain the integrity of the program structure . It doesn't do anything , Equivalent to a placeholder statement .
exercises 1:
use while Statement to print out the 99 multiplication table .
exercises 2:
A four digit number abcd, Satisfy abcd * 4 = dcba, Find this number .
Official account : Pangao will accompany you to learn programming , reply 017, Get the answer to the exercise .