Python Variables

1-13-2021

Variables are one of the most frequently used concepts in programming. Variables are used so programs can hold onto and manipulate different pieces of data.



How To Create a Variable



To create a variable in Python, you simply type the name you would like the variable to be called, and use an equal sign to set it equal to whatever you like. Variables can be set to a variety of data types, some of which are covered in our other article here. Here is an example of creating variables of a variety of data types.



score=2
weight=75.5
greeting="hello"
flag=False


Variables can generally be called whatever you like. However, if you create a variable with a certain name, and then create another with the same name, you will essentially erase the first variable you created. Additionally there are certain rules to avoid errors when naming variables, such as not using spaces, not starting the name with a number, and only using alphanumeric characters. An exhaustive list can be found at the official Python documentation.


Case Sensitivity


One small but important idea to remember when creating a variable is that they are case sensitive. In other words, the variables "num", "NUM", and "Num" are three different variables!


Using Variables


Let's use our variable called greeting for an example. In Python, if we wanted to print the word "hello" to the console, we could type:

print("hello")

However, since we have a variable, greeting, which is holding the value "hello", we can use it as well:

print(greeting)

This wil accomplish the same goal. Variables essentially hold onto whatever value you give them. This can be useful for programs where a value needs to be initialized and modified over time. Think of a game where the score starts at zero, and is incremented. If you needed to increment a variable holding a number called "score", you would create it and increment it by typing:

score=0
score=score+1

This is just some simple arithmetic, so you can read more about arithmetic here. Now you know how to create variables in Python, and how they can hold values. In this sense, they can be essentially equal to a value, and these values can be manipulated when needed.