Skip to content

Mojo Variables

A variable is a name that holds a value, like age holding 36 or name holding "Ada". You’ll use them in almost every line of code you write. Mojo variables look a lot like Python’s, with one big difference: you have to say when you’re creating a new one. This page shows how, plus types, changing values and where a variable can be used.

You make a new variable with the var keyword, a name, = and a value:

def main():
var name = "Ada"
var age = 36
print(name, "is", age)

Output:

Ada is 36

var name = "Ada" creates a new variable called name and stores the text "Ada" in it. After that, you can use name anywhere below it in the same function.

In Python you’d write name = "Ada" and be done. In Mojo, leaving out var is an error:

def main():
age = 36
print(age)
hello.mojo:2:5: error: implicit declaration of 'age' is not allowed; add 'var' to declare a new name
age = 36
^~~
var
mojo: error: failed to parse the provided Mojo source module

“Implicit declaration” means creating a variable just by assigning to it. Mojo doesn’t allow it, so a typo like totl = 5 can’t quietly create a second variable when you meant to change total.

All Mojo variables can change. To give an existing variable a new value, assign to it without var:

def main():
var score = 10
print(score)
score = 25
print(score)
score = score + 5
print(score)

Output:

10
25
30

score = score + 5 reads the current value (25), adds 5, and stores the result back in score. You’ll see shorter ways to write that (score += 5) in the Operators lesson.

If you write var again for a name that already exists in the same block, Mojo stops you:

def main():
var x = 1
var x = 2
print(x)
hello.mojo:3:9: error: invalid redefinition of 'x'
var x = 2
^
hello.mojo:2:9: note: previous definition here
var x = 1
^
mojo: error: failed to parse the provided Mojo source module

If you want a value that can never change, that’s a constant. Mojo has comptime for that, which gets its own lesson: Mojo Constants.

Every variable in Mojo has a type: what kind of value it holds. When you write var age = 36, Mojo works out the type for you (Int, a whole number). This is called type inference.

You can also write the type yourself, after a colon. This is a type annotation:

def main():
var count: Int = 3
var price: Float64 = 4.5
var title: String = "Receipt"
var paid: Bool = True
print(title, count, price, paid)

Output:

Receipt 3 4.5 True

Python has the same name: type syntax, but there it’s only a hint. In Mojo the compiler checks it. Annotations are handy when the inferred type isn’t the one you want, for example a smaller number type like UInt8. You’ll meet all of these types in Mojo Data Types.

Once a variable has a type, it keeps it. In Python you can put a number in a variable and later a string. In Mojo you can’t:

def main():
var count = 8
count = "Nine?"
print(count)
hello.mojo:3:13: error: cannot implicitly convert 'StringLiteral["Nine?"]' value to 'Int'
count = "Nine?"
^~~~~~~
mojo: error: failed to parse the provided Mojo source module

count became an Int on the first line, so it can only ever hold whole numbers. This feels strict at first, but it means Mojo catches a whole class of mistakes before your program even runs. If you really need text, make a second variable, or convert the value (see Mojo Type Conversion).

You can create a variable with just a type and give it a value later:

def main():
var temperature = 31
var message: String
if temperature > 25:
message = "Hot"
else:
message = "Fine"
print(message)

Output:

Hot

var message: String creates the name without a value. Both branches of the if set it, so it’s ready by the time print uses it. If there’s any path where you’d read it before setting it, the compiler refuses:

def main():
var message: String
print(message)
hello.mojo:3:10: error: use of uninitialized value 'message'
print(message)
^
hello.mojo:2:9: note: 'message' declared here
var message: String
^
mojo: error: failed to run the pass manager

So you never get a random “garbage” value by accident, like you can in C.

You can create or change several variables at once, the same way as in Python:

def main():
var x, y = 10, 20
print(x, y)
x, y = y, x
print(x, y)

Output:

10 20
20 10

x, y = y, x swaps the two values in one step, without a temporary variable.

A variable’s scope is the part of the code where its name exists. In Mojo, a variable lives in the block where you created it, and in any blocks nested inside that one. The official Mojo manual page on variables calls this block-level, lexical scoping.

def main():
var total = 0
if total == 0:
var bonus = 5
total = total + bonus
print("inside:", total, bonus)
print("outside:", total)

Output:

inside: 5 5
outside: 5

The if block can read and change total, because total comes from the outer block. But bonus was created inside the if, so it’s gone when that block ends. Try to use it after the block and you’ll get use of unknown declaration 'bonus'.

If you write var with an outer name inside a nested block, you create a new variable that hides the outer one until the block ends. This is called shadowing:

def main():
var level = 1
if level == 1:
var level = 2
print("inside:", level)
print("outside:", level)

Output:

inside: 2
outside: 1

The inner level is a different variable, so changing it doesn’t touch the outer one. It works, but it’s easy to confuse a reader, so most of the time it’s better to pick a different name.

This program should print Sam has 3 apples and then Sam has 5 apples. It has two mistakes.

def main():
name = "Sam"
var apples = 3
print(name, "has", apples, "apples")
var apples = 5
print(name, "has", apples, "apples")

Hint: one variable is created without var, and another gets var twice.

Show solution
def main():
var name = "Sam"
var apples = 3
print(name, "has", apples, "apples")
apples = 5
print(name, "has", apples, "apples")

Output:

Sam has 3 apples
Sam has 5 apples

name is new, so it needs var. apples already exists by the second print, so you just assign to it.

Create a variable total set to 0. Then add 12, 7 and 30 to it, one at a time, and print total after each step. Use a type annotation on total.

Hint: total = total + 12 changes the existing variable.

Show solution
def main():
var total: Int = 0
total = total + 12
print(total)
total = total + 7
print(total)
total = total + 30
print(total)

Output:

12
19
49

var total: Int = 0 creates the variable once, with an explicit type. Every later line changes the same variable.

This code fails with use of unknown declaration 'grade'. Change it so it prints Grade: pass.

def main():
var points = 72
if points >= 50:
var grade = "pass"
print("Grade:", grade)

Hint: create grade before the if, and only set it inside.

Show solution
def main():
var points = 72
var grade = "fail"
if points >= 50:
grade = "pass"
print("Grade:", grade)

Output:

Grade: pass

Now grade lives in the outer block, so it still exists after the if. Giving it a starting value of "fail" also covers the case where the if doesn’t run.

  • Create a new variable with var name = value. Plain name = value only works for names that already exist.
  • All variables can change; for values that can’t, use comptime (see Constants).
  • Add a type annotation with var name: Type = value. Without one, Mojo infers the type.
  • A variable’s type never changes after it’s created.
  • You can declare first (var x: Int) and set it later, as long as it’s set before it’s read.
  • Variables have block scope: a name created inside a block is gone when the block ends.

Next up: data types, a tour of the kinds of values a variable can hold.

Quick check

1. Which line creates a new variable called total?
2. After var count = 8, what happens with count = "nine"?
3. A variable is created with var inside an if block. Can you use it after the block?
4. What does var x, y = 1, 2 followed by x, y = y, x do?