# Basic variable declaration
= 1 # Implicit typing
x ::Int64 = 5 # Explicit type annotation
y
# Common types
= 42 # Integer (Int64)
num_int = 19.99 # Float (Float64)
num_float = true # Boolean
is_student = "Julia" # String
name = 3 + 4im # Complex number
c = :symbol # Symbol
sym
# Check type
typeof(num_int) # Returns Int64
typeof(num_float) # Returns Float64
Julia Syntax Cheatsheet
Optimization with Julia
This cheatsheet provides a quick reference for Julia programming language syntax and common operations. Julia is a high-level, high-performance programming language designed for numerical and scientific computing. It combines the ease of use of Python or R with the speed of C. For comprehensive documentation, visit:
Variables and Basic Types
Variable Declaration and Types
String Operations
# String manipulation
= "Hello, World!"
str length(str) # String length
lowercase(str) # Convert to lowercase
uppercase(str) # Convert to uppercase
strip(" text ") # Remove leading/trailing whitespace
String Interpolation
= "Julia"
name = 30
age # Basic interpolation
= "I am $age years old"
msg1 # Expression interpolation
= "In 5 years, I'll be $(age + 5)"
msg2 # Complex interpolation
= "Hello, my name is $name and I am $age years old" greeting
Type Conversion
# Convert between types
= Float64(42) # Int to Float
float_num = Int64(3.14) # Float to Int
int_num = string(42) # Number to String str_num
Key Points
- Variables are dynamic, types are not
- Use
typeof()
to check variable type - String interpolation is powerful for formatted output
Vectors, Matrices, and Tuples
Vectors
# Create vectors
= [95, 87, 91, 78, 88] # Numeric vector
grades = ["Mike", "Yola", "Elio"] # String vector
names
# Vector operations
push!(grades, 82) # Add element to end
pop!(grades) # Remove last element
popfirst!(grades) # Remove first element
# Vector indexing
= grades[1] # Access first element
first = grades[1:3] # Access first three elements subset
Matrices
# Create matrices
= [1 2 3; 4 5 6] # 2x3 matrix
matrix # Matrix operations
2,3] = 17 # Change specific element
matrix[
# Matrix arithmetic
= [2 2; 3 3]
matrix1 = [1 2; 3 4]
matrix2 = matrix1 + matrix2 # Matrix addition
sum_matrix = matrix1 * matrix2 # Matrix multiplication
prod_matrix = matrix1 .* matrix2 # Element-wise multiplication
element_prod
# Broadcasting
.+ 10 # Add 10 to each element matrix
Tuples
# Create tuples (immutable)
= ("Elio Smith", 18, "Hamburg")
person = (255, 0, 0)
rgb
# Tuple operations
= person[1] # Access first element
name = person[2:3] # Multiple assignment age, city
Key Differences
- Vectors: Mutable, 1-dimensional, good for lists
- Matrices: Mutable, 2-dimensional, good for linear algebra
- Tuples: Immutable, fixed-size, good for grouping related constants
Comparison and Logical Operators
Basic Comparisons
# Comparison operators
== y # Equal to
x != y # Not equal to
x < y # Less than
x > y # Greater than
x <= y # Less than or equal to
x >= y # Greater than or equal to
x
# Examples
= (input == "secret123")
password_correct = (age >= 18)
is_adult = (price <= budget) can_afford
Logical Operators
# AND operator (&&)
= (age >= 18) && (money >= price) # Both conditions must be true
can_buy
# OR operator (||)
= (temp < 10) || is_raining # At least one must be true
need_coat
# NOT operator (!)
= !is_open # Inverts boolean value is_closed
Chained Comparisons
# Instead of
>= 0 && x <= 10 # Check if x is between 0 and 10
x
# You can write
0 <= x <= 10 # More natural syntax
# Real-world examples
= 36.5 <= body_temp <= 37.5
normal_temp = 9 <= current_hour < 17 work_hours
Key Points
- Comparisons return boolean values (
true
orfalse
) &&
requires all conditions to be true||
requires at least one condition to be true!
inverts a boolean value- Chained comparisons make range checks more readable
Loops and Iterations
For Loops
# Basic for loop with range
for i in 1:3
println(i) # Prints 1, 2, 3
end
# Iterating over array
= ["apple", "banana", "cherry"]
fruits for fruit in fruits
println(fruit) # Prints each fruit
end
# For loop with break
for x in 1:10
if x == 4
break # Exits loop when x is 4
end
end
# For loop with conditions
for x in 1:10
if x <= 2
println(x)
elseif x == 3
println("Three!")
else
break
end
end
While Loops
# Basic while loop
= 10
number while number >= 5
-= 1 # Decrements until < 5
number end
# Infinite loop with break
= 0
current while true
+= 1
current if current == 5
break # Exits when condition met
end
end
# While loop with condition
= 3
lives while lives > 0
-= 1 # Continues until lives = 0
lives end
Nested Loops
# Nested loop example
= ["S", "M", "L"]
sizes = ["Red", "Blue"]
colors for size in sizes
for color in colors
println("$color $size")
end
end
# Matrix iteration
for i in 1:3
for j in 1:2
println("Position: $i,$j")
end
end
List Comprehensions
# Basic list comprehension
= [n^2 for n in 1:5] # [1,4,9,16,25]
squares
# With condition
= [n for n in 1:10 if n % 2 == 0] # [2,4,6,8,10]
evens
# Nested comprehension
= [i*j for i in 1:3, j in 1:3] # 3x3 multiplication table matrix
Key Points
for
loops are best when you know the number of iterationswhile
loops are useful for unknown iteration counts- Use
break
to exit loops early - List comprehensions offer concise array creation
- Nested loops are useful for multi-dimensional iteration
Dictionaries
Basic Dictionary Operations
# Create a dictionary
= Dict(
student_ids "Elio" => 1001,
"Bob" => 1002,
"Yola" => 1003
)
# Access values
= student_ids["Elio"] # Get value by key
id "David"] = 1004 # Add new key-value pair
student_ids[delete!(student_ids, "Bob") # Remove entry
# Check key existence
if haskey(student_ids, "Eve")
println(student_ids["Eve"])
end
Advanced Operations
# Dictionary with array values
= Dict(
grades "Elio" => [85, 92, 78],
"Bob" => [76, 88, 94]
)
# Get all keys and values
= keys(grades) # Get all keys
names = values(grades) # Get all values
scores
# Iterate over dictionary
for (student, grade_list) in grades
= sum(grade_list) / length(grade_list)
avg println("$student: $avg")
end
Common Methods
# Dictionary methods
length(dict) # Number of entries
empty!(dict) # Remove all entries
get(dict, key, default)# Get value or default if key missing
merge(dict1, dict2) # Combine two dictionaries
copy(dict) # Create shallow copy
Key Points
- Keys must be unique
- Values can be of any type (including arrays)
- Use
haskey()
to safely check for key existence - Dictionaries are mutable (can be changed)
- Keys are accessed with square brackets
dict["key"]
Functions
Basic Function Definition
# Basic function with explicit return
function say_hello(name)
return "Hello, $(name)!"
end
# Function with implicit return
function multiply(a, b)
* b # Last expression is automatically returned
a end
# Conditional return
function do_something(a, b)
if a > b
return a * b
else
return a + b
end
end
Advanced Function Features
# Optional arguments
function greet(name="Guest", greeting="Hello")
"$greeting, $name!"
end
# Multiple return values
function stats(numbers)
= sum(numbers) / length(numbers)
avg = minimum(numbers)
min_val = maximum(numbers)
max_val return avg, min_val, max_val
end
# Anonymous functions
= 1:10
numbers map(x -> x^2, numbers) # Square each number
Function Scope
# Local scope example
function bake_cake()
= "vanilla" # Only exists inside function
secret_ingredient return secret_ingredient # Must return to access outside
end
# Variables outside function not accessible inside
= 10
global_var function scope_example()
# Can read global_var but can't modify it
return global_var + 5
end
Multiple Dispatch
# Generic operation for all types
function operation(a, b)
"Generic operation for $(typeof(a)) and $(typeof(b))"
end
# Type-specific implementations
operation(a::Number, b::Number) = a + b # For numbers
operation(a::String, b::String) = string(a, b) # For strings
# Usage examples
operation(10, 20) # Returns 30
operation("Hello", "!") # Returns "Hello!"
operation("Hi", 42) # Uses generic operation
Key Points
- Functions can have explicit or implicit returns
- Last expression is automatically returned if no
return
statement - Variables inside functions are local by default
- Multiple dispatch allows different behavior based on argument types
- Use
return
for early exits or conditional
Package Management
Basic Package Operations
# Import package manager
import Pkg # Access as Pkg.function()
using Pkg # Import all exported names
# Add packages
Pkg.add("DataFrames") # Add single package
Pkg.add(["Package1", "Package2"]) # Add multiple packages
# Update packages
Pkg.update() # Update all packages
Pkg.update("DataFrames") # Update specific package
# Remove packages
Pkg.rm("DataFrames") # Remove package