Python Loops in Rust (loop, while, for)
Rust provides three loop constructs: loop (infinite loop that can return values via break expr), while (condition-based loop), and for (safe iteration over ranges and iterators).
"loop is a conveyor belt that runs forever until you pull the emergency lever (break value). for is a delivery driver who visits every address on a list in order and stops when the list is done."
Deep Dive: How It Works
Returning Values from loop: break result; terminates loop and evaluates to result.
for in Range: for i in 0..5 iterates 0, 1, 2, 3, 4 (inclusive: 0..=5).
Iterator Safety: for element in &array eliminates index out-of-bounds panics completely.
Syntax Blueprint
let val = loop { if done { break 42; } }; | for i in 1..=3 { ... }Use loop for retries that return values and for in ranges for clean counting.
Core Rules to Remember



Common Beginner Traps & How to Fix Them
Using 0..5 expecting it to include 5.Why it happens: 0..5 is exclusive of the upper bound (yields 0 to 4).
How to fix: Use the inclusive range operator 0..=5 if 5 must be included.
Live Interactive Example
Hit Run Code to see it liveYour Turn: Micro Challenge
No pressure! Edit the starter code below and test your solution with instant feedback.
Calculate factorial with a for loop
Calculate factorial of 5 (1 * 2 * 3 * 4 * 5 = 120).
Initialize let mut product = 1;
Use for i in 1..=5 { product *= i; }
Print "Factorial: 120".
Finished reading and practicing?
Mark this lesson as completed to update your course progress.