2.4 Python Variables (BT101CO)
Variables are named locations in a computer's memory used to store data that can be manipulated during program execution. Think of a variable as a label or a reference attached to a specific value.
1. The Core Concept: Labels, Not Boxes
In many older languages, a variable is like a "box" where you drop a value. In Python, it is more accurate to view a variable as a tag or pointer tied to an object in memory.
- When you write
x = 10, an object10is created in memory, and the labelxis pointed at it. - If you then write
y = x, you aren't creating a second "10"; you are simply attaching a second label (y) to the same memory location.
2. Rules for Naming (Identifiers)
To ensure the interpreter recognizes a variable, it must follow these strict syntax rules:
- Start with a letter (
A-Z,a-z) or an underscore (_). - No Digits at the start:
1variableis invalid;variable1is fine. - Case-Sensitivity:
Age,age, andAGEare three completely different variables. - No Keywords: Reserved words like
if,while, orclasscannot be used as names. - No Special Characters: Symbols like
@,$, and%are prohibited (except for the underscore).
3. Dynamic Typing
Python uses Dynamic Typing, meaning you don't have to tell the computer what kind of data a variable will hold (like int or string) beforehand. The type is automatically determined by the value assigned to it:
score = 100$\rightarrow$ The variable is an Integer.score = "High"$\rightarrow$ The same variable now points to a String.
4. Assignment Methods
Values are assigned using the = operator (the assignment operator).
- Single Assignment:
price = 99.99 - Multiple Assignment (Same Value):
a = b = c = 0(All three point to zero). - Multiple Assignment (Different Values):
name, age = "Ashok", 25(Assigns "Ashok" tonameand25toagesimultaneously).
5. Scope: Where the Variable Lives
A variable's "Scope" determines where in the code it can be accessed:
- Local Variables: Defined inside a function; they only exist while that function is running.
- Global Variables: Defined outside functions; they are accessible throughout the entire script.
Summary Table
| Feature | Description |
|---|---|
| Declaration | Not required (created at the moment of assignment). |
| Typing | Dynamic (type changes based on the value). |
| Memory | Acts as a reference/pointer to an object. |
| Naming | Must start with a letter/underscore; case-sensitive. |
By mastering variables, you gain the ability to store, track, and change information—the fundamental requirement for any problem-solving logic.