Julia Basic Syntax
This chapter introduces the basic syntax rules of Julia to help you get started quickly.
Comments
Single-Line Comments
Use # to start single-line comments:
# This is a single-line comment
x = 10 # End-of-line commentMulti-Line Comments
Use #= and =# to enclose multi-line comments:
#=
This is a multi-line comment
It can span multiple lines
For detailed explanations
=#Variables
Variable Naming
Julia variable names follow these rules:
- Start with letter (A-Z, a-z), underscore (_), or Unicode character
- Can contain digits (but cannot start with digit)
- Case-sensitive
- Cannot use reserved words
# Valid variable names
x = 1
my_variable = 2
变量 = 3 # Chinese supported
α = 0.5 # Greek letters supported
_private = 4
# Invalid variable names
# 2nd = 5 # Cannot start with digit
# for = 6 # Cannot use reserved wordVariable Assignment
# Single assignment
x = 10
# Multiple assignment
a, b, c = 1, 2, 3
# Swap variables
a, b = b, a
# Chained assignment
x = y = z = 0Constants
Use const to declare constants:
const PI = 3.14159
const MAX_SIZE = 100
# Attempting to modify constants produces warnings
# PI = 3.14 # Warning: redefining constantBasic Data Types
Numeric Types
# Integers
a = 42 # Int64 (on 64-bit systems)
b = Int32(42) # Int32
# Floating point
c = 3.14 # Float64
d = Float32(3.14) # Float32
# Boolean
e = true
f = falseCharacters and Strings
# Character (single quotes)
char = 'A'
# String (double quotes)
str = "Hello, Julia!"
# Multi-line string
multiline = """
This is a
multi-line string
"""Output
print and println
# print doesn't add newline
print("Hello")
print(" World") # Output: Hello World
# println adds newline
println("Hello")
println("World")
# Output:
# Hello
# WorldString Interpolation
Use $ for string interpolation:
name = "Julia"
age = 10
println("$name is $age years old.")
# Output: Julia is 10 years old.
# Expression interpolation
println("2 + 3 = $(2 + 3)")
# Output: 2 + 3 = 5Formatted Output
Use @printf macro:
using Printf
@printf("Integer: %d\n", 42)
@printf("Float: %.2f\n", 3.14159)
@printf("String: %s\n", "Hello")
@printf("Zero-padded: %05d\n", 42) # Output: 00042Input
readline
print("Enter your name: ")
name = readline()
println("Hello, $name!")Reading Numbers
print("Enter a number: ")
input = readline()
num = parse(Int, input)
println("You entered: $num")
# Or use Float64
num_float = parse(Float64, readline())Code Blocks
Semicolons
Semicolons suppress output in REPL, or separate multiple statements on one line:
# Suppress output
x = 10;
# Multiple statements on one line
a = 1; b = 2; c = 3Code Blocks
Use begin...end to create code blocks:
result = begin
x = 10
y = 20
x + y # Last expression value becomes block value
end
println(result) # Output: 30Can also use parentheses:
result = (x = 1; y = 2; x + y)
println(result) # Output: 3Scope
Global Scope
Variables defined at module top level:
global_var = 100
function show_global()
println(global_var)
endLocal Scope
Inside functions, loops, conditionals:
function local_example()
local_var = 10 # Local variable
println(local_var)
end
# local_var not accessible outside functionlet Blocks
Create new local scope:
let
x = 10
y = 20
println(x + y)
end
# x and y not accessible outside let blockglobal Keyword
Access or modify global variables in local scope:
counter = 0
function increment()
global counter
counter += 1
end
increment()
println(counter) # Output: 1Modules
Defining Modules
module MyModule
export greet # Exported function
const VERSION = "1.0"
function greet(name)
println("Hello, $name!")
end
function internal_function()
# Internal function, not exported
end
end # moduleUsing Modules
# Use all exported content from module
using MyModule
greet("Julia")
# Import only specific content
using MyModule: greet
# Import module itself
import MyModule
MyModule.greet("Julia")Standard Library Modules
using Statistics
using LinearAlgebra
using RandomExpressions and Statements
Compound Expressions
# Using begin...end
z = begin
x = 1
y = 2
x + y
end
# Using semicolon chain
z = (x = 1; y = 2; x + y)Conditional Expression (Ternary Operator)
x = 10
result = x > 5 ? "greater than 5" : "5 or less"
println(result) # Output: greater than 5Short-Circuit Evaluation
# && - if first is true, execute second
x = 10
x > 5 && println("x is greater than 5")
# || - if first is false, execute second
x < 5 || println("x is not less than 5")Nothing and Missing
Nothing
Represents "no value" or function has no return value:
function no_return()
println("This function returns nothing")
end
result = no_return()
println(result) # Output: nothing
println(isnothing(result)) # Output: trueMissing
Represents missing data (similar to SQL NULL):
data = [1, 2, missing, 4, 5]
println(ismissing(data[3])) # Output: true
# Missing propagation
println(1 + missing) # Output: missing
# Skip missing values
using Statistics
println(mean(skipmissing(data))) # Output: 3.0Type Annotations
Julia allows optional type annotations:
# Variable type annotation
x::Int = 10
# Function parameter types
function add(a::Int, b::Int)
return a + b
end
# Return type
function multiply(a, b)::Float64
return a * b
endCode Style Suggestions
Variable names use lowercase letters and underscores
juliamy_variable = 10Type names use CamelCase
juliastruct MyCustomType field::Int endFunction names use lowercase letters
juliafunction calculate_sum(arr) return sum(arr) endConstants use uppercase letters
juliaconst MAX_ITERATIONS = 1000Use appropriate spacing and indentation
juliafunction example(x, y) if x > 0 return x + y else return y end end
Next Steps
After mastering basic syntax, continue learning:
- Data Types - Deep dive into Julia type system
- Arrays - Learn array operations
- Functions - Function definition and usage