Variables in Python

Variables are used to store information to be referenced and manipulated in a computer program. They also provide a way of labeling data with a descriptive name, so our programs can be understood more clearly by the reader and ourselves. It is helpful to think of variables as containers that hold information. Their sole purpose is to label and store data in memory. This data can then be used throughout your program.

Creating Variables

In Python, a variable is created the moment you first assign a value to it. A variable can be assigned any data type.

x = 5
y = "Hello, World!"

# x is of type int, y is of type str

Variable Names

A variable can have a short name (like x and y) or a more descriptive name (age, carname, total_volume). Rules for Python variables:

# Legal variable names:
myvar = "John"
my_var = "John"
_my_var = "John"
myVar = "John"
MYVAR = "John"
myvar2 = "John"

# Illegal variable names:
2myvar = "John"
my-var = "John"
my var = "John"

Dynamic Typing

Python is a dynamically typed language, which means you don't have to declare the type of variable while creating one - the type is inferred at runtime.

x = 4       # x is of type int
x = "Sally"  # x is now of type str
print(x)

Conclusion

Understanding variables is fundamental in learning to program in Python. As you progress, you'll learn how these placeholders are used to construct more complex data structures and algorithms.