1、while循环
while循环,只要条件满足,就不断循环,条件不满足时就退出循环
案例1:
n=10
while n>0
n=n-1
print(n)
print('over!')
案例2:
numbers=[12,37,5,42,8,3]
even=[ ]
odd=[ ]
while len(numbers)>0
number=numbers.pop()
if (number % 2 ==0):
even.append(number)
else:
odd.append(number)
2、while 语句另外两个重要的命令:continue、break 来跳过循环,continue用于跳过该次循环,break则用于退出循环,此外“判断条件”还可以是个常值,表示循环必定成立
#continue 和 break 的用法
举例1:
i = 1
while i < 10 :
i += 1
if i%2 > 0 : #非双数时跳过输出
continue
print(i) #输出双数 2、4、6、8、10
举例2:
i = 1
while 1 :
print i
i += 1
if i > 10 :
break
无限循环
如果条件判断语句永远为true,循环将会无限的执行下去:
举例1:
var = 1
while var == 1 :
num = input("enter a number :")
print ("you entered :", num)
print ("bye")
循环使用else语句
在python中,while.....else 在循环条件为false时执行else语句块;
count = 0
while count < 5 :
print (count,"is less than 5")
count =count + 1
else :
print (count,"is not less than 5")