python 流程控制语句

流程控制语句

判断语句

  • if语句
# if 后面的条件为真则执行,否则不执行
if 1 + 2 == 3:
    print("1 + 2 == 3")

if 1 + 2 == 4:
    print("1 + 2 == 4")
1 + 2 == 3
  • if … else …
# if 后面的条件为真则执行,否则else执行
if 1 + 2 == 3:
    print("1 + 2 == 3")
else:
    print("1 + 2 != 3")

if 1 + 2 == 4:
    print("1 + 2 == 4")
else:
    print("1 + 2 != 4")
1 + 2 == 3
1 + 2 != 4
  • if … elif … else
# if 后面的条件为真则执行,否则elif判断,都不为真执行else
if 1 + 2 == 4:
    print("1 + 2 == 4")
elif 1 + 3 == 4:
    print("1 + 3 == 4")
else:
    print("~77~")
1 + 3 == 4
  • and、or、not
# and 前后两个条件都为真是结果为真
# 表达式1  and  表达式2
# True   and  True    # 结果为 True
# True   and  False   # 结果为 False
# False  and  True    # 结果为 False
# False  and  False   # 结果为 False
if 1 == 1 and 1 == 2:
    print("it's True")
if 1 == 1 and 2 == 2:
    print("it's all True")
it's all True
# 表达式1  or  表达式2
# 两个表达式有一个为真,就为真
# True   or  True    # 结果为 True
# True   or  False   # 结果为 True
# False  or  True    # 结果为 True
# False  or  False   # 结果为 False
if 1 == 1 or 1 == 2:
    print("it's True")
if 1 == 2 or 1 == 2:
    print("it's all FALSE")
it's True
# not 表达式
# not  True    # 结果为 False
# not  False   # 结果为 True

if not (1 == 1):
    print("it's true")
if not (1 == 2):
    print("it's false")
it's false

循环语句

  • while
# while 表达式:
#   循环体
# 只要表达式为真,就执行循环体
a = 4
while a > 0:
    print("a = ",a)
    a = a - 1
a =  4
a =  3
a =  2
a =  1
  • for语句
cols = ['red', 'yellow', 'blue']
# 循环遍历列表
for col in cols:
    print(col)
red
yellow
blue
  • range() 函数

内置函数 range() 常用于遍历数字序列

for i in range(5):
    print("i = ",i)
i =  0
i =  1
i =  2
i =  3
i =  4
  • break、continue、else
# break 跳出循环
for i in range(5):
    if i == 3:
        break
    print("i = ",i)
i =  0
i =  1
i =  2
# continue跳过本次循环,执行下一次
for i in range(5):
    if i == 2:
        continue
    print("i = ",i)
i =  0
i =  1
i =  3
i =  4
# else for循环不满足执行else
for i in range(2,8):
    for x in (2,i):
        if i % x == 0:
            print(i, 'equals', x, '*', i//x)
    else:
        print(i, 'is a prime number')
2 equals 2 * 1
2 equals 2 * 1
2 is a prime number
3 equals 3 * 1
3 is a prime number
4 equals 2 * 2
4 equals 4 * 1
4 is a prime number
5 equals 5 * 1
5 is a prime number
6 equals 2 * 3
6 equals 6 * 1
6 is a prime number
7 equals 7 * 1
7 is a prime number
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Ghost_199503

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值