Python-流程控制总结(if、elif、else、for、while、continue、break、pass等)

目录

条件

if、elif、else

 三元操作符???

循环

for

while

无限循环

计数循环

do...while???

continue与break

pass

循环中的else

内置函数

enumerate(iterable, start=0)

range(start, stop[, step])

zip(*iterables)


条件

if、elif、else

关键字 'elif' 是 'else if' 的缩写,一个 if ... elif ... elif ... 序列可以看作是其他语言中的 switch  case 语句的替代

可以有零个或多个elif部分,以及一个可选的 else部分。

可与and、or、not等一起使用

格式:

if <条件判断1>:
    <执行1>
elif <条件判断2>:
    <执行2>
elif <条件判断3>:
    <执行3>
else:
    <执行4>

举例:

x = 80
if 0 < x < 60:
    print('bad')
elif 60 <= x < 90:
    print('excellent')
else:
    print('perfect')

结果:

excellent

 三元操作符???

在C++中有?,那么python中没有?,要实现三元操作符如何办呢?X if C else Y

举例:

>>> grade = 90
>>> a = 'good' if grade>=90 else 'bad'
>>> a
'good'

循环

for

对任意序列进行迭代(例如,列表、元组、字符串等),使用关键字in。

举例:

words = ['hello', 'lady', 'killer', '9']
for w in words:
    print(w, len(w))

结果:

hello 5
lady 4
killer 6
9 1

如果你想要循环时对序列进行修改(增加、删除等),建议你拷贝一份,使用[:]是一个不错的选择,有的可迭代类型有copy函数,也可以选择。

nums = [3, 7, 8, 3, 4, 6, 1]

for num in nums[:]:
    if num > 5:
        nums.pop(nums.index(num))
print(nums)

结果:

[3, 3, 4, 1]

while

循环语句,与if相比,若满足条件,一直运行,而不是一次。

while expression:
    something need to repeat

无限循环

while True即可,不再举例

计数循环

使用cnt进行计数

cnt = 0
while cnt < 5:
    print(f'第{cnt+1}次循环')
    cnt += 1 

结果:

第1次循环
第2次循环
第3次循环
第4次循环
第5次循环

do...while???

在C++中你可以找到doo...while,然而,python中没有。python的开发者希望语言变得更简单,如果不是有人使用语言中的其他关键字模仿三元操作符经常出错,甚至连if..else实现三元操作符也不会有。当然,do...while的实现就很简单了,使用一个flag即可,do...while就是先做,然后再判断。

举例:

import random
flag = True
while flag:
    num = random.choice(range(10))
    print(num)
    if num < 4:
        flag = False

结果(当然,你的结果和我的可能不一样):

8
3

continue与break

continue用于停止本次循环,进入下次循环;break用于跳出循环。两个关键字让循环变得更灵活。

小综合举例:

cnt = 3
password = 'lady_killer9'
while cnt != 0:
    pwd = input('please input your password:')
    if pwd == password:
        print('log in success')
        break
    else:
        print('password not right!!!')
        cnt -= 1
        continue

结果:

E:\Workspace\python_workspace\learnpy>python learncondition.py
please input your password:hi
password not right!!!
please input your password:lady
password not right!!!
please input your password:lady_killer
password not right!!!

E:\Workspace\python_workspace\learnpy>python learncondition.py
please input your password:hello
password not right!!!
please input your password:lady_killer9
log in success

pass

python使用缩进而不是{},有些时候语法上需要写语句,但是我们又希望什么都不要做,这个时候就可以使用pass。

举例(找到对3取余为1的数):

num = 0
nums = [1, 2, 5, 6, 4, 7]
for i in nums:
    if i % 3 == 1:
        print('找到了:', i)
        continue
    if i % 2 == 0:
        print('偶数但不符合')
    else:
        pass

结果:

找到了: 1
偶数但不符合
偶数但不符合
找到了: 4
找到了: 7

i为5时,pass掉了

循环中的else

循环语句可能带有一个 else 子句;它会在循环遍历完列表 (使用for) 或是在条件变为假 (使用while) 的时候被执行,但是不会在循环被break语句终止时被执行。也就是说,循环没有被break终止,那么就执行else后的语句。

寻找最大因子

普通:

def showMaxFactor(num):
    flag = False
    count = int(num/2)
    while count > 1:
        if num % count == 0:
            print(f'largest factor of {num} if {count}')
            flag = True
            break
        count -= 1
    if not flag:
        print(num, 'is prime')


for n in range(10, 21):
    showMaxFactor(n)

结果:

largest factor of 10 if 5
11 is prime
largest factor of 12 if 6
13 is prime
largest factor of 14 if 7
largest factor of 15 if 5
largest factor of 16 if 8
17 is prime
largest factor of 18 if 9
19 is prime
largest factor of 20 if 10

else写法:

def showMaxFactor(num):
    count = int(num/2)
    while count > 1:
        if num % count == 0:
            print(f'largest factor of {num} if {count}')
            break
        count -= 1
    else:
        print(num, 'is prime')

内置函数

enumerate(iterable, start=0)

返回一个枚举对象。iterable 必须是一个序列,或迭代器,或其他支持迭代的对象。enumerate()返回的迭代器的__next__()方法返回一个元组,里面包含一个计数值(从 start 开始,默认为 0)和通过迭代 iterable 获得的值。

当在序列中循环时,可以将索引位置和其对应的值同时取出

lst = [7, 0, 'a', 'b', 7, '345', 67, 'lady', 'killer', 78, '9', 'lady_killer9', 4, 6]
for i, v in enumerate(lst):
    if v == 'lady_killer9':
        lst.pop(i)
print(lst)

结果:

[7, 0, 'a', 'b', 7, '345', 67, 'lady', 'killer', 78, '9', 4, 6]

range(start, stop[, step])

一个不可变的序列类型,start可以大于stop,step可以为负数

for i in range(len(lst) - 1, -1, -1):
    print(lst[i], sep=' ', end=' ')

结果:

6 4 lady_killer9 9 78 killer lady 67 345 7 b a 0 7

zip(*iterables)

创建一个聚合了来自每个可迭代对象中的元素的迭代器。

返回一个元组的迭代器,其中的第 i 个元组包含来自每个参数序列或可迭代对象的第 i 个元素。 当所输入可迭代对象中最短的一个被耗尽时,迭代器将停止迭代。 当只有一个可迭代对象参数时,它将返回一个单元组的迭代器。 不带参数时,它将返回一个空迭代器。

x = [1, 2, 3]
y = [4, 5, 6]
zipped = zip(x, y)
print(list(zipped))
print(list(zip(*zip(x, y))))
for k, v in zip(x, y):
    if v == 2 * k:
        print(k, v)

结果:

[(1, 4), (2, 5), (3, 6)]
[(1, 2, 3), (4, 5, 6)]
3 6

更多python相关内容:【python总结】python学习框架梳理

本人b站账号:lady_killer9

有问题请下方评论,转载请注明出处,并附有原文链接,谢谢!如有侵权,请及时联系。如果您感觉有所收获,自愿打赏,可选择支付宝18833895206(小于),您的支持是我不断更新的动力。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

lady_killer9

感谢您的打赏,我会加倍努力!

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

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

打赏作者

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

抵扣说明:

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

余额充值