4. Control flow¶
Control flow is how you branch and loop.
if / elif / else¶
def describe(n: int) -> str:
if n < 0:
return "negative"
elif n == 0:
return "zero"
else:
return "positive"
match (pattern matching)¶
match is the main way to branch on enums like Result and Option:
def main() -> None:
result = parse_port("8080")
match result:
case Ok(port): println(f"port={port}")
case Err(e): println(f"error: {e}")
Coming from Rust?
Incan also supports a more Rust-like match-arm style using =>:
def main() -> None:
match parse_port("8080"):
Ok(port) => println(f"port={port}")
Err(e) => println(f"error: {e}")
This is equivalent to the case ...: form; pick whichever reads best to you.
for loops¶
Incan supports Python-like for loops:
def main() -> None:
items = ["Alice", "Bob", "Cara"]
for name in items:
println(name)
You can break early:
for name in items:
if name == "Bob":
break
Try it¶
- Write a function
classify(n: int) -> strusingif/elif/else. - Use
matchon aResultand print either the value or the error. - Loop over a list and stop early with
break.
One possible solution
# 1) classify function
def classify(n: int) -> str:
if n < 0:
return "negative"
elif n == 0:
return "zero"
else:
return "positive"
def main() -> None:
println(classify(-1)) # negative
println(classify(0)) # zero
println(classify(2)) # positive
# 2) match on Result
match parse_port("8080"):
Ok(port) => println(f"port={port}")
Err(e) => println(f"error={e}")
# 3) loop over a list and stop early with break
items = ["Alice", "Bob", "Cara"]
for name in items:
if name == "Bob":
break
println(name)
Where to learn more¶
- Control flow overview: Control flow
- Enums (often used with
match): Enums - Error handling (deep dive on
Result/Option): Error Handling
Next¶
Back: 3. Functions
Next chapter: 5. Modules and imports