Python流程控制与while 循环(day01)

一:流程控制

假如把写程序比做走路,那我们到现在为止,一直走的都是直路,还没遇到过分叉口,想象现实中,你遇到了分叉口,然后你决定往哪拐必然是有所动机的。你要判断哪条叉路是你真正要走的路,如果我们想让
程序也能处理这样的操作,那么设一些条件判断语句,满足哪个条件,就执行相对应的操作。

单分支

if  条件:
   满足条件执行后的代码

如:if  a > b:
          print(“hello”)

双分支

if  条件:
    满足条件执行后的代码
else: 
     不满足条件执行的代码

如: 
if   a > b:
     print("hello")
else:
     print("no")

多重分支判断:

if    条件1:
       满足条件1执行的代码:
elif  条件2:
        满足条件2执行的代码:
elif  条件3:
      满足条件3执行的代码:
        
else:
      以上条件都不满足执行的代码

如:
grade = int(input("请输入成绩: "))

if    grade == 100:
      print("S")
elif  grade >= 90:
       print("A")
elif  grade >= 80:
       print("B")
elif   grade >= 70:
       print("C")
else:
        print("D")

多重条件判断

两个条件都满足
if     条件1   and  条件2:
       两者都满足后执行的条件
如:

if    a  > b and a <=c:
      print("hello")

两个条件二选一
if     条件1   or  条件2:
       两者只要满足一个条件都会执行
如:

if    a  > b or a <=c:
      print("hello")

注:if 可以多重嵌套,注意每层之间的缩进。

二: while循环

通过循环语句可以让代码重复执行多次,while 指当后面的条件成立,就执行while下面的代码

格式:

定义一个计数器,
count = 0 

while 条件:
         满足条件后执行的代码

注:这里的条件可以为 count <3 也可以为True,代表为真,下方的代码会一直执行

如:
我们让程序从 0 打印到100
count = 0

while  count <=100:
          print("loop",count)
          count +=1         每执行一次,就把count+1,要不然就变成死循环了,因为count一直为0

打印1到100的偶数

注:能被2整除的都是偶数
count = 0 

while  count <=100:
           if  count %2 = 0:
               print("loop",count)
            count += 1

循环中止语句
如果在循环的过程中,因为某些原因,你不想继续执行循环了,怎么把他中止呢?这就用到break 或 continue语句:

break : 完全结束一个循环,跳出循环体执行循环后面的语句
continue: 与break类似,区别在于continue 只是终止本次循环,接着还执行后面的循环,break则完全终止。
sleep : 让程序睡眠 n秒后再执行

例子:

count = 0
 
while count <=100:
         print("loop",count)
         if  count == 5:
              break
         count +=1

当count = 5的时候,循环将会结束

例子2:

count = 0
while count <= 100:
         count +=1
         if  count > 5  and count <95:
             continue
         print("loop",count)
print("----out of while loop----")

只有count 在 6-94之间,就不走下面的print语句,直接进入下一次loop。
while 还有一种语句

while 条件:
执行的代码:
else:
循环执行完后执行的语句

注: 当循环被break后,就不会执行else 处的语句。

猜你喜欢

转载自www.cnblogs.com/bingguoguo/p/10163264.html