python之while/for循环

 一、while循环

(一)循环语句

while 后面接判断语句,在返回结果时有以下几种语句:

1、break

仅适用于循环语句,意思是结束最近的循环

2、continue

仅适用于循环语句,意思是跳到最近的循环首行

3、pass

空占位语句

4、else

不满足循环的判断条件时执行同级别的else语句

可通过执行一下猜错语句感受break与continue的区别

_uesr = 'yangdanhua'
_password = '123456'
count = 0
while True:
    user = input('username:')
    password = input('password:')
    if user == _uesr and password == _password:
        print ('welcome to {my} world'.format(my = user) )
        break
    else:
        print ('Invaild')
        count +=1
        if count == 3:
            count_panduan = input('Do you want to try again? (N/Y)')
            if count_panduan == 'y':
                count = 0
                continue
            else:
                print ('see you')
                break

pass与else详见:

a = input('please input num1:')
b = input('please input num2')
while a>b:
    pass
else:
    print ('can not meet the condition')

 二、for循环

for循环一般是通用的迭代器,可用于字符串、列表、元组、其他内置可迭代对象预计通过类创建的新对象

一般格式: for <target> in <object>:

同样支持附带else块

eg:

for i in range(0,100,2):    #每隔1位输出一次
    print ('-------------',i)
else:
    print ('stop')

i从0循环到99,输出“---------n”样式共100个结果

还可以用于把对象元素赋值给目标

也可用作输出字典

猜你喜欢

转载自www.cnblogs.com/hhdw/p/9471769.html