Part 03 - Flow Control - Conditionals
If Statement
| Definition: if statement A control statement that contains one or more Boolean expressions whose results determine whether to execute other statements within the If statement. |
An if statemnt allows you to travel down multiple logical paths, depending on a condition given. If the condition given is true, the block of code associated with it will be run.
i is equal to 5.
| Be careful notice the difference between If you try an assignment while running a conditional, Boo will emit a warning. |
You may have noticed that unlike other languages, there is no then-endif or do-end or braces { }. Blocks of code are determined in Boo by its indentation. By this, your code blocks will always be noticeable and readable.
| Recommendation Always use tabs for indentation. |
You can have multiple code blocks within eachother as well.
i is greater than 0. i is less than 10.
If-Else Statement
With the if statement comes the else statement. It is called when your if statement's condition is false.
i is less than or equal to 5.
Quite simple.
If-Elif-Else Statement
Now if you want to check for a condition after your if is false, that is easy as well. This is done through the elif statement.
i is equal to 5.
You can have one if, any number of elif s, and an optional else .
Unless Statement
The unless statement is handy if you want a readable way of checking if a condition is not true.
It didn't output because i was equal to 5 in that case.
Statement with Modifier
Like in Ruby and Perl, you can follow a statement with a modifier.
0 5 5
| Recommendation Don't use Statement with Modifier on a long line. In that case, you should just create a code block. |
Some common conditionals:
Operator |
Meaning |
Example |
|---|---|---|
|
equal |
|
|
not equal |
|
|
greater than |
|
|
less than |
|
|
greater than or equal to |
|
|
less than or equal to |
|
Not Condition
To check if a condition is not true, you would use not.
i is not greater than 5
Combining Conditions
To check more than one condition, you would use and or or. Use parentheses ( ) to change the order of operations.
Note that and requires that both comparisons are true, while or requires that only one is true or both are true.
i is between 0 and 10.
Exercises
- Given the numbers x = 4, y = 8, and z = 6, compare them and print the middle one.
Go on to Part 04 - Flow Control - Loops
