Control Flow
Stable
Control flow syntax is stable in Levython 1.0.
Control the execution of your code with if, elif, and else
statements.
Table of Contents
If Statements#
Execute code when a condition is true:
if condition { body }
levython
age <- 25
if age >= 18 {
say("You are an adult")
}
# With variables
is_valid <- true
if is_valid {
say("Valid!")
}
If-Else#
Execute alternative code when the condition is false:
if condition { body } else { alternative }
levython
temperature <- 72
if temperature > 80 {
say("It's hot!")
} else {
say("It's comfortable")
}
# Output: It's comfortable
If-Elif-Else#
Check multiple conditions in sequence:
if condition1 { ... } elif condition2 { ... } else { ... }
levython
score <- 85
if score >= 90 {
say("Grade: A")
} elif score >= 80 {
say("Grade: B")
} elif score >= 70 {
say("Grade: C")
} elif score >= 60 {
say("Grade: D")
} else {
say("Grade: F")
}
# Output: Grade: B
Comparison Operators#
Use these operators to create conditions:
| Operator | Description | Example | Result |
|---|---|---|---|
== |
Equal to | 5 == 5 |
true |
!= |
Not equal to | 5 != 3 |
true |
> |
Greater than | 10 > 5 |
true |
< |
Less than | 3 < 10 |
true |
>= |
Greater than or equal | 5 >= 5 |
true |
<= |
Less than or equal | 3 <= 10 |
true |
levython
x <- 50
y <- 50
if x == y {
say("x equals y")
}
if x != 0 {
say("x is not zero")
}
if x >= 1 {
if x <= 100 {
say("x is between 1 and 100")
}
}
Logical Operators#
Combine multiple conditions using logical operators:
| Operator | Description | Example |
|---|---|---|
and |
Logical AND (both conditions must be true) | x > 0 and x < 10 |
or |
Logical OR (at least one condition must be true) | x < 0 or x > 100 |
not |
Logical NOT (inverts boolean value) | not is_valid |
levython
# AND operator - both conditions must be true
age <- 25
has_license <- true
if age >= 18 and has_license {
say("You can drive")
}
# OR operator - at least one condition must be true
day <- "Saturday"
is_holiday <- false
if day == "Saturday" or day == "Sunday" or is_holiday {
say("It's a day off!")
}
# NOT operator - inverts boolean
is_raining <- false
if not is_raining {
say("Let's go outside!")
}
# Complex conditions with parentheses
score <- 85
bonus_points <- 10
if (score >= 90) or (score >= 80 and bonus_points >= 10) {
say("Grade: A")
}
Short-Circuit Evaluation
Logical operators use short-circuit evaluation for efficiency:
and: If left side isfalse, right side is not evaluatedor: If left side istrue, right side is not evaluated
levython
# Safe division check using short-circuit
x <- 10
y <- 0
# y != 0 is checked first, preventing division by zero
if y != 0 and x / y > 5 {
say("Quotient is greater than 5")
} else {
say("Cannot divide or quotient is not > 5")
}
Nested Conditionals#
Conditionals can be nested inside each other:
levython
age <- 25
has_license <- true
if age >= 18 {
if has_license {
say("You can drive")
} else {
say("Get a license first")
}
} else {
say("Too young to drive")
}
# Output: You can drive