(1) while loop
#当某个条件成立时, always perform an action with the following syntax:
while conditional expression:
Loop code
#条件表达式结果为True的时候 Loop code is always executed
#知道条件表达式结果为False
while True:
if (input(' input is a? ') = =' A '):
Break
Note: The above code is a dead loop, and the program is terminated only when you enter a.
#简单打印出1到100数字
Cur= 1
whileCur<= -:
Print(cur)
Cur += 1
#打印所有学生信息 [' Mike ', ' Jack ', ' Luoqian ', ' Chenzi ', ' Liqian ']
ARR1 = [' MikE ',' Jack ',' Luoqian ',' Chenzi ', ' Liqian ']
I=0
whileI< Len(ARR1):
Print(Arr1[i])
i +=1
(2) forCycle
#打印所有学生信息 [' Mike ', ' Jack ', ' Luoqian ', ' Chenzi ', ' Liqian ']
arr1 = [' Mike ',' Jack ', 'Luoqian ',' Chenzi ',' Liqian ']
for Stu in arr1:
Print (Stu) #stu就代表列表中的元素
Note: The above two examples show that the while loop requires a variable, which requires a self-increment of 1.
Add: Python2 range xrange The difference between the two
The #range function returns a list, and xrange is like a generator
#如果需要遍历一个很庞大的数字范围, with Xrange, because it saves memory
Range in #Python3 similar to xrange in Python2
for stu in range (1 , 101 , 10 ):
# package left not packet right, take 1 to 100, followed by 10 is the number of steps, that is, every 10 digits print once
#打印结果为: 1,11, ...
print (stu)
Note: If the number of steps is negative
for stu in range ( 101 , 1 , -10 ):
#打印结果为: 101, he, Bayi, ...
print (Stu)
(3 ) break statement: This layer loops over the specified condition and no longer loops back, if there are other outer or inner loops that do not affect
Sumdata = 0
for i in range(1, 101):
Sumdata += I
if i = = :
Break #结束本层循环
Print (Sumdata)
(4) contiune statement: The end of the cycle, after the next cycle, if there are other outer or inner loop does not affect
(5) Notes
#注释方法一: Use "#"
#注释方法二: Multiple lines of comment with three quotation marks ""
#注释方法三: Comment for function
def Fun ():
#函数的属性
"This is Doc"
Print ("Function! ")
Print (fun.__doc__)
#打印后会显示里面的 the "This is Doc" property explains
Python Basics 4 (looping and commenting)