for语句执行的是有限循环,必须输入循环的次数
while语句是无限循环 语法结构:
while <condition>: <body>condition是布尔表达式
body是一条或多条语句 当condition为真时循环体重复执行 当条件为假时循环体中止运行
while循环总是在循环顶部被判断,即在循环体中止之前,这种结构又被称作前侧循环
break跳出所有循环 continue的作用是结束本次循环。即跳出循环体中下面尚未执行的语句。对于while循环,则继续求解循环条件。而对于for循环程序流程接着遍历循环列表
continue语句与break语句的区别 continue语句,其作用为结束本次循环。跳出循环体下面尚未执行的语句,对于while循环则继续求解其循环条件。 continue只结束本次循环而不结束整个循环。 break则结束整个循环过程而不再执行循环条件
交互式循环 随时询问是否继续输入数据,无需自己计数 哨兵循环 执行循环直到遇到特定的值,才会中止 后测循环
number=-1 while number<0: number=eval(input("enter a positive number:")设定一个初始值,让循环至少执行一次,相当于后测循环 break语句实现后测循环
while true: number=eval(input("enter a postive number:") if x>0:break #如果数字有效则跳出循环需要注意的是如果if语句只包含一个条件可以写在同一行 后测循环代码1
number=-1 while number<0: number=eval(input("enter a postive number:")) if number<0: print("number you get is not postive")后测循环代码2
while true: number=eval(input("enter a postive number:") if x>=0: break#跳出所有循环 else: print("the number you get is not postive")需要注意的是此时while true是对所有条件都是成立,由于while可以无限循环必须需要加入Break才可中止循环,否则将陷入死循环