Learn Julia · 2/15

Core Fundamentals: Variables & Data Types

7 min read

Core Fundamentals: Variables & Data Types 📜

Welcome to the foundational concepts of Julia! Before we can build magnificent castles of code, we need to understand the bricks and mortar. This guide will walk you through the absolute essentials: how to store information and the different kinds of information Julia understands.


1. Variables and Assignments: Storing Your Data 📥

The Problem: Imagine you're a sous-chef in a bustling kitchen. You've just perfectly measured out 200 grams of flour for a recipe. If you just leave it on the counter without a label, you (or another chef) might forget what it is or how much is there. In programming, we constantly deal with values (like 200 grams of flour) that we need to use later. How do we keep track of them?

The Solution: Variables! A variable is essentially a labeled container for a value. You give it a name, and you can put data inside it. This makes your code readable and allows you to reuse values without having to type them out every time.

In Julia, assigning a value to a variable is as simple as using the equals sign (=):

julia
# Assign the value 10 to the variable x
x = 10

# Now we can use 'x' in other calculations
y = x + 5 # y will be 15

# You can also change the value of a variable
x = 20 # x is now 20

Naming Your Variables: The Julia Way ✒️

Julia is quite flexible with variable names, but to keep your code understandable for yourself and others, it's good to follow some conventions.

  • Start with a letter or underscore: Variable names must begin with a letter (a-z, A-Z), an underscore (_), or a Unicode character. They cannot start with a number.
  • Case sensitivity matters: my_variable is different from My_Variable.
  • Use lowercase for variables: The community standard is to use lowercase for variable and function names.
  • Word separation: If your variable name consists of multiple words, you can separate them with an underscore (_), like my_awesome_variable. However, it's often preferred to just run them together if it's still readable.

Here are some examples of valid variable names:

julia
# Good variable names
apples = 5
banana_price = 1.25
_temporary_value = "don't mind me"

# You can even use Unicode characters! (Type \delta and press Tab in the Julia REPL)
δ = 0.001

Funny exaggeration: Naming your variables a, b, c, and so on might seem like a good idea at 2 AM, but when you come back to your code a week later, it'll be like trying to read ancient hieroglyphics without a Rosetta Stone. Give your variables meaningful names! Your future self will thank you.


2. Basic Types: Numbers, Booleans, and Characters 🔢

The Problem: In our kitchen, we don't just have flour. We have liquids (like water), solids (like sugar), and even concepts like "Is the oven on?" (which can be true or false). Similarly, in programming, we need to work with different kinds of data. How does Julia distinguish between a whole number, a number with a decimal, and a piece of text?

The Solution: Data Types! Julia, like most programming languages, has different data types to represent different kinds of information. Let's look at the most common ones.

Numbers: Integers and Floating-Point 🧮

  • Integers (Int): These are whole numbers, both positive and negative. On most modern computers, the default is Int64, which means it uses 64 bits of memory to store the number.
  • Floating-Point Numbers (Float64): These are numbers with a decimal point. The default is Float64, which offers a good balance of precision and range for most tasks.
julia
my_integer = 100
typeof(my_integer) # This will tell you the type is Int64

my_float = 3.14
typeof(my_float) # This will show Float64

Under the Hood: Why the different types? It comes down to how computers store numbers. Integers are stored exactly, while floating-point numbers are approximations. For most everyday tasks, this distinction isn't a huge deal, but in scientific computing, precision can be very important!

Booleans (Bool): The Essence of Logic 🤔

A Boolean can only have one of two values: true or false. They are the foundation of decision-making in your programs.

julia
is_julia_awesome = true
is_it_monday = false
typeof(is_julia_awesome) # This will be Bool

Interesting Fact: In Julia, true is numerically equivalent to 1 and false to 0. You can even do math with them, though it might look a bit strange!

julia
true + true # This will give you 2!

Characters (Char) 🔡

A Char represents a single character and is enclosed in single quotes.

julia
my_initial = 'J'
typeof(my_initial) # This will be Char

Heads up! Don't confuse single quotes for characters with double quotes, which are used for strings (sequences of characters), a topic for another guide!


3. Mathematical Operations and Type Promotion ➕➖✖️➗

The Problem: Now that we have our ingredients (numbers), we need to be able to mix them together. If you add a whole number (an integer) to a number with a decimal (a float), what should the result be? A whole number? A decimal number?

The Solution: Mathematical Operations and a Smart System Called Promotion!

Julia provides all the standard mathematical operators you'd expect.

  • + for addition
  • - for subtraction
  • * for multiplication
  • / for division
  • ^ for exponentiation (raising to a power)
julia
a = 10
b = 3

a + b  # 13
a - b  # 7
a * b  # 30
a / b  # 3.333...
a ^ b  # 1000

Integer Division vs. Floating-Point Division: Notice that 10 / 3 resulted in a floating-point number. This is because standard division in Julia always produces a float. If you want to perform integer division (where the remainder is discarded), you can use the ÷ symbol (typed as \div then Tab).

julia
10 ÷ 3 # This gives 3

To get the remainder of a division, use the modulo operator %.

julia
10 % 3 # This gives 1

Type Promotion: Julia's Smart Calculations 🧠

So, what happens when you mix different numeric types?

julia
1 + 2.5

Here, Julia's promotion system steps in. It automatically converts the integer 1 to a floating-point number (1.0) before performing the addition to avoid losing the decimal part. The result, as you might guess, is 3.5.

In essence, Julia "promotes" the types to a common, more general type to ensure accuracy. This is incredibly convenient and makes mathematical operations behave naturally.


4. Constants: Defining Immutable Values 🛡️

The Problem: Imagine you're building a physics simulation. The speed of light is a fundamental constant; it doesn't change. While you could store it in a regular variable, there's a risk that you or someone else on your team might accidentally change its value later in the code, leading to some very weird (and incorrect!) physics.

The Solution: Constants! A constant is a variable whose value is not supposed to change. Once you've declared a constant, you're signaling to everyone (and the Julia compiler) that this value is fixed.

You declare a constant using the const keyword. By convention, constant names are written in all uppercase letters.

julia
const SPEED_OF_LIGHT = 299792458 # in meters per second
const PI = 3.14159

Why use constants?

  • Readability: It makes your code clearer. 2 * PI * radius is much more understandable than 2 * 3.14159 * radius.
  • Maintainability: If a constant value needs to be updated (perhaps a more precise measurement of PI is needed), you only have to change it in one place.
  • Error Prevention: It helps prevent accidental changes to values that should remain fixed.

An Interesting Quirk: If you try to change the value of a constant in Julia, it will let you, but it will give you a warning. This is a bit different from other languages where it might be a hard error. Think of it as Julia saying, "I'll let you do this, but are you really sure you want to redefine a fundamental constant of the universe?"

Under the Hood: Using const can also give the Julia compiler hints that can lead to performance optimizations, as it knows the value of the variable won't change.

And that's a wrap on the very basics! You've learned how to store data, the different fundamental types of data Julia works with, how to perform calculations, and how to protect values that shouldn't change. These are the building blocks you'll use in every Julia program you write.


References for Extra Reading 📚

Challenge

Julia Fundamentals: Budget Calculation

You are tasked with writing a script to perform budget calculations for a shopping trip. Your goal is to determine the total cost of an item, how many of that item can be purchased within a budget, and the remaining funds.

Requirements:

  1. Define two constants for the script: SALES_TAX_RATE with a value of 0.088 and SERVICE_FEE with a value of 2.50.
  2. Using the provided item_base_price, calculate the tax_amount for a single item.
  3. Calculate the single_item_total_cost, which is the sum of the base price, tax amount, and service fee. Ensure this calculation correctly utilizes Julia's type promotion.
  4. Determine the num_items_purchasable, which is the maximum number of whole items that can be bought with the customer_budget. This must be an integer.
  5. Calculate the remaining_budget after purchasing the maximum number of items.
  6. Create a boolean variable can_afford_one that is true if the customer's budget is sufficient to buy at least one item, and false otherwise.
  7. Create a character variable currency_initial and assign it the character for 'Dollar', which is 'D'.

Expected result

Your final code should correctly define and calculate all the required variables.

  • SALES_TAX_RATE should be declared as a const with the value 0.088.
  • SERVICE_FEE should be declared as a const with the value 2.50.
  • tax_amount should hold the product of item_base_price and SALES_TAX_RATE.
  • single_item_total_cost should be the sum of item_base_price, tax_amount, and SERVICE_FEE. The resulting type should be Float64.
  • num_items_purchasable must be an Int calculated using integer division (÷) of customer_budget by single_item_total_cost.
  • remaining_budget should be a Float64 calculated using the modulo operator (%) between customer_budget and single_item_total_cost.
  • can_afford_one must be a Bool value, derived from comparing customer_budget to single_item_total_cost.
  • currency_initial must be a Char with the value 'D'.
julia

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.