Fundamentals 4 min read

Python Control Flow: if‑elif‑else, while, and for Loops

This article explains Python's core control‑flow constructs—if‑elif‑else, while, and for loops—providing clear explanations, runnable code examples, and additional notes on boolean logic and string formatting for beginners and intermediate programmers.

Practical DevOps Architecture
Practical DevOps Architecture
Practical DevOps Architecture
Python Control Flow: if‑elif‑else, while, and for Loops

This article introduces Python's fundamental control‑flow statements: if‑elif‑else , while , and for loops, each accompanied by concise explanations and executable code snippets.

1. if‑elif‑else statement The first condition that evaluates to True executes its block; if none are true, the else block runs. Python uses indentation to define blocks.

>> x = 5
>>> if x < 5:
...     y = -1
...     z = 5
... elif x > 5:
...     y = 1
...     z = 11
... else:
...     y = 0
...     z = 10
...
>>> print(x, y, z)
5 0 10

2. while loop The loop continues as long as its condition remains True . Inside the loop you can nest other control structures.

>> u, v, x, y = 0, 0, 100, 30
>>> while x > y:
...     u = u + y
...     x = x - y
...     if x < y + 20:
...         v = v + x
...         x = 0
...     else:
...         v = v + y + 2
...         x = x - y - 2
...
>>> print(u, v)
60 40

3. for loop A for loop iterates over any iterable (e.g., lists, tuples). The example demonstrates type checking with isinstance , using continue , and finding the first integer divisible by seven.

>> item_list = [3, "string1", 23, 14.0, "string2", 49, 64, 70]
>>> for x in item_list:
...     if not isinstance(x, int):
...         continue
...     if not x % 7:
...         print("found an integer divisible by seven: %d" % x)
...         break
...
found an integer divisible by seven: 49

Additional notes: the not operator negates a boolean value; not False is True . The article also lists common string‑formatting specifiers such as %s , %d , %f , and their meanings.

--- End of tutorial ---

Pythonprogramming fundamentalsif-elsecontrol flowfor loopwhile loop
Practical DevOps Architecture
Written by

Practical DevOps Architecture

Hands‑on DevOps operations using Docker, K8s, Jenkins, and Ansible—empowering ops professionals to grow together through sharing, discussion, knowledge consolidation, and continuous improvement.

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.