Variables

What is a Variable?

A variable is essentially a label for a value. They contain a piece of data. A variable can contain any data type. For instance, a variable can contain a list.

Why Should I Use Variables?

Variables help improve readability of code, and can reduce the amount of coding needed.

Say that you need to use a string again and again, you could just write the string each time, but then if you wanted to change the string, you would need to change each mention of the string. Instead, you can use a variable that contains the string. Meaning that if you wanted to change the string, you would only need to change it once.

Using Variables

To use a variable, the variable must first be defined. After that, it may be referenced or changed.

Defining Variables

To define a variable, you simply write it's name followed by an equals sign and then the value the variable will have.

my_variable = "A simple string"

Now, the variable, "my_variable" may be called from the code.

Changing Variables

Changing a variable is a lot like defining it, in fact, it's no different.

my_variable = "A simple string"
my_variable = "A different string"

The first line will create the variable and give it the value, and the second line will change the value of the variable.

Referencing Variables

To reference a variable, you simply write the name of it where you would like it to be used.

my_variable = "A simple string"
print(my_variable)

This will print, "A simple string" to the terminal.

Last updated