print and println@printftry-catch for Exception HandlingfinallyMany programs become much more useful when they can interact with the user, asking for information or instructions during runtime. Displaying information using print and println is one aspect of program communication; the other side is obtaining input from the user. Julia provides straightforward ways to read data entered into the console.
readlineThe primary function for capturing user input from the console in Julia is readline(). When your program encounters readline(), it pauses execution and waits for the user to type something into the console and press Enter. Whatever the user types before pressing Enter is then returned by the function as a string.
Let's try a simple example. If you run the following code in a Julia REPL or as a script:
print("Please enter your name: ")
name = readline()
println("Hello, ", name, "!")
The program will first display "Please enter your name: ". Then, it will wait. If you type "JuliaFan" and press Enter, the variable name will store the string "JuliaFan". The program will then output:
Hello, JuliaFan!
Notice that readline() captures everything up to the Enter key press. The newline character itself (from pressing Enter) is typically not included in the returned string, which is usually what you want.
A very important point to remember is that readline() always returns the input as a String data type, regardless of what the user types. If the user types 42, readline() will return the string "42", not the number 42.
This has implications if you intend to perform numerical operations with the input. Consider this:
print("Enter the first number: ")
num_str1 = readline()
print("Enter the second number: ")
num_str2 = readline()
result = num_str1 + num_str2 # This will be string concatenation!
println("The 'sum' is: ", result)
If you enter 10 for the first number and 20 for the second, you might expect the output The 'sum' is: 30. However, since num_str1 is "10" and num_str2 is "20" (both strings), the + operator performs string concatenation. The output will actually be:
The 'sum' is: 1020
This is clearly not the arithmetic sum we were hoping for. To treat user input as numbers, or any other data type, we need to convert it.
parseJulia provides the parse() function to convert a string into another data type, such as an integer or a floating-point number. The general syntax is parse(TargetType, string_value).
Let's modify our previous example to correctly calculate the sum:
print("Enter the first number: ")
num_str1 = readline()
num1 = parse(Int, num_str1) # Convert to an Integer
print("Enter the second number: ")
num_str2 = readline()
num2 = parse(Int, num_str2) # Convert to an Integer
result = num1 + num2
println("The sum is: ", result)
Now, if you enter 10 and 20, num1 will become the integer 10 and num2 will become the integer 20. The + operator will perform addition, and you'll correctly see:
The sum is: 30
Similarly, if you expect decimal input, you can parse it as a floating-point number, typically Float64:
print("Enter a price: ")
price_str = readline()
price = parse(Float64, price_str)
println("The price you entered is: \$", price)
If the user enters 19.99, price will be the floating-point number 19.99.
The parse() function is strict. If it cannot convert the string to the specified type (e.g., if the user types "hello" when parse(Int, ...) is called), it will raise an error, and your program will stop. For instance:
print("Enter your age: ")
age_str = readline()
age = parse(Int, age_str) # This line will error if input is not a valid integer
println("Next year, you will be ", age + 1)
If you run this and enter "twenty", you'll see an ArgumentError.
Handling such situations gracefully is a topic for error handling, which we'll cover in more detail in Chapter 8. For now, be aware that parse() expects the input string to be in a format it can convert.
A slightly more forgiving function is tryparse(TargetType, string_value). Instead of raising an error, tryparse returns the converted value if successful, or nothing if the conversion fails. This nothing value is a special Julia object indicating the absence of a value. You can then check for nothing to handle invalid input without the program crashing.
print("Enter your age (numeric): ")
age_str = readline()
age = tryparse(Int, age_str)
if age === nothing
println("Invalid input. Please enter a number for age.")
else
println("Next year, you will be ", age + 1)
end
Using tryparse can make your interactive programs more user-friendly by allowing them to recover from incorrect input.
As seen in the examples, it's common practice to use print() immediately before readline() to display a prompt, guiding the user on what information to enter. This makes the program's interaction clearer.
# Example: A short survey
println("Start our mini-survey!")
print("What is your favorite programming language? ")
fav_lang = readline()
print("How many years have you been programming (e.g., 0, 1, 5.5)? ")
years_str = readline()
years_programming = tryparse(Float64, years_str)
if years_programming === nothing
println("Thank you for sharing about ", fav_lang, ". Your programming experience input was not recognized as a number.")
else
println("Great! So you like ", fav_lang, " and have ", years_programming, " years of experience.")
end
This example demonstrates:
fav_lang) and using it directly.years_programming), attempting to parse it with tryparse, and providing different feedback based on the success of the conversion.Learning to accept and correctly process user input is a fundamental skill for building interactive applications. With readline(), parse(), and tryparse(), you have the tools to make your Julia programs communicate effectively with users.
Was this section helpful?
readline function, The Julia Language, 2024 (The Julia Language) - Provides the official reference and usage details for reading a line of text from the console.© 2026 ApX Machine LearningEngineered with