Loops are used in Python to repeat a block of code multiple times.
Python mainly has two types of loops:
forloopwhileloop
1. for Loop
<div class="infographic-pyfor">
<style>
.infographic-pyfor {
--ink: #1a1a1a;
--ink-soft: #5c5c5c;
--paper: #ffffff;
--paper-alt: #f0ece4;
--accent: #2563eb;
--accent-soft:#e3ebfd;
--line: #ddd6c9;
--ok: #1a7f4e;
--ok-soft: #e3f5ec;
--display-font: 'Fraunces', Georgia, serif;
--body-font: 'Inter', -apple-system, sans-serif;
--mono-font: 'IBM Plex Mono', 'Courier New', monospace;
max-width: 680px;
margin: 0 auto;
box-sizing: border-box;
font-family: var(--body-font);
color: var(--ink);
background: var(--paper);
}
.infographic-pyfor[data-theme="dark"] {
--ink: #e8e6e1;
--ink-soft: #9a968c;
--paper: #121212;
--paper-alt: #1e1e26;
--accent: #5b8def;
--accent-soft:#202942;
--line: #2c313d;
--ok: #5cd6a0;
--ok-soft: #16342a;
}
.infographic-pyfor * { box-sizing: border-box; }
.infographic-pyfor .ig-inner { padding: 1.75rem clamp(1.25rem, 5vw, 3rem) 2rem; }
.infographic-pyfor .ig-title {
font-family: var(--display-font); font-size: clamp(1.4rem, 4.5vw, 1.9rem);
font-weight: 600; text-align: center; margin: 0 0 0.4rem;
}
.infographic-pyfor .ig-code {
text-align: center; font-family: var(--mono-font); font-size: 0.85rem; color: var(--ink-soft);
margin: 0 0 0.35rem;
}
.infographic-pyfor .ig-code strong { color: var(--accent); }
.infographic-pyfor .ig-subnote {
text-align: center; font-size: 0.76rem; color: var(--ink-soft); margin: 0 0 1.6rem;
}
.infographic-pyfor .controls { display: flex; align-items: center; justify-content: center; gap: 0.6rem; flex-wrap: wrap; }
.infographic-pyfor .ctrl-btn {
font: inherit; font-size: 0.82rem; font-weight: 600; border: 1px solid var(--line);
background: var(--paper-alt); color: var(--ink); padding: 0.45rem 1rem;
border-radius: 999px; cursor: pointer; display: inline-flex; align-items: center; gap: 0.35rem;
}
.infographic-pyfor .ctrl-btn:hover { border-color: var(--accent); color: var(--accent); }
.infographic-pyfor .ctrl-btn.primary { background: var(--accent); color: var(--paper); border-color: var(--accent); }
.infographic-pyfor .i-badge {
font-family: var(--mono-font); font-size: 0.85rem; font-weight: 700; color: var(--accent);
background: var(--accent-soft); padding: 0.45rem 0.9rem; border-radius: 999px;
}
.infographic-pyfor .stage { margin-top: 1.5rem; display: flex; justify-content: center; }
.infographic-pyfor .stage svg { width: 100%; max-width: 560px; height: auto; overflow: visible; }
.infographic-pyfor .fc-shape { fill: var(--paper-alt); stroke: var(--line); stroke-width: 1.8; transition: fill 0.2s, stroke 0.2s; }
.infographic-pyfor .fc-shape.reached-yes { fill: var(--accent-soft); stroke: var(--accent); filter: drop-shadow(0 3px 6px rgba(0,0,0,0.15)); }
.infographic-pyfor .fc-shape.reached-no { fill: var(--paper-alt); stroke: var(--accent); }
.infographic-pyfor .fc-block.reached { fill: var(--ok-soft); stroke: var(--ok); filter: drop-shadow(0 3px 6px rgba(0,0,0,0.15)); }
.infographic-pyfor .fc-pill { fill: var(--accent-soft); stroke: var(--accent); }
.infographic-pyfor .fc-pill.reached { filter: drop-shadow(0 3px 6px rgba(0,0,0,0.15)); }
.infographic-pyfor .fc-text { font-family: var(--mono-font); font-size: 12px; fill: var(--ink); text-anchor: middle; }
.infographic-pyfor .fc-text.on-pill { fill: var(--accent); font-weight: 700; }
.infographic-pyfor .fc-text.on-block { font-weight: 700; }
.infographic-pyfor .fc-mark { font-family: var(--mono-font); font-size: 13px; font-weight: 700; text-anchor: middle; }
.infographic-pyfor .fc-mark.yes { fill: var(--accent); }
.infographic-pyfor .fc-mark.no { fill: var(--ink-soft); }
.infographic-pyfor .edge-label { font-family: var(--mono-font); font-size: 10px; fill: var(--ink-soft); text-anchor: middle; }
.infographic-pyfor .fc-edge path { stroke: var(--line); stroke-width: 2; fill: none; transition: stroke 0.2s; }
.infographic-pyfor .fc-edge polygon { fill: var(--line); transition: fill 0.2s; }
.infographic-pyfor .fc-edge.is-active path { stroke: var(--accent); stroke-width: 2.5; }
.infographic-pyfor .fc-edge.is-active polygon { fill: var(--accent); }
.infographic-pyfor .output {
margin-top: 1.5rem; text-align: center; font-family: var(--mono-font); font-size: 0.85rem;
color: var(--ink-soft); min-height: 1.4em;
}
.infographic-pyfor .output strong { color: var(--ok); }
.infographic-pyfor .caption {
text-align: center; font-size: 0.9rem; color: var(--ink-soft); margin-top: 0.6rem; min-height: 1.2em;
}
.infographic-pyfor .caption strong { color: var(--ink); font-family: var(--mono-font); }
@media (prefers-reduced-motion: reduce) {
.infographic-pyfor *, .infographic-pyfor *::before, .infographic-pyfor *::after {
animation-duration: 0.001ms !important; transition-duration: 0.001ms !important;
}
}
</style>
<div class="ig-inner">
<p class="ig-code">for i in <strong>range(5)</strong>: <strong>print(i)</strong></p>
<p class="ig-subnote">Python hides init / check / increment inside range() — here's what it does underneath.</p>
<div class="controls">
<button class="ctrl-btn primary" id="playBtn">▶ Play</button>
<button class="ctrl-btn" id="restartBtn">⟲ Restart</button>
<span class="i-badge" id="iBadge">i = —</span>
</div>
<div class="stage">
<svg viewBox="0 0 600 350" xmlns="http://www.w3.org/2000/svg">
<!-- Start -->
<g id="n-start">
<rect class="fc-shape fc-pill" x="15" y="130" width="100" height="40" rx="20"></rect>
<text class="fc-text on-pill" x="65" y="155">Start</text>
</g>
<!-- Start -> Init -->
<g class="fc-edge" id="e-start-init">
<path d="M115,150 L149,150"></path>
<polygon points="155,150 145,145 145,155"></polygon>
</g>
<!-- Init -->
<g id="n-init">
<rect class="fc-shape fc-block" x="155" y="125" width="130" height="50" rx="8"></rect>
<text class="fc-text on-block" x="220" y="155">i = 0</text>
</g>
<!-- Init -> Condition -->
<g class="fc-edge" id="e-init-check">
<path d="M285,150 L309,150"></path>
<polygon points="315,150 305,145 305,155"></polygon>
</g>
<!-- Condition -->
<g id="n-check">
<polygon class="fc-shape" points="365,95 435,150 365,205 295,150"></polygon>
<text class="fc-text" x="365" y="146">i < 5</text>
<text class="fc-text" x="365" y="160">?</text>
<text class="fc-mark" id="mark-check" x="400" y="115"></text>
</g>
<!-- Yes -> Statement -->
<g class="fc-edge" id="e-check-yes">
<path d="M435,150 L459,150"></path>
<polygon points="465,150 455,145 455,155"></polygon>
</g>
<text class="edge-label" x="450" y="138">yes</text>
<g id="n-statement">
<rect class="fc-shape fc-block" x="465" y="125" width="120" height="50" rx="8"></rect>
<text class="fc-text on-block" x="525" y="155">print(i)</text>
</g>
<!-- Statement -> Increment -->
<g class="fc-edge" id="e-statement-inc">
<path d="M525,125 L525,84"></path>
<polygon points="525,78 520,88 530,88"></polygon>
</g>
<!-- Increment -->
<g id="n-increment">
<rect class="fc-shape fc-block" x="465" y="25" width="120" height="50" rx="8"></rect>
<text class="fc-text on-block" x="525" y="55">i += 1</text>
</g>
<!-- Increment -> Condition (loop back) -->
<g class="fc-edge" id="e-inc-check">
<path d="M465,50 L365,50 L365,84"></path>
<polygon points="365,90 360,80 370,80"></polygon>
</g>
<!-- No -> End -->
<g class="fc-edge" id="e-check-no">
<path d="M365,205 L365,274"></path>
<polygon points="365,280 360,270 370,270"></polygon>
</g>
<text class="edge-label" x="381" y="240">no</text>
<!-- End -->
<g id="n-end">
<rect class="fc-shape fc-pill" x="315" y="280" width="100" height="40" rx="20"></rect>
<text class="fc-text on-pill" x="365" y="305">End</text>
</g>
</svg>
</div>
<p class="output" id="output"></p>
<p class="caption" id="caption">Press Play to run the loop.</p>
</div>
</div>
<script>
(function () {
const wrapper = document.currentScript.closest('.infographic-pyfor')
|| document.querySelector('.infographic-pyfor');
const bodyAttr = document.body.getAttribute('data-darkmode');
let dark;
if (bodyAttr === 'true') {
dark = true;
} else if (bodyAttr === 'false') {
dark = false;
} else {
const match = document.cookie.match(/(?:^|;\s*)darkMode=([^;]+)/);
dark = match ? match[1] === 'true' : false;
}
if (dark) wrapper.setAttribute('data-theme', 'dark');
const MAX = 5;
const playBtn = wrapper.querySelector('#playBtn');
const restartBtn = wrapper.querySelector('#restartBtn');
const iBadge = wrapper.querySelector('#iBadge');
const output = wrapper.querySelector('#output');
const caption = wrapper.querySelector('#caption');
const nStart = wrapper.querySelector('#n-start .fc-pill');
const nInit = wrapper.querySelector('#n-init .fc-block');
const nCheck = wrapper.querySelector('#n-check .fc-shape');
const markCheck = wrapper.querySelector('#mark-check');
const nStatement = wrapper.querySelector('#n-statement .fc-block');
const nIncrement = wrapper.querySelector('#n-increment .fc-block');
const nEnd = wrapper.querySelector('#n-end .fc-pill');
const eStartInit = wrapper.querySelector('#e-start-init');
const eInitCheck = wrapper.querySelector('#e-init-check');
const eCheckYes = wrapper.querySelector('#e-check-yes');
const eStatementInc = wrapper.querySelector('#e-statement-inc');
const eIncCheck = wrapper.querySelector('#e-inc-check');
const eCheckNo = wrapper.querySelector('#e-check-no');
const allNodes = [nStart, nInit, nCheck, nStatement, nIncrement, nEnd];
const allEdges = [eStartInit, eInitCheck, eCheckYes, eStatementInc, eIncCheck, eCheckNo];
function resetVisual() {
allNodes.forEach(n => n.classList.remove('reached', 'reached-yes', 'reached-no'));
allEdges.forEach(e => e.classList.remove('is-active'));
markCheck.textContent = ''; markCheck.classList.remove('yes', 'no');
}
// Build the full step sequence
let steps = [];
function buildSteps() {
steps = [];
steps.push({ edge: eStartInit });
steps.push({ node: nInit, i: 0, setBadge: 0 });
steps.push({ edge: eInitCheck });
for (let i = 0; i < MAX; i++) {
steps.push({ check: true, i, result: true });
steps.push({ edge: eCheckYes });
steps.push({ node: nStatement, i, print: i });
steps.push({ edge: eStatementInc });
steps.push({ node: nIncrement, i, setBadge: i + 1 });
steps.push({ edge: eIncCheck });
}
steps.push({ check: true, i: MAX, result: false });
steps.push({ edge: eCheckNo });
steps.push({ node: nEnd, done: true });
}
buildSteps();
let idx = -1;
let timer = null;
let printed = [];
function applyStep(step) {
resetVisual();
nStart.classList.add('reached');
if (step.edge) {
step.edge.classList.add('is-active');
}
if (step.node) {
step.node.classList.add('reached');
if (step.setBadge !== undefined) iBadge.textContent = `i = ${step.setBadge}`;
if (step.print !== undefined) {
printed.push(step.print);
output.innerHTML = `output: <strong>${printed.join(', ')}</strong>`;
}
if (step.done) {
caption.textContent = 'Loop finished — range(5) is exhausted.';
}
}
if (step.check) {
nCheck.classList.add(step.result ? 'reached-yes' : 'reached-no');
markCheck.textContent = step.result ? '✓' : '✗';
markCheck.classList.add(step.result ? 'yes' : 'no');
iBadge.textContent = `i = ${step.i}`;
caption.textContent = step.result
? `i = ${step.i} → true, run the loop body`
: `i = ${step.i} → false, exit the loop`;
}
}
function stop() {
clearInterval(timer);
timer = null;
playBtn.textContent = '▶ Play';
}
function advance() {
idx++;
if (idx >= steps.length) {
stop();
return;
}
applyStep(steps[idx]);
if (idx >= steps.length - 1) stop();
}
function play() {
if (timer) { stop(); return; }
if (idx >= steps.length - 1) restart(false);
playBtn.textContent = '⏸ Pause';
timer = setInterval(advance, 850);
advance();
}
function restart(clearBadge = true) {
stop();
idx = -1;
printed = [];
output.textContent = '';
resetVisual();
if (clearBadge) {
iBadge.textContent = 'i = —';
caption.textContent = 'Press Play to run the loop.';
}
}
playBtn.addEventListener('click', play);
restartBtn.addEventListener('click', () => restart(true));
restart(true);
})();
</script></div>The for loop is used to iterate over a sequence or collection of items.
Syntax
for variable in sequence:
# code to executeExample
fruits = ["Apple", "Banana", "Mango"]
for fruit in fruits:
print(fruit)Apple
Banana
MangoHere, the loop takes each item from the list one by one and executes the code.
Example for range()
range() is commonly used when we want to repeat something a specific number of times.
for i in range(5):
print(i)0
1
2
3
4range(5) starts from 0 and stops before 5.
for i in range(2, 6):
print(i)2
3
4
5The stop value is not included.
The third value determines how much the number changes each time.
for i in range(1, 10, 2):
print(i)
1
3
5
7
9Here:
1→ Start10→ Stop2→ Step
A negative step can be used to count backwards.
for i in range(5, 0, -1):
print(i)5
4
3
2
12. while Loop
<div class="infographic-pywhile">
<style>
.infographic-pywhile {
--ink: #1a1a1a;
--ink-soft: #5c5c5c;
--paper: #ffffff;
--paper-alt: #f0ece4;
--accent: #2563eb;
--accent-soft:#e3ebfd;
--line: #ddd6c9;
--ok: #1a7f4e;
--ok-soft: #e3f5ec;
--display-font: 'Fraunces', Georgia, serif;
--body-font: 'Inter', -apple-system, sans-serif;
--mono-font: 'IBM Plex Mono', 'Courier New', monospace;
max-width: 700px;
margin: 0 auto;
box-sizing: border-box;
font-family: var(--body-font);
color: var(--ink);
background: var(--paper);
}
.infographic-pywhile[data-theme="dark"] {
--ink: #e8e6e1;
--ink-soft: #9a968c;
--paper: #121212;
--paper-alt: #1e1e26;
--accent: #5b8def;
--accent-soft:#202942;
--line: #2c313d;
--ok: #5cd6a0;
--ok-soft: #16342a;
}
.infographic-pywhile * { box-sizing: border-box; }
.infographic-pywhile .ig-inner { padding: 1.75rem clamp(1.25rem, 5vw, 3rem) 2rem; }
.infographic-pywhile .ig-title {
font-family: var(--display-font); font-size: clamp(1.4rem, 4.5vw, 1.9rem);
font-weight: 600; text-align: center; margin: 0 0 0.4rem;
}
.infographic-pywhile .ig-code {
text-align: center; font-family: var(--mono-font); font-size: 0.85rem; color: var(--ink-soft);
margin: 0 0 1.75rem;
}
.infographic-pywhile .ig-code strong { color: var(--accent); }
.infographic-pywhile .controls { display: flex; align-items: center; justify-content: center; gap: 0.6rem; flex-wrap: wrap; }
.infographic-pywhile .ctrl-btn {
font: inherit; font-size: 0.82rem; font-weight: 600; border: 1px solid var(--line);
background: var(--paper-alt); color: var(--ink); padding: 0.45rem 1rem;
border-radius: 999px; cursor: pointer; display: inline-flex; align-items: center; gap: 0.35rem;
}
.infographic-pywhile .ctrl-btn:hover { border-color: var(--accent); color: var(--accent); }
.infographic-pywhile .ctrl-btn.primary { background: var(--accent); color: var(--paper); border-color: var(--accent); }
.infographic-pywhile .i-badge {
font-family: var(--mono-font); font-size: 0.85rem; font-weight: 700; color: var(--accent);
background: var(--accent-soft); padding: 0.45rem 0.9rem; border-radius: 999px;
}
.infographic-pywhile .stage { margin-top: 1.5rem; display: flex; justify-content: center; }
.infographic-pywhile .stage svg { width: 100%; max-width: 580px; height: auto; overflow: visible; }
.infographic-pywhile .fc-shape { fill: var(--paper-alt); stroke: var(--line); stroke-width: 1.8; transition: fill 0.2s, stroke 0.2s; }
.infographic-pywhile .fc-shape.reached-yes { fill: var(--accent-soft); stroke: var(--accent); filter: drop-shadow(0 3px 6px rgba(0,0,0,0.15)); }
.infographic-pywhile .fc-shape.reached-no { fill: var(--paper-alt); stroke: var(--accent); }
.infographic-pywhile .fc-block.reached { fill: var(--ok-soft); stroke: var(--ok); filter: drop-shadow(0 3px 6px rgba(0,0,0,0.15)); }
.infographic-pywhile .fc-pill { fill: var(--accent-soft); stroke: var(--accent); }
.infographic-pywhile .fc-pill.reached { filter: drop-shadow(0 3px 6px rgba(0,0,0,0.15)); }
.infographic-pywhile .fc-text { font-family: var(--mono-font); font-size: 12px; fill: var(--ink); text-anchor: middle; }
.infographic-pywhile .fc-text.on-pill { fill: var(--accent); font-weight: 700; }
.infographic-pywhile .fc-text.on-block { font-weight: 700; }
.infographic-pywhile .fc-mark { font-family: var(--mono-font); font-size: 13px; font-weight: 700; text-anchor: middle; }
.infographic-pywhile .fc-mark.yes { fill: var(--accent); }
.infographic-pywhile .fc-mark.no { fill: var(--ink-soft); }
.infographic-pywhile .edge-label { font-family: var(--mono-font); font-size: 10px; fill: var(--ink-soft); text-anchor: middle; }
.infographic-pywhile .fc-edge path { stroke: var(--line); stroke-width: 2; fill: none; transition: stroke 0.2s; }
.infographic-pywhile .fc-edge polygon { fill: var(--line); transition: fill 0.2s; }
.infographic-pywhile .fc-edge.is-active path { stroke: var(--accent); stroke-width: 2.5; }
.infographic-pywhile .fc-edge.is-active polygon { fill: var(--accent); }
.infographic-pywhile .output {
margin-top: 1.5rem; text-align: center; font-family: var(--mono-font); font-size: 0.85rem;
color: var(--ink-soft); min-height: 1.4em;
}
.infographic-pywhile .output strong { color: var(--ok); }
.infographic-pywhile .caption {
text-align: center; font-size: 0.9rem; color: var(--ink-soft); margin-top: 0.6rem; min-height: 1.2em;
}
.infographic-pywhile .caption strong { color: var(--ink); font-family: var(--mono-font); }
@media (prefers-reduced-motion: reduce) {
.infographic-pywhile *, .infographic-pywhile *::before, .infographic-pywhile *::after {
animation-duration: 0.001ms !important; transition-duration: 0.001ms !important;
}
}
</style>
<div class="ig-inner">
<p class="ig-code">i = 0<br>while <strong>i < 5</strong>: print(i); <strong>i += 1</strong></p>
<div class="controls">
<button class="ctrl-btn primary" id="playBtn">▶ Play</button>
<button class="ctrl-btn" id="restartBtn">⟲ Restart</button>
<span class="i-badge" id="iBadge">i = —</span>
</div>
<div class="stage">
<svg viewBox="0 0 630 350" xmlns="http://www.w3.org/2000/svg">
<!-- Start -->
<g id="n-start">
<rect class="fc-shape fc-pill" x="15" y="130" width="100" height="40" rx="20"></rect>
<text class="fc-text on-pill" x="65" y="155">Start</text>
</g>
<!-- Start -> Init -->
<g class="fc-edge" id="e-start-init">
<path d="M115,150 L149,150"></path>
<polygon points="155,150 145,145 145,155"></polygon>
</g>
<!-- Init -->
<g id="n-init">
<rect class="fc-shape fc-block" x="155" y="125" width="130" height="50" rx="8"></rect>
<text class="fc-text on-block" x="220" y="155">i = 0</text>
</g>
<!-- Init -> Condition -->
<g class="fc-edge" id="e-init-check">
<path d="M285,150 L309,150"></path>
<polygon points="315,150 305,145 305,155"></polygon>
</g>
<!-- Condition -->
<g id="n-check">
<polygon class="fc-shape" points="365,95 435,150 365,205 295,150"></polygon>
<text class="fc-text" x="365" y="146">i < 5</text>
<text class="fc-text" x="365" y="160">?</text>
<text class="fc-mark" id="mark-check" x="400" y="115"></text>
</g>
<!-- Yes -> Statement -->
<g class="fc-edge" id="e-check-yes">
<path d="M435,150 L459,150"></path>
<polygon points="465,150 455,145 455,155"></polygon>
</g>
<text class="edge-label" x="450" y="138">yes</text>
<g id="n-statement">
<rect class="fc-shape fc-block" x="465" y="125" width="150" height="50" rx="8"></rect>
<text class="fc-text on-block" x="540" y="146">print(i)</text>
<text class="fc-text on-block" x="540" y="163">i += 1</text>
</g>
<!-- Statement -> Condition (loop back) -->
<g class="fc-edge" id="e-loop-back">
<path d="M540,125 L540,50 L365,50 L365,84"></path>
<polygon points="365,90 360,80 370,80"></polygon>
</g>
<!-- No -> End -->
<g class="fc-edge" id="e-check-no">
<path d="M365,205 L365,274"></path>
<polygon points="365,280 360,270 370,270"></polygon>
</g>
<text class="edge-label" x="381" y="240">no</text>
<!-- End -->
<g id="n-end">
<rect class="fc-shape fc-pill" x="315" y="280" width="100" height="40" rx="20"></rect>
<text class="fc-text on-pill" x="365" y="305">End</text>
</g>
</svg>
</div>
<p class="output" id="output"></p>
<p class="caption" id="caption">Press Play to run the loop.</p>
</div>
</div>
<script>
(function () {
const wrapper = document.currentScript.closest('.infographic-pywhile')
|| document.querySelector('.infographic-pywhile');
const bodyAttr = document.body.getAttribute('data-darkmode');
let dark;
if (bodyAttr === 'true') {
dark = true;
} else if (bodyAttr === 'false') {
dark = false;
} else {
const match = document.cookie.match(/(?:^|;\s*)darkMode=([^;]+)/);
dark = match ? match[1] === 'true' : false;
}
if (dark) wrapper.setAttribute('data-theme', 'dark');
const MAX = 5;
const playBtn = wrapper.querySelector('#playBtn');
const restartBtn = wrapper.querySelector('#restartBtn');
const iBadge = wrapper.querySelector('#iBadge');
const output = wrapper.querySelector('#output');
const caption = wrapper.querySelector('#caption');
const nStart = wrapper.querySelector('#n-start .fc-pill');
const nInit = wrapper.querySelector('#n-init .fc-block');
const nCheck = wrapper.querySelector('#n-check .fc-shape');
const markCheck = wrapper.querySelector('#mark-check');
const nStatement = wrapper.querySelector('#n-statement .fc-block');
const nEnd = wrapper.querySelector('#n-end .fc-pill');
const eStartInit = wrapper.querySelector('#e-start-init');
const eInitCheck = wrapper.querySelector('#e-init-check');
const eCheckYes = wrapper.querySelector('#e-check-yes');
const eLoopBack = wrapper.querySelector('#e-loop-back');
const eCheckNo = wrapper.querySelector('#e-check-no');
const allNodes = [nStart, nInit, nCheck, nStatement, nEnd];
const allEdges = [eStartInit, eInitCheck, eCheckYes, eLoopBack, eCheckNo];
function resetVisual() {
allNodes.forEach(n => n.classList.remove('reached', 'reached-yes', 'reached-no'));
allEdges.forEach(e => e.classList.remove('is-active'));
markCheck.textContent = ''; markCheck.classList.remove('yes', 'no');
}
let steps = [];
function buildSteps() {
steps = [];
steps.push({ edge: eStartInit });
steps.push({ node: nInit, setBadge: 0 });
steps.push({ edge: eInitCheck });
for (let i = 0; i < MAX; i++) {
steps.push({ check: true, i, result: true });
steps.push({ edge: eCheckYes });
steps.push({ node: nStatement, i, print: i, setBadge: i + 1 });
steps.push({ edge: eLoopBack });
}
steps.push({ check: true, i: MAX, result: false });
steps.push({ edge: eCheckNo });
steps.push({ node: nEnd, done: true });
}
buildSteps();
let idx = -1;
let timer = null;
let printed = [];
function applyStep(step) {
resetVisual();
nStart.classList.add('reached');
if (step.edge) {
step.edge.classList.add('is-active');
}
if (step.node) {
step.node.classList.add('reached');
if (step.setBadge !== undefined) iBadge.textContent = `i = ${step.setBadge}`;
if (step.print !== undefined) {
printed.push(step.print);
output.innerHTML = `output: <strong>${printed.join(', ')}</strong>`;
}
if (step.done) {
caption.textContent = 'Loop finished — condition is now false.';
}
}
if (step.check) {
nCheck.classList.add(step.result ? 'reached-yes' : 'reached-no');
markCheck.textContent = step.result ? '✓' : '✗';
markCheck.classList.add(step.result ? 'yes' : 'no');
iBadge.textContent = `i = ${step.i}`;
caption.textContent = step.result
? `i = ${step.i} → true, run the loop body`
: `i = ${step.i} → false, exit the loop`;
}
}
function stop() {
clearInterval(timer);
timer = null;
playBtn.textContent = '▶ Play';
}
function advance() {
idx++;
if (idx >= steps.length) {
stop();
return;
}
applyStep(steps[idx]);
if (idx >= steps.length - 1) stop();
}
function play() {
if (timer) { stop(); return; }
if (idx >= steps.length - 1) restart(false);
playBtn.textContent = '⏸ Pause';
timer = setInterval(advance, 850);
advance();
}
function restart(clearBadge = true) {
stop();
idx = -1;
printed = [];
output.textContent = '';
resetVisual();
if (clearBadge) {
iBadge.textContent = 'i = —';
caption.textContent = 'Press Play to run the loop.';
}
}
playBtn.addEventListener('click', play);
restartBtn.addEventListener('click', () => restart(true));
restart(true);
})();
</script></div>A while loop repeatedly executes a block of code as long as a condition is True.
Syntax
while condition:
# code to executeExample
x = 1
while x <= 5:
print(x)
x += 11
2
3
4
53. while Loop with User Input
A while loop is useful when we don't know beforehand how many times the loop should run.
password = ""
while password != "1234":
password = input("Enter password: ")
print("Access Granted")The loop continues until the user enters the correct password.
4. Infinite while Loop
If the condition never becomes False, the loop will continue forever.
x = 1
while x <= 5:
print(x)Here, x never changes, so x <= 5 will always be True.
Therefore, always make sure a while loop has a way to eventually make its condition False.
for vs while
|
|
|---|---|
Used to iterate over a sequence | Runs while a condition is |
Usually used when the number of iterations is known | Useful when the number of iterations is unknown |
Commonly used with | Commonly used with conditions |
Less likely to create an infinite loop | Can create an infinite loop if the condition never becomes |