print and println@printftry-catch for Exception HandlingfinallyWhile for loops are excellent for iterating a known number of times or over the elements of a collection, there are many situations where you need a loop to continue as long as a certain condition holds true, without knowing in advance how many iterations that will take. This is where while loops come into play. A while loop repeatedly executes a block of code as long as a specified boolean expression evaluates to true.
The basic structure of a while loop in Julia is:
while condition
# Code to execute while condition is true
end
while Loops Workcondition. This condition is an expression that must result in a boolean value (true or false).condition is true, the code block inside the while...end statements is executed.condition is checked again.condition evaluates to false (either initially or after some number of iterations), the loop terminates, and the program continues with the statement immediately following the end keyword.It's very important that something inside the loop's body eventually causes the condition to become false. Otherwise, the loop will run forever, a situation known as an infinite loop.
while Loop ExampleLet's look at a common task: counting up to a certain number. While a for loop might be more idiomatic for simple counting, a while loop can also achieve this and helps illustrate its mechanics.
Suppose we want to print numbers from 1 to 3:
let
count = 1
while count <= 3
println("Current count: ", count)
count = count + 1 # Or count += 1
end
println("Loop finished!")
end
Output:
Current count: 1
Current count: 2
Current count: 3
Loop finished!
Let's break this down:
count = 1: We initialize a variable count to 1. This variable will be used in our condition and updated within the loop.while count <= 3: This is the condition.
count is 1. 1 <= 3 is true, so the loop body executes.count is 2. 2 <= 3 is true, so the loop body executes.count is 3. 3 <= 3 is true, so the loop body executes.count is 4. 4 <= 3 is false, so the loop terminates.println("Current count: ", count): This line prints the current value of count.count = count + 1: This is a very important line. It increments count. Without this, count would always remain 1, count <= 3 would always be true, and the loop would never end.println("Loop finished!"): This line executes after the loop has terminated.The following diagram shows the general flow of a while loop:
Logic flow of a
whileloop. The loop continues to execute its body as long as the specified condition evaluates to true.
An infinite loop occurs when the condition of a while loop never becomes false. This can happen if you forget to update the variable(s) involved in the condition, or if the logic of the update never allows the condition to be falsified.
For example, if we forgot the count = count + 1 line in the previous example:
# CAUTION: This is an infinite loop!
# let
# count = 1
# while count <= 3
# println("This will print forever: ", count)
# # Missing count = count + 1
# end
# end
This loop would continuously print "This will print forever: 1" because count always stays 1, and 1 <= 3 is always true.
If you accidentally run an infinite loop in the Julia REPL or a script, you can usually stop it by pressing Ctrl+C. This sends an interrupt signal to Julia, asking it to stop the current operation. Being aware of how to stop your program is a useful skill when learning about loops!
A common scenario for while loops is when you need to get valid input from a user. You don't know how many times the user will enter invalid data before providing something acceptable.
Let's say we need the user to enter a positive number:
function get_positive_number()
num_str = ""
num = -1 # Initialize to an invalid number
while num <= 0
print("Please enter a positive number: ")
num_str = readline()
try
num = parse(Float64, num_str)
if num <= 0
println("Not a positive number. Try again.")
end
catch e
println("Invalid input. Please enter a number.")
num = -1 # Reset to ensure loop continues
end
end
println("You entered: ", num)
return num
end
# Example call (uncomment to run in a script or REPL)
# user_number = get_positive_number()
In this example:
while num <= 0.num remains such that num <= 0 is true, causing the loop to repeat.num become greater than 0, making num <= 0 false, and the loop terminates.while true with breakSometimes, the condition to exit a loop is more naturally checked in the middle or at the end of the loop's body, rather than at the very beginning. In such cases, a common pattern is to use while true and then use an if statement combined with the break keyword to exit the loop. As you learned in the "Modifying Loop Behavior: break and continue" section, break immediately terminates the innermost loop it's contained in.
Example: Simulating a process that stops on a specific event.
let
attempts = 0
while true # Loop indefinitely until a break
attempts += 1
println("Attempt: ", attempts)
# Simulate some condition or event
if attempts >= 5
println("Target reached or maximum attempts. Exiting.")
break # Exit the while loop
end
# Simulate some work
# sleep(0.5) # Pauses for 0.5 seconds, requires using Dates
println("...processing...")
end
println("Loop finished after ", attempts, " attempts.")
end
This loop is set to run forever (while true), but the if attempts >= 5 condition inside provides an exit point using break. This can make code clearer if the main loop logic is complex and the exit condition depends on intermediate results calculated within the loop body.
for and whileThe choice between a for loop and a while loop generally comes down to whether you know the number of iterations in advance:
Use for loops:
1:5, an array, or characters in a string).Use while loops:
Understanding while loops adds a powerful tool to your Julia programming toolkit, allowing you to control program flow based on dynamic conditions. This is fundamental for writing programs that can respond to changing states or inputs effectively.
Was this section helpful?
while loops within the Julia programming language.while loops, across various programming paradigms.while loops, from a reputable introductory computer science course.© 2026 ApX Machine LearningEngineered with