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 in :

同样支持附带else块

eg:

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

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

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

也可用作输出字典

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值