In Python, a variable is essentially a named storage location in memory that holds a value. Variables allow us to store, retrieve, and manipulate data within our programs. Python is not statically typed, that means we do not need to declare variables before using them or declare their type. For example, on these code box we are declaring and defining three variables of different data types.
x = 5 # x is an integer
y = "Hello" # y is a string
z = 3.14 # z is a float
Variables are assigned values with the = operator. You can reassign a new value to an existing variable at any time, even with a different data type.
x = 5
x = "New Value" # x is now a string
You can assign values to multiple variables at once, which is helpful for more concise code.
a, b, c = 1, 2, 3
Variable Naming Rules
A variable name must start with a letter or an underscore (_).
A variable name can only contain alpha-numeric characters and underscores.
Variable names in Python are case-sensitive (myVar and myvar are different).
The reserved words (keywords) in Python cannot be used to name the variable.
my_var = 10
_myVar = "Python"
my2ndVar = True
Global and Local Scope.
Variables defined outside any function are global, accessible throughout the program. Variables inside functions are local to that function.
x = "global"
def func():
x = "local" # Only within func
Deleting Variables.
You can delete a variable using the del keyword, which frees up the memory it occupied.
del x
To learn more about check out our complete Python course.