Fundamentals 4 min read

Python Control Flow: Conditional Statements, Loops, Iterators, and List Comprehensions

This article introduces Python's basic control flow constructs, including if/elif/else conditional statements, for and while loops with break/continue, iterator usage with Iterable and enumerate, and list comprehensions, providing example code snippets and their outputs for each concept.

DevOps Cloud Academy
DevOps Cloud Academy
DevOps Cloud Academy
Python Control Flow: Conditional Statements, Loops, Iterators, and List Comprehensions

Python control flow includes conditional statements, loops, iterator utilities, and list comprehensions, each demonstrated with example code and outputs.

Code Block

A block of code consists of multiple statements.

Conditional Statements

If statement

if 条件 :
    做事情
else:
    做事情


if 条件:
    做事情
elif 条件:
    做事情
else:
    做事情

Example Code

# if 语句

score = 60

students = {"zhangsan":80,"lisi":70,"wangwu":40}

if students["wangwu"] >= score:
    print("及格了")
elif students["zhangsan"] >= 80:
    print("你很优秀")
else:
    print("不及格")


a=True
b=True

if a == True:
    print(True)
    if b == 1:
        print(False)

Output

你很优秀

Loop Statements

For Loop

for 变量名 in 序列:
    todo

Example Code

#For  循环语句

students = ["aa","bbb","ccc","ddd"]

for i in students:
    print("students's name is {0}".format(i))

    for index in range(len(students)):
        if students[index] == i:
            print(index)

Output

students's name is aa
0
students's name is bbb
1
students's name is ccc
2
students's name is ddd
3

While Loop

while 条件=True:
    todo

Example Code

#while 语句

a = 11

while a >= 10 :
    for i in range(100):
        print(i)
        if i == 5:
            a = i
            print(a)

break and continue statements

Break out of the loop

Skip the current iteration and continue with the next

#break continue

for i in range(10):
    if i == 5:
        break
    else:
        print(i)


for i in range(10):
    if i == 5:
        continue
    else:
        print(i)

Iterator

Iterable

#迭代器

#lterable

from collections import Iterable

num=456
print(isinstance(num, Iterable))

num1 = [1,2,3]
print(isinstance(num1, Iterable))

Output

False
True

enumerate

#enumerate

names = ['z','a','b']
print(enumerate(names))

for i,value in enumerate(names):
    print(i,value)
0 z
1 a
2 b

List Comprehension

#列表推导式

numlist = []
for x in range(5):
    numlist.append(x)
print(numlist)

#
print([x for x in range(5)])
[0, 1, 2, 3, 4]
[0, 1, 2, 3, 4]
PythonIteratorlist comprehensioncontrol flowLoopconditional
DevOps Cloud Academy
Written by

DevOps Cloud Academy

Exploring industry DevOps practices and technical expertise.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.