In programming, a variable is a container for a value that can change during the execution of a program. Variables can hold many different types of data, including numbers and strings.
Creating a variable
When a variable is first created, it is usually assigned an initial value. This value can then be updated or changed as the program runs, using assignment statements. A variable is created when you assign a value to it using the assignment operator =
. The assignment operator assigns a value to a container, so it is not the same thing as the equality operator. This is the reason why the following code does not represent an error:
x = 3
x = x + 1
print(x) # Output => 4
Generally speaking, x does not equal x + 1, but in this case, we are updating the value held inside our variable from 3 to 4.
Naming a variable
Python variables must begin with a letter or underscore, and can contain letters, numbers, and underscores. It is generally recommended to use descriptive variable names that convey their purpose, but there are some conventions to follow. It is a common practice in Python to use lowercase letters for variable names and underscore as a word separator for multiple-word variable names.
user = "John" # this is a valid name
my_age = 24 # this is a valid name
1_place = "Mark" # this is not a valid name
?_question = "What's your name?" # this is not a valid name