Variables help make programs changeable and adaptable. Without variables, it would be impossible to create most programs.

Suppose we are programming a scoring system for a game. Since the program needs to remember the current score and flexibly change it throughout the game, a variable can help us out.

Suppose we have two players, we’ll need to create two variables:

player1Score = 0 player2Score = 0

The basic syntax for declaring a variable is: name = value. In this example, two variables are created with the name player1Score and player2Score. We assigned the number value 0 to each variable using an equal sign (=). Each variable will start with the 0 value. But like scores in a game, each variable’s value will change as the players earn points.

Once we’ve assigned the value 0 to each variable, the variable names now represent 0. We can access the values inside of variables by using their variable names, so rather than writing

print(0) --output: 0

We can directly reference the variable with

print(player1Score) --output: 0

We should strive to name variables succinctly but descriptively so that when we look at them, it is easy to understand their purpose. For example, a variable named myValue does not tell us what kind of value that variable holds, while player1Score gives us a lot more info.



Our game’s record-keeping needs a bit of work! Let’s expand on the data we’re keeping track of.

Declare a variable named player1Name and assign the string value "Kamala" to it.


Declare a variable named player2Name and assign the string value "Bruno" to it.


Declare a variable named highestScore and assign the nil value nil to it. Our game hasn’t started yet, so there isn’t a highest score!

Take this course for free

Mini Info Outline Icon
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.

Or sign up using:

Already have an account?