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.
Creating a variable with var
Section titled “Creating a variable with var”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 36var 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 ^~~ varmojo: 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.
Changing a variable
Section titled “Changing a variable”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:
102530score = 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 moduleIf you want a value that can never change, that’s a constant. Mojo has comptime for that, which gets its own lesson: Mojo Constants.
Type annotations
Section titled “Type annotations”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 TruePython 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.
A variable’s type never changes
Section titled “A variable’s type never changes”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 modulecount 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).
Declaring now, setting later
Section titled “Declaring now, setting later”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:
Hotvar 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 managerSo you never get a random “garbage” value by accident, like you can in C.
Several variables on one line
Section titled “Several variables on one line”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 2020 10x, y = y, x swaps the two values in one step, without a temporary variable.
Scope: where a variable can be used
Section titled “Scope: where a variable can be used”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 5outside: 5The 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'.
Shadowing: same name, inner block
Section titled “Shadowing: same name, inner block”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: 2outside: 1The 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.
Practice
Section titled “Practice”1. Fix the variables
Section titled “1. Fix the variables”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 applesSam has 5 applesname is new, so it needs var. apples already exists by the second print, so you just assign to it.
2. Keep a running total
Section titled “2. Keep a running total”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:
121949var total: Int = 0 creates the variable once, with an explicit type. Every later line changes the same variable.
3. Use the value after the block
Section titled “3. Use the value after the block”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: passNow 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. Plainname = valueonly 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
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- Mojo manual: Variables: declarations, type annotations, scopes and shadowing, from the official docs.
- Mojo manual: Types: the built-in types a variable can hold.
- Identifiers, keywords and conventions: the exact rules for variable names and reserved words.
- Mojo tips for Python developers: the Python habits that work in Mojo, and the ones that don’t.