A Python variable is simply a name (a label) you use to refer to a value (the information). It allows you to store, retrieve, and change data in your program in an organized way.
Creating a variable is simple in Python. You just give it a name and use the equals sign (=) to put a value inside the “box”.
Syntax (The Rule):variable_name = value
Example
What it does (Box Analogy)
age = 30
Creates a box labeled age and puts the number 30 inside.
name = "Sara"
Creates a box labeled name and puts the text “Sara” inside.
is_sunny = True
Creates a box labeled is_sunny and puts the value True inside.
A variable can have a short name (like a and b) or a more descriptive name (age, name, total_number).
A variable name must start with a letter or the underscore character.
A variable name cannot begin with a number.
A variable name can only contain alphanumeric characters and underscores (A-z, 0-9, and _).
Variable names are case-sensitive (e.g., age, Age, and AGE are three different variables).
Cannot be one of Python’s reserved words (like if, for, while, etc.).
A variable is not set in stone. You can change the value in the “box” whenever you need to.
Start:score = 100 (The score box holds 100)
Change:score = 150 (The score box now holds 150. The old value 100 is forgotten.)
You can even change the type of information a variable holds (though this is often avoided in professional code, Python allows it).
Change Type:data = 5 (Holds a number) –> data = "hello" (Now holds text)
The type of value a variable holds is called its Data Type. Python figures this out automatically.
The three main types you’ll use are:
Type
Layman’s Term
Python Name
Example
Whole Numbers
Integers
int
10, -5, 0
Text
Strings (anything inside quotes)
str
"Hello", "30", "A"
True/False
Booleans
bool
True, False
In Python, variables have different scopes, which simply means where they are visible or where they can be used.
A Global Variable is a variable defined in the main body of your Python script (outside of any specific function).
Think of it as a central bulletin board available to everyone in the office (your entire program). Any function or piece of code can read its value.
Example
MAX_PLAYERS=50 Â # This is a Global Variable
defcheck_limit(new_players): Â # This function can READ MAX_PLAYERS without any special keywords. Â ifnew_players>MAX_PLAYERS: Â Â Â print("Limit reached!")