Lesson 6 of 26
if, loops and ranges
Rust's if looks like Python's, with two differences: no parentheses around the condition, and the
braces are always required. Rust also has no truthiness. The condition must be a real bool, so an
empty string or the number 0 is not "false" to Rust. You compare instead: n != 0,
!text.is_empty().
Loops are close to Python. for i in 0..5 is for i in range(5). The two dots make a
range, and it stops before the last number. Write 0..=5 when you want the 5 included.
while works as you expect. Rust also has loop, a loop with no condition, which you leave
with break.
if, else if, else
Read the Rust side for three things: no parentheses, braces instead of indentation, and
else if where Python writes elif.
score = 72
if score >= 90:
print("A")
elif score >= 70:
print("B")
else:
print("C")fn main() {
let score = 72;
if score >= 90 {
println!("A");
} else if score >= 70 {
println!("B");
} else {
println!("C");
}
}BThere is no truthiness
Python asks "is this value falsy?" Rust has no such question, so this does not compile. To say the same
thing in Rust, ask a question that has a yes or no answer: if !name.is_empty(). The !
is "not". For a number you write if n != 0, and for a list if !items.is_empty().
name = ""
if name:
print("has a name")
else:
print("empty")fn main() {
let name = String::new();
if name {
println!("has a name");
} else {
println!("empty");
}
}emptyfor and ranges
One line per Python loop. 0..3 stops before 3, like range(3).
3..=5 includes 5, like range(3, 6). Ranges also have methods: step_by is
the third argument of range, and rev counts down.
for i in range(3):
print(i)
for i in range(3, 6):
print(i)
for i in range(0, 10, 2):
print(i)
for i in range(4, 0, -1):
print(i)fn main() {
for i in 0..3 {
println!("{i}");
}
for i in 3..=5 {
println!("{i}");
}
for i in (0..10).step_by(2) {
println!("{i}");
}
for i in (1..=4).rev() {
println!("{i}");
}
}0
1
2
3
4
5
0
2
4
6
8
4
3
2
1while and continue
This adds up the odd numbers below 10. continue jumps to the next round of the loop and
skips the rest of the body, exactly like in Python.
n = 0
total = 0
while n < 10:
n += 1
if n % 2 == 0:
continue
total += n
print(total)fn main() {
let mut n = 0;
let mut total = 0;
while n < 10 {
n += 1;
if n % 2 == 0 {
continue;
}
total += n;
}
println!("{total}");
}25loop, and break with a value
loop is while True. The useful part is that break can hand a value
out, and that value becomes the value of the whole loop. Here the loop is assigned to
found, which is why there is a ; after its closing brace.
You will also meet labels: 'outer: for i in 0..3 { ... break 'outer; }. A label lets
break leave both loops at once. Python has no direct equivalent.
n = 6
steps = 0
while True:
if n % 2 == 0:
n = n // 2
elif n == 1:
break
else:
n = 3 * n + 1
steps += 1
print(f"{n} after {steps} steps")fn main() {
let mut n = 6;
let mut steps = 0;
let found = loop {
if n % 2 == 0 {
n = n / 2;
} else if n == 1 {
break n;
} else {
n = 3 * n + 1;
}
steps += 1;
};
println!("{found} after {steps} steps");
}1 after 8 stepsWhere the Python analogy breaks
- There is no truthiness.
if items:,if name:andif n:don't compile. Write the check you mean:!items.is_empty(),!name.is_empty(),n != 0. &&,||and!only take and give abool. Python'sx or 0returns one of the two values. In Rust that idea isunwrap_or(lesson 11).- Loops have no
else. Python'sfor ... else, which runs when there was nobreak, doesn't exist. Useloopwith abreakvalue, or.any()(lesson 8). - There is no negative step.
range(5, 0, -1)becomes(1..=5).rev(). A range whose start is bigger than its end, like5..0, is simply empty.
Cheat card
| Python | Rust |
|---|---|
if x > 0: | if x > 0 { |
elif x == 0: | } else if x == 0 { |
else: | } else { |
if items: | if !items.is_empty() { |
for i in range(5): | for i in 0..5 { |
for i in range(1, 6): | for i in 1..=5 { |
for i in range(0, 10, 2): | for i in (0..10).step_by(2) { |
for i in range(5, 0, -1): | for i in (1..=5).rev() { |
while n > 0: | while n > 0 { |
while True: | loop { |
break | break; |
continue | continue; |