条件语句和while循环

if语句

if语句后面跟判断语句,多用肯定,少用否定
1.单个条件时:

if ___:
    print('')
 else:
     print('')
  

2.多个条件时:

if ___:
    print('')
elif___:
    print('')
else:
    print('')

三目运算

print(True if a>5 else False)

为真时返回值:True
为假时返回值:False

逻辑运算:and、or、not

1.and:并且、和的意思,当两边都为真时,才会返回真

a=6
if a>3 and a<9:
    print('ok')
else:
    print('no')

2.or:或,只要两边存在真,就会返回真。都是假才会返回假。

a=11
if a>8 or a<2:
    print('ok')
else:
print('no')

3.not:取反,真变假,假变真

a=False
if not a:
    print('ok')
else:
    print('no')

4.三者优先级:not>and>or

not 1==1 and 2==2 and 1==3 or 3==3
→True
not 2==3 and 3==3 or 1==2 and 2==2
→True

代码执行顺序:从左到右,从上到下

5.逻辑短路
1.or

1==1 or a==2
→True

因为左边为真,那么右边的结果对于整体没有影响
2.and

1==2 and a==2
报错

and运算必须两边都为真
3.not没有逻辑短路

while循环

1.循环的三要素

i=1   循环的初始值
while i<=5:   循环的判断条件
    print(i)   执行的代码块
    i+=1    更新循环变量
else:    当循环正常结束时,就会执行else里面的代码
    print()

2.break:提前终止程序,不会再执行else里面的代码

i=1
while i<=5:
    if i==3:
        break
     print(i)
     i+=1
else:
    print()

3.continue:跳出本次循环,继续下次循环

i=1
while i<=5:
    if i==3:
        i+=1
        continue
    print(i)
    i+=1
else:
    print()
        

嵌套循环

a=1
while a<5:
    print('a:',a)
    a+=1
else:
    print('循环结束')

ptint()默认情况下会换行,end=’'能够让print()不换行

b=1
while b<10:
    if b%5=0:
        break
    print('b:',b,end='')
    b+=1

嵌套:

a=1
while a<5:
    b=1
    while b<10:
        if b%5=0:
            break
        print('b:',b,end='')
        b+=1
    print('a:',a)
    a+=1
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值