Python day 4 循环与控制

if 前面整理了,不支持switch,对应只能多个elif。

对于循环类型,Python 提供了 for 循环和 while 循环(在 Python 中没有 do..while 循环)

对于循环控制,Python提供了break,continue,对比Java 多了pass.单纯为了保证语法校验通过的。

i = 1
while i < 10:
    i += 1
    if i % 2 > 0:  # 非双数时跳过输出
        continue
    print(i)  # 输出双数2、4、6、8、10
print("byebye while 1")
i = 11
while 1:  # 循环条件为1必定成立
    print(i)  # 输出11~15
    i += 1
    if i > 15:  # 当i大于15时跳出循环
        break
print("byebye while 2")

输出:

2
4
6
8
10
byebye while 1
11
12
13
14
15
byebye while 2

for  循环也是一样

for i in range(5):
    print(i)
for i in range(6, 20, 2):
    print(i)
for j  in  "bohu83":
    print(j)

break 跟上面一样:

for letter in 'baoshu':     #
   if letter == 'h':
      break
   print('当前字母 :', letter)

输出:

当前字母 : b
当前字母 : a
当前字母 : o
当前字母 : s

continue.就是跳过

n = 0
while n < 10:
    n = n + 1
    if n % 2 == 0:      # 如果n是偶数,跳过
        continue        # continue语句会直接继续,不打印
    print(n)

输出:

1
3
5
7
9

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值