Master conditional statements, loops, and control flow in Walrus
Control flow statements allow you to control the execution path of your program. Walrus provides conditional statements, loops, and flow control keywords.
let grade = 85;let letter = "";if grade >= 90 { letter = "A";} else if grade >= 80 { letter = "B";} else if grade >= 70 { letter = "C";} else if grade >= 60 { letter = "D";} else { letter = "F";}println(f"Grade: {letter}");
for n in 1..101 { let result = ""; if n % 3 == 0 { result += "Fizz"; } if n % 5 == 0 { result += "Buzz"; } if result == "" { result = str(n); } println(result);}
fn is_prime : n { if n < 2 { return false; } let i = 2; while i * i <= n { if n % i == 0 { return false; } i = i + 1; } return true;}// Find primes up to 50for i in 2..51 { if is_prime(i) { println(i); }}
let valid_input = false;let attempts = 0;let max_attempts = 3;while not valid_input and attempts < max_attempts { attempts += 1; // Simulate getting input (in real code, use input()) let value = attempts * 10; if value >= 10 and value <= 100 { println(f"Valid input: {value}"); valid_input = true; } else { println("Invalid input, try again"); }}if not valid_input { println("Max attempts reached");}
let users = [ {"name": "Alice", "age": 30}, {"name": "Bob", "age": 25}, {"name": "Charlie", "age": 35}];let found = false;for user in users { if user["name"] == "Bob" { println(f"Found Bob, age: {user['age']}"); found = true; break; }}if not found { println("User not found");}
let numbers = [1, 2, 3, 4, 5];let sum = 0;for num in numbers { sum += num;}println(f"Sum: {sum}");
let words = ["apple", "banana", "apple", "cherry", "apple"];let apple_count = 0;for word in words { if word == "apple" { apple_count += 1; }}println(f"Apples: {apple_count}");
let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];let filtered = [];for num in numbers { if num > 5 { filtered.push(num); }}println(filtered); // [6, 7, 8, 9, 10]
let items = ["a", "b", "c", "d", "e"];let target = "c";let index = -1;for i in 0..len(items) { if items[i] == target { index = i; break; }}println(f"Found at index: {index}");
Use while when the number of iterations is unknown
// Good: for with rangefor i in 0..10 { println(i);}// Good: for with collectionfor item in items { process(item);}// Good: while with conditionwhile not done { done = check_condition();}
Avoid deeply nested conditionals
Use early returns or refactor into functions:
// Instead of deep nestingif condition1 { if condition2 { if condition3 { // do something } }}// Use early returnsfn process : { if not condition1 { return; } if not condition2 { return; } if not condition3 { return; } // do something}