print and println@printftry-catch for Exception HandlingfinallyPrograms often need to make decisions and execute different pieces of code based on certain conditions. Just like you might decide to take an umbrella if it's raining, or choose a different route if there's traffic, Julia programs can evaluate conditions and alter their behavior accordingly. This decision-making capability is fundamental to writing useful and interactive software. The primary tools for this in Julia are the if, elseif, and else statements, which allow you to define conditional execution paths in your code.
if Statement: Basic Conditional ExecutionThe simplest form of conditional execution is the if statement. It allows a block of code to be executed only if a specified condition is true.
The basic structure looks like this:
if condition
# Code to execute if the condition is true
end
Here, condition is an expression that must evaluate to a Boolean value, either true or false. If condition is true, the code indented between if and end is executed. If condition is false, this block of code is skipped, and the program continues with any statements after the end keyword. The end keyword is essential; it marks the termination of the if block.
Let's consider an example. Suppose we want to print a message only if a number is positive:
x = 10
if x > 0
println("The number is positive.")
end
y = -5
if y > 0
println("This message will not be printed for y.") # This line won't execute
end
In the first part, the condition x > 0 (which is 10>0) evaluates to true, so the statement println("The number is positive.") is executed. In the second part, y > 0 (which is −5>0) evaluates to false. Consequently, the println statement associated with y is skipped.
else StatementOften, you'll want to execute one block of code if a condition is true and a different block of code if the condition is false. This is where the else statement comes into play. It provides an alternative execution path when the if condition is not met.
The structure is:
if condition
# Code to execute if the condition is true
else
# Code to execute if the condition is false
end
If condition evaluates to true, the first block of code (indented under if) is executed, and the else block is skipped. Conversely, if condition evaluates to false, the if block is skipped, and the else block is executed.
Let's expand our previous example to handle both positive and non-positive numbers:
temperature = 15 # degrees Celsius
if temperature > 20
println("It's warm, no need for a jacket.")
else
println("It might be chilly, consider a jacket.")
end
In this scenario, temperature > 20 (15>20) is false. Therefore, the code inside the else block is executed, and "It might be chilly, consider a jacket." is printed. If temperature were, for instance, 25, the if block would execute instead, printing "It's warm, no need for a jacket."
elseifSometimes, you need to check several different conditions in sequence. If the first condition isn't met, you might want to check a second, then a third, and so on, until one is found to be true or all conditions have been checked. The if-elseif-else structure allows for this kind of multi-path decision making.
The general syntax is:
if condition1
# Code to execute if condition1 is true
elseif condition2
# Code to execute if condition1 is false AND condition2 is true
elseif condition3
# Code to execute if condition1 and condition2 are false AND condition3 is true
# ... you can have more elseif clauses ...
else
# Code to execute if ALL preceding conditions are false
end
Julia evaluates these conditions one by one, from top to bottom:
condition1 is true, its associated code block is executed, and the rest of the elseif and else blocks are skipped entirely.condition1 is false, Julia then proceeds to check condition2. If condition2 is true, its code block is executed, and any subsequent elseif and else blocks are skipped.elseif clauses.if or elseif conditions evaluate to true, the code block under the optional else statement is executed. If the else clause is omitted and all conditions are false, then no code within the entire if-elseif-else structure is executed.Consider an example for assigning grades based on a score:
score = 78
if score >= 90
println("Grade: A")
elseif score >= 80
println("Grade: B")
elseif score >= 70
println("Grade: C")
elseif score >= 60
println("Grade: D")
else
println("Grade: F")
end
Given score = 78:
score >= 90 (78≥90), is false.elseif. The condition score >= 80 (78≥80) is also false.elseif. The condition score >= 70 (78≥70) is true.println("Grade: C") is executed.elseif and else blocks are skipped, and the program continues after the final end.The order of elseif conditions is very important, especially when the conditions might overlap. In the grading example, if we had mistakenly ordered the checks like elseif score >= 70 before elseif score >= 80, a score of 85 would incorrectly result in "Grade: C" because 85≥70 is true and would be evaluated first.
Flow of execution in an
if-elseif-elsestructure. The program evaluates conditions sequentially until one is true or it reaches theelseblock.
The conditions in if, elseif, and else statements are boolean expressions. These expressions can be simple comparisons (e.g., age >= 18, name == "Julia") or more complex logical constructions built using Julia's logical operators: && (logical AND), || (logical OR), and ! (logical NOT). You've already encountered these operators earlier in this chapter.
Logical AND (&&): An expression condition1 && condition2 evaluates to true only if both condition1 and condition2 are true.
age = 25
has_drivers_license = true
if age >= 18 && has_drivers_license
println("Eligible to drive.")
else
println("Not eligible to drive.") # This would print if either condition was false
end
Logical OR (||): An expression condition1 || condition2 evaluates to true if at least one of condition1 or condition2 is true.
is_weekend = true
is_public_holiday = false
if is_weekend || is_public_holiday
println("Enjoy your day off!") # Prints because is_weekend is true
else
println("Back to work or school.")
end
Logical NOT (!): The ! operator inverts the boolean value of a condition. If condition is true, !condition is false, and vice-versa.
is_raining = false
if !is_raining # This is true because is_raining is false
println("It's not raining, good weather for a walk.")
end
You can combine these operators and use parentheses () to group sub-expressions and explicitly control the order of evaluation, much like in arithmetic expressions. For example: (is_student && age < 25) || has_discount_card.
A noteworthy feature of && and || operators in Julia (and many other languages) is short-circuit evaluation:
a && b: If a evaluates to false, the expression b is not evaluated at all, because the entire && expression must be false regardless of b's value.a || b: If a evaluates to true, the expression b is not evaluated, because the entire || expression must be true regardless of b's value.Short-circuiting is not just an optimization; it can be used to prevent errors. For instance, in count > 0 && sum / count > 50, if count is 0, the sum / count part is never evaluated, avoiding a potential division-by-zero error.
It's also possible to place if-elseif-else structures inside other if-elseif-else structures. This is known as nesting.
x = 10
y = -3
if x > 0
println("x is positive.")
if y > 0
println("y is also positive.")
else
println("y is not positive.") # This will be printed
end
else
println("x is not positive.")
end
In this example, the inner if-else block (which checks the sign of y) is only reached and executed if the outer condition (x > 0) is true.
Nesting provides a way to model more complex decision trees. However, be mindful that deeply nested conditional statements (e.g., more than two or three levels) can quickly make code difficult to read, understand, and debug. If you find your code becoming too convoluted with nesting, it might be a signal to rethink your logic. Sometimes, breaking the problem into smaller functions or using different control flow approaches can lead to clearer code.
By mastering if, elseif, and else, you gain a powerful tool for controlling the flow of your Julia programs, enabling them to respond intelligently to different inputs and states.
Was this section helpful?
© 2026 ApX Machine LearningEngineered with