基础补充(四)——流程控制

 流程控制

一、流程控制之if……else……

  if 条件1:

    缩进的代码块

  elif 条件2:

    缩进的代码块

  elif 条件3:

    缩进的代码块

  ......

  else:  

    缩进的代码块

二、流程控制之while……循环

1. 为了不写重复代码,而且程序可以重复执行多次

2. while循环语法

while 条件:    
    # 循环体
 
    # 如果条件为真,那么循环体则执行,执行完毕后再次循环,重新判断条件。。。
    # 如果条件为假,那么循环体不执行,循环终止
#打印0-10之间的偶数
count=0
while count <= 10:
    if count%2 == 0:
        print('loop',count)
    count+=1
while循环示例

3. 循环嵌套与tag

tag=True 

while tag:

  ......

  while tag:

    ........

    while tag:

      tag=False
#练习,要求如下:
    1 循环验证用户输入的用户名与密码
    2 认证通过后,运行用户重复执行命令
    3 当用户输入命令为quit时,则退出整个程序 
#实现一:
name='egon'
password='123'

while True:
    inp_name=input('用户名: ')
    inp_pwd=input('密码: ')
    if inp_name == name and inp_pwd == password:
        while True:
            cmd=input('>>: ')
            if not cmd:continue
            if cmd == 'quit':
                break
            print('run <%s>' %cmd)
    else:
        print('用户名或密码错误')
        continue
    break



#实现二:使用tag
name='egon'
password='123'

tag=True
while tag:
    inp_name=input('用户名: ')
    inp_pwd=input('密码: ')
    if inp_name == name and inp_pwd == password:
        while tag:
            cmd=input('>>: ')
            if not cmd:continue
            if cmd == 'quit':
                tag=False
                continue
            print('run <%s>' %cmd)
    else:
        print('用户名或密码错误')
View Code

4、while……else……

与其它语言else 一般只与if 搭配不同,在Python 中还有个while ...else 语句,while 后面的else 作用是指,当while 循环正常执行完,中间没有被break 中止的话,就会执行else后面的语句

count = 0
while count <= 5 :
    count += 1
    print("Loop",count)

else:
    print("循环正常执行完啦")
print("-----out of while loop ------")
输出
Loop 1
Loop 2
Loop 3
Loop 4
Loop 5
Loop 6
循环正常执行完啦
-----out of while loop ------

#如果执行过程中被break啦,就不会执行else的语句啦
count = 0
while count <= 5 :
    count += 1
    if count == 3:break
    print("Loop",count)

else:
    print("循环正常执行完啦")
print("-----out of while loop ------")
输出

Loop 1
Loop 2
-----out of while loop ------
View Code

注意:while中一般会有一个count用来计数

三、流程控制之for循环(迭代式循环)

1、for循环语法

for i in range(10):

    缩进的代码块

2、打印九九乘法表

for i in range(1,10):
    for j in range(1,i+1):
        print("%s * %s = %s"%(i,j,i*j),end='')
    print()
九九乘法表

四、break与continue

#break用于退出本层循环
while True:
    print "123"
    break
    print "456"

#continue用于退出本次循环,继续下一次循环
while True:
    print "123"
    continue
    print "456"

猜你喜欢

转载自www.cnblogs.com/linagcheng/p/9570746.html