# Type ? at the julia> prompt, then type digits(10)
digits(10)2-element Vector{Int64}:
0
1
This tutorial will give some examples of basic Julia commands and syntax. It is written for students who have taken an introductory scientific programming course in Python, and highlights key differences between the two languages.
If you are coming from Python, here are the most important differences to keep in mind as you read.
Julia indexes arrays starting at 1, not 0. arr[1] is the first element. This is consistent with MATLAB, R, and Fortran, but different from Python and C.
true and false are lowercasePython uses True and False. Julia uses true and false.
Python organizes code with classes and methods (obj.method()). Julia uses functions and multiple dispatch: you define functions that behave differently depending on the types of all their arguments. There is no self and no method-calling dot. Instead of arr.sort(), you write sort(arr).
.In NumPy, np.sqrt(arr) automatically applies to every element. In Julia, you must opt in to element-wise application with a dot: sqrt.(arr). The dot is the broadcast operator and is one of the most distinctive parts of Julia syntax.
Variables defined inside a loop or if block in a function or script are local to that block by default. This is stricter than Python. If you define x inside a for loop, x won’t exist after the loop ends (unless you declare it with local or assign to it in an outer scope first).
using, import, and includeusing PackageName loads a package and brings its exported names into scope (like from package import *).import PackageName loads a package but requires qualification (PackageName.func()).include("filename.jl") is completely different: it runs a source file as if you had typed it at the REPL. It does not create a module or namespace.*, not +Julia reserves + for numeric addition only. To join strings, use * or the string() function.
Julia’s interactive environment (the REPL, for Read-Eval-Print-Loop) has several modes beyond just typing code:
| Mode | How to enter | Prompt | Purpose |
|---|---|---|---|
| Julia | (default) | julia> |
Evaluate Julia expressions |
| Help | ? |
help?> |
Look up function documentation |
| Package | ] |
pkg> |
Add/remove/update packages |
| Shell | ; |
shell> |
Run shell commands |
For example, to break 10 into its digits:
To add a package:
To list files in the current directory:
As a result, you can install packages, read documentation, and manage files without leaving Julia.
?functionname to get help.You can suppress output using a semi-colon (;).
That didn’t show anything, as opposed to:
Suppressing output is usually unnecessary but can be useful when you are doing a multi-step calculation and don’t want to see the intermediate results or when the output of a command is extremely large.
begin...end BlocksSometimes you need to group multiple expressions together — for example, to suppress the output of a multi-line computation. Use a begin...end block:
The block returns the value of its last expression (in this case, into x, which has a value of a + b). begin...end is the equivalent of wrapping expressions in parentheses in Python when you need multiple statements in a position that expects one.
Note that a and b will not exist outside of the begin...end block, because they are local to that block. If you want to use them later, you need to define them outside of the block.
Variables are names which correspond to some type of object. These names are bound to objects (and hence their values) using the = operator.
Variables can be manipulated with standard arithmetic operators.
Another advantage of Julia is the ability to use Greek letters (or other Unicode characters) as variable names. For example, type a backslash followed by the name of the Greek letter (i.e. \alpha) followed by TAB.
You can also include subscripts or superscripts in variable names using \_ and \^, respectively, followed by TAB. If using a Greek letter followed by a sub- or super-script, make sure you TAB following the name of the letter before the sub- or super-script. Effectively, TAB after you finish typing the name of each \character.
However, try not to overwrite predefined names! For example, you might not want to use π as a variable name…
In the grand scheme of things, overwriting π is not a huge deal unless you want to do some trigonometry. However, there are more important predefined functions and variables that you may want to be aware of. Always check that a variable or function name is not predefined!
Every value in Julia has a type. Types determine what operations are valid on a value and how it is stored in memory. Julia’s type system is dynamic: you don’t have to declare types for variables (unlike C), but the compiler infers them automatically. You can optionally annotate types to improve performance or enforce constraints.
This is different from Python’s duck typing: in Python, any object that has a .sort() method can be sorted. In Julia, sort() dispatches to a specific implementation based on the concrete type of the argument. This gives Julia C-like performance without C-like verbosity.
You can identify the type of a variable or expression with the typeof() function.
A key distinction is between an integer type (or Int) and a floating-point number type (or float). Integers only hold whole numbers, while floating-point numbers correspond to numbers with fractional (or decimal) parts. For example, 9 is an integer, while 9.25 is a floating point number. The difference between the two has to do with the way the number is stored in memory. 9, an integer, is handled differently in memory than 9.0, which is a floating-point number, even though they’re mathematically the same value.
Sometimes certain function specifications will require you to use a Float variable instead of an Int. One way to force an Int variable to be a Float is to add a decimal point at the end of the integer.
Strings hold characters, rather than numeric values. Even if a string contains what seems like a number, it is actually stored as the character representation of the digits. As a result, you cannot use arithmetic operators (for example) on this datum.
MethodError: no method matching +(::String, ::Int64) The function `+` exists, but no method is defined for this combination of argument types. Closest candidates are: +(::Any, ::Any, ::Any, ::Any...) @ Base operators.jl:596 +(::Missing, ::Number) @ Base missing.jl:123 +(::Complex{Bool}, ::Real) @ Base complex.jl:323 ... Stacktrace: [1] top-level scope @ ~/Teaching/BEE4750/fall2026/tutorials/julia-basics.qmd:201
However, you can try to tell Julia to interpret a string encoding a numeric character as a numeric value using the parse() function. This can also be used to encode a numeric data as a string.
Two strings can be concatenated using *:
A range represents a sequence of numbers without storing all of them in memory. Ranges are created with the colon operator : and are the standard way to express iteration bounds or evenly-spaced sequences.
1.0:0.5:3.0
Ranges are lazy — 1:1000000 takes almost no memory, just like Python’s range(1, 1000001). But unlike Python’s range, you can use Julia ranges directly in arithmetic and they work as you’d expect (broadcasting aside). To materialize a range into an array, use collect(r).
nothing, missing, and NaNJulia distinguishes three kinds of “absent” or “invalid” values, which is important for data analysis:
| Value | Meaning | Use case |
|---|---|---|
nothing |
No value / void return | The return value of println; a function that has nothing useful to return |
missing |
Data is absent (from Missings.jl) |
A missing survey response; propagates through calculations (missing + 1 → missing) |
NaN |
Not a Number (Float64) | The result of 0/0; propagates differently from missing — NaN + 1 is still NaN |
For this course, you’ll encounter missing most often when loading real-world datasets with gaps. Use skipmissing(data) to filter out missing values, or coalesce.(data, 0.0) to replace them with a default.
A NamedTuple is like a tuple where each element has a name. They are lightweight, immutable, and very useful for passing structured options to functions.
Named tuples are the Julia equivalent of Python’s simple data classes or lightweight dictionaries. Many Julia functions (especially in plotting) accept named tuples for keyword-style options.
Boolean variables (or Bools) are logical variables, that can have true or false as values. (Note: these are lowercase — Python uses True/False.)
Numerical comparisons, such as ==, !=, or <, return a Bool.
Bools are important for logical flows, such as if-then-else blocks or certain types of loops.
Addition, subtraction, multiplication, and division work as you would expect. Just pay attention to types! The type of the output is influenced by the type of the inputs: adding or multiplying an Int by a Float will always result in a Float, even if the Float is mathematically an integer. Division is a little special: dividing an Int by another Int will still return a float, because Julia doesn’t know ahead of time if the denominator is a factor of the numerator.
Raising a base to an exponent uses ^, not **.
Julia allows the use of updating operators to simplify updating a variable in place (in other words, using x += 5 instead of x = x + 5.
Logical operations can be used on variables of type Bool. Typical operators are && (and), || (or), and ! (not).
Comparisons can be chained together.
We didn’t do this above, since Julia doesn’t require it, but it’s easier to understand these types of compound expressions if you use parentheses to signal the order of operations. This helps with debugging!
Data structures are containers which hold multiple values in a convenient fashion. Julia has several built-in data structures, and there are many extensions provided in additional packages.
Tuples are collections of values. Julia will pay attention to the types of these values, but they can be mixed. Tuples are also immutable: their values cannot be changed once they are defined.
Tuples can be defined by just separating values with commas.
To access a value, use square brackets and the desired index.
Julia indexing starts at 1, not 0!
As mentioned above, tuples are immutable. What happens if we try to change the value of the first element of test_tuple?
MethodError: no method matching setindex!(::Tuple{Int64, Int64, Int64}, ::Int64, ::Int64)
The function `setindex!` exists, but no method is defined for this combination of argument types.
Stacktrace:
[1] top-level scope
@ ~/Teaching/BEE4750/fall2026/tutorials/julia-basics.qmd:357
Tuples also do not have to hold the same types of values.
Tuples can also be defined by enclosing the values in parentheses.
Arrays also hold multiple values, which can be accessed based on their index position. Arrays are commonly defined using square brackets.
Unlike tuples, arrays are mutable, and their contained values can be changed later.
Arrays also can hold multiple types. Unlike tuples, this causes the array to no longer care about types at all.
Compare this with test_array:
Instead of using integer indices based on position, dictionaries are indexed by keys. They are specified by passing key-value pairs to the Dict() method.
Creating a data structure with more than a handful of elements can be tedious to do by hand. If your desired array follows a certain pattern, you can create structures using a comprehension. Comprehensions iterate over some other data structure (such as an array) implicitly and populate the new data structure based on the specified instructions.
For dictionaries, make sure that you also specify the keys.
Dict{String, Int64} with 6 entries:
"4" => 16
"1" => 1
"5" => 25
"0" => 0
"2" => 4
"3" => 9
Comprehensions are powerful and are extremely useful for simple tasks. However, they can be difficult to read if they are too long or complicated, such as if multiple commands are required to populate the data structure. In these cases, it is better to use a loop. Always prioritize readability over conciseness.
map, filter, and reduceComprehensions are the most idiomatic way to transform collections in Julia, but you can also use map, filter, and reduce — these work similarly to Python:
5-element Vector{Int64}:
1
4
9
16
25
A useful pattern: mapreduce combines the two in one pass:
A function is an object which accepts a tuple of arguments and maps them to a return value. In Julia, functions are defined using the following syntax.
Functions in Julia do not require explicit use of a return statement. They will return the last expression evaluated in their definition. However, it’s good style to explicitly return function outputs. This improves readability and debugging, especially when functions can return multiple expressions based on logical control flows (if-then-else blocks).
Functions in Julia are objects, and can be treated like other objects. They can be assigned to new variables or passed as arguments to other functions.
Try to structure your code using functions as often as possible to reduce bugs and simplify debugging! If you find yourself copying and pasting code, or writing the same code multiple times, consider writing a function instead. If there’s a mistake in that code, you only have to find it and fix it once.
This will also make your code more readable and easier to follow, as function names should be chosen to make it clear what that chunk of code is doing.
In addition to the long form of the function definition shown above, simple functions can be specified in more compact forms when helpful.
This is the short form:
This is the anonymous form:
The convention in Julia is that functions should not modify (or mutate) their input data. The reason for this is to ensure that the data are preserved. Mutating functions are mainly appropriate for applications where performance needs to be optimized, and making a copy of the input data would be too memory-intensive.
If you do write a mutating function in Julia, the convention is to add a ! to its name, like my_mutating_function!(x). This makes it clear to anyone reading or using your code that they should expect x to be modified, rather than the output of my_mutating_function to be stored in a different variable.
There are two extremes with regard to function parameters which do not always need to be changed.
Most modern languages, including Julia, allow an alternate solution, which is to make these arguments optional. This involves setting a default value, which is used unless the argument is explicitly defined in a function call.
setting_optional_arguments (generic function with 2 methods)
If we want to stick with the fixed value \(c=0.5\), all we have to do is call setting_optional_arguments with the x and y arguments.
Otherwise, we can pass a new value for c.
Instead of passing variables individually, it may make sense to pass a data structure, such as an array or a tuple, and then unpacking within the function definition. This is straightforward in long form: access the appropriate elements using their index.
In short or anonymous form, there is a trick which allows the use of readable variables within the function definition.
h₂ (generic function with 1 method)
MethodError: no method matching h₂(::Int64, ::Int64) The function `h₂` exists, but no method is defined for this combination of argument types. Closest candidates are: h₂(::Any) @ Main.Notebook ~/Teaching/BEE4750/fall2026/tutorials/julia-basics.qmd:535 Stacktrace: [1] top-level scope @ ~/Teaching/BEE4750/fall2026/tutorials/julia-basics.qmd:543
Julia uses dot syntax to broadcast an operation element-wise across an array. This is the Julia equivalent of NumPy’s automatic vectorization, but it’s explicit — you add a . wherever you want element-wise behavior.
Julia requires you to opt-in to broadcasting because it allows you to write code that is clear and has expected behavior: if you do not want a function to be used on a array, a function that lacks broadcasting will throw an error, alerting a user that they are using the function incorrectly. This is a common source of bugs in Python (or R), where functions are often written to accept both scalars and arrays, but the behavior is not always what the user expects. And with multiple dispatch, if you want scalars and arrays to handled differently, you can use two different methods for the same function name, each with the appropriate logic.
| Python (NumPy) | Julia |
|---|---|
np.sqrt(arr) |
sqrt.(arr) |
arr * 2 |
arr .* 2 |
arr1 + arr2 |
arr1 .+ arr2 |
np.sin(arr) |
sin.(arr) |
f(arr) where f is your function |
f.(arr) |
The dot fuses: sin.(cos.(x)) is equivalent to a single loop and as fast as writing it by hand.
For example, to calculate the square root of 3:
To calculate the square roots of every integer between 1 and 5:
5-element Vector{Float64}:
1.0
1.4142135623730951
1.7320508075688772
2.0
2.23606797749979
The same dot syntax works for arithmetic:
And for your own functions:
You can also use the @. macro to broadcast an entire expression at once:
3-element Vector{Float64}:
0.5143952585235492
-0.4042391538522658
-0.8360218615377305
Broadcasting is faster than writing a loop by hand (Julia fuses the operations) and is the standard way to write vectorized code. Use it liberally!
|>Julia has a pipe operator |> that chains function calls left-to-right:
This is equivalent to sum(filter(iseven, [1,2,3,4,5])) but avoids deeply nested parentheses. Pipelines are especially common in data-analysis workflows with DataFrames.jl.
You can return multiple values by separating them with a comma. This implicitly causes the function to return a tuple of values.
These values can be unpacked into multiple variables.
nothingSometimes you don’t want a function to return any values at all. For example, you might want a function that only prints a string to the console.
The Text() function returns its argument as a plain text string. Notice how this is different from evaluating a string!
Text() is used in this tutorial as it returns the string passed to it. To print directly to the console, use println().
What if we want to include the value of a variable inside of a string? We do this using string interpolation, using $variablename inside of the string.
One of the tricky things about learning a new programming language can be getting used to the specifics of control flow syntax. These types of flows include conditional if-then-else statements or loops.
Conditional blocks allow different pieces of code to be evaluated depending on the value of a boolean expression or variable. For example, if we wanted to compute the absolute value of a number, rather than using abs():
our_abs (generic function with 1 method)
To nest conditional statements, use elseif.
test_sign (generic function with 1 method)
Loops allow expressions to be evaluated repeatedly until they are terminated. The two main types of loops are while loops and for loops.
while loops continue to evaluate an expression so long as a specified boolean condition is true. This is useful when you don’t know how many iterations it will take for the desired goal to be reached.
120
While loops can easily turn into infinite loops if the condition is never meaningfully updated. Be careful, and look there if your programs are getting stuck. Also, if the expression in a while loop is false when the loop is reached, the loop will never be evaluated.
for loops run for a finite number of iterations, based on some defined index variable.
10
for loops can also iterate over explicitly passed containers, rather than iterating over an incrementally-updated index sequence. Use the in keyword when defining the loop.
enumerate, zip, and pairsThese functions work similarly to their Python counterparts:
Item 1 is a
Item 2 is b
Item 3 is c
1 + 4 = 5
2 + 5 = 7
3 + 6 = 9
This is Julia’s most important concept. A generic function is a function that can have many methods, each specialized for different combinations of argument types.
"\"hello\" is a string"
Julia calls this multiple dispatch because the specific method is chosen based on the types of all arguments, not just the first one (unlike Python’s single dispatch in traditional OOP).
To take advantage of multiple dispatch (and to write fast code), annotate arguments with their expected types, such as the ::Int and ::String annotations above. If you omit them, the compiler does not know what types to expect, and as a result will generate slower generic code and will not know how to choose the appropriate method.
You can also annotate return types, but this is less common.
In Python, you might write obj.method() where obj’s class determines which method runs. In Julia, you write method(obj) and the types of all arguments collectively determine the implementation. This is why Julia doesn’t need classes — dispatch replaces inheritance.
Matrices are defined in Julia as 2d arrays. Unlike basic arrays, matrices need to contain the same data type so Julia knows what operations are allowed. When defining a matrix, use semicolons to separate rows. Row elements should not be separated by commas.
You can also specify matrices using spaces and newlines.
Finally, matrices can be created using comprehensions by separating the inputs by a comma.
5×5 Matrix{Int64}:
1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25
Vectors are treated as 1d matrices.
Many linear algebra operations on vectors and matrices can be loaded using the LinearAlgebra package.
The CSV.jl package (which needs to be installed separately into an environment; I will include this by default for assignments where file I/O is needed) reads comma-separated files into a DataFrame (this will result in an error because we don’t have the actual file):
WARNING: using DataFrames.describe in module Notebook conflicts with an existing identifier.
| Row | time | sensor_a | sensor_b |
|---|---|---|---|
| Float64 | Float64 | Float64 | |
| 1 | 0.0 | 12.3 | 45.1 |
| 2 | 1.0 | 12.5 | 45.0 |
| 3 | 2.0 | 12.8 | 44.8 |
| 4 | 3.0 | 13.0 | 44.5 |
| 5 | 4.0 | 13.1 | 44.3 |
| 6 | 5.0 | 13.3 | 44.0 |
For plain text files, use read() (or more often, readlines()) and write():
"Experimental run: Trial A\nDate: 2024-01-15\nTemperature: 22.5 C\nPressure: 101.3 kPa\nConcentration: 0.45 mol/L\n"
5-element Vector{String}:
"Experimental run: Trial A"
"Date: 2024-01-15"
"Temperature: 22.5 C"
"Pressure: 101.3 kPa"
"Concentration: 0.45 mol/L"
DelimitedFiles (standard library)For simple numeric matrices, use readdlm from the standard library:
3×3 Matrix{Float64}:
1.0 2.0 3.0
4.0 5.0 6.0
7.0 8.0 9.0
readdlm() will also work with other delimiters, such as tabs or spaces, by passing a second argument:
Julia’s approach to error handling is for you to try a command, and if it fails, to catch the error and handle it gracefully. This is similar to Python.
Use try/catch blocks to handle errors gracefully:
Caught a DomainError: sqrt was called with a negative real argument but will only return a complex result if called with a complex argument. Try sqrt(Complex(x)).
NaN
For more specific handling, catch particular exception types (you can e.g. explain the error in plainer language than the default error message):
Cannot take sqrt of a negative real: DomainError(-1.0, "sqrt was called with a negative real argument but will only return a complex result if called with a complex argument. Try sqrt(Complex(x)).")
Julia can match C speeds, but only if you avoid a few common pitfalls. Here are the most important ones:
Put performance-critical code inside functions. Code at global scope is slower because the compiler can’t assume types are stable.
Avoid changing variable types. If x starts as an Int and later becomes a Float64, the compiler must generate slower generic code. This is called type instability.
Pre-allocate arrays. Instead of push!-ing one element at a time, create an array of the right size with zeros(n) or Vector{Float64}(undef, n) and fill it.
You can check your code’s performance with @time:
0.000000 seconds
5000000050000000
The first run includes compilation time (Julia compiles functions the first time they’re called). Run it twice to see the steady-state speed.
A lack of memory pre-allocation is a common source of slowdowns. Here is a concrete comparison. Both functions compute the squares of 1:n, but the first grows the array incrementally while the second allocates ahead of time:
function squares_push(n)
result = Float64[] # empty array
for i in 1:n
push!(result, i^2) # reallocates on every append
end
return result
end
function squares_prealloc(n)
result = Vector{Float64}(undef, n) # allocate once
for i in 1:n
result[i] = i^2 # write to existing slot
end
return result
end
@time squares_push(10^6);
@time squares_push(10^6); # second call: steady-state speed 0.003162 seconds (24 allocations: 17.477 MiB)
0.009288 seconds (24 allocations: 17.477 MiB, 75.73% gc time)
0.001269 seconds (3 allocations: 7.641 MiB)
0.001196 seconds (3 allocations: 7.641 MiB)
The pre-allocated version is typically 3–10× faster and allocates far less memory. The difference grows with n.
include(): Running Script FilesIn Python, import file loads a module. In Julia, include("file.jl") runs a source file as if you typed its contents into the REPL. No module or namespace is created — everything defined in the file becomes available in your current scope. This is the standard way to load helper code or split a large project across multiple files.
SystemError: opening file "/Users/vs498/Teaching/BEE4750/fall2026/tutorials/myfunctions.jl": No such file or directory Stacktrace: [1] include(fname::String) @ QuartoNotebookWorker.NotebookInclude ~/.julia/packages/QuartoNotebookRunner/evCNi/src/QuartoNotebookWorker/src/NotebookInclude.jl:10 [2] top-level scope @ ~/Teaching/BEE4750/fall2026/tutorials/julia-basics.qmd:1003
Sometimes you might need functionality that does not exist in base Julia. Julia handles packages using the Pkg package manager. After finding a package which has the functions that you need, you have two options:
julia in your terminal). Enter this by typing ] at the standard green Julia prompt julia>. This will become a blue pkg>. You can then add new packages using add packagename.import Pkg; Pkg.add(packagename). The packagename package can then be used by adding using packagename to the start of the script.
Comments
Comments hide statements from the interpreter or compiler. It’s a good idea to liberally comment your code so readers (including yourself!) know why your code is structured and written the way it is. Good comments focus on the why of the code logic and structure, not the what or the how. The what and how should be clear from the code itself.
Single-line comments in Julia are preceded with a
#. Multi-line comments are preceded with#=and ended with=#