Skip to content

Latest commit

 

History

History
1331 lines (980 loc) · 16 KB

File metadata and controls

1331 lines (980 loc) · 16 KB

Python Variables

A variable is a named reference that points to a value (object) stored in memory.

Think of a variable as a label attached to a value.

name = "Ironman"
  • name → Variable (Reference / Identifier)
  • = → Assignment operator
  • "Ironman" → Value (String object)

How Assignment Works

When Python executes

name = "Ironman"

it performs these steps:

Step 1

Python creates the string object.

"Ironman"

Step 2

Python stores the object in memory.

Memory

┌──────────────────┐
│    "Ironman"     │
└──────────────────┘

Step 3

Python creates the variable.

name

Step 4

The variable points to the object.

name
 │
 ▼
┌──────────────────┐
│    "Ironman"     │
└──────────────────┘

The variable does not store the value directly.

It stores a reference (memory address) to the object.


Variable Visualization

Variable

name
 │
 ▼

Value

"Ironman"

Or

Variable         Value

name      ─────────────► "Ironman"

Another Example

age = 25

Python performs

Step 1

25

Step 2

Memory

┌──────┐
│  25  │
└──────┘

Step 3

age
 │
 ▼

┌──────┐
│  25  │
└──────┘

Multiple Variables

name = "Tony"
age = 53
height = 5.9
is_alive = True

Memory diagram

name
 │
 ▼
"Tony"

age
 │
 ▼
53

height
 │
 ▼
5.9

is_alive
 │
 ▼
True

Or

name      ─────► "Tony"

age       ─────► 53

height    ─────► 5.9

is_alive  ─────► True

Each variable points to its own object.


Variables and Memory

city = "London"

Memory

city
 │
 ▼
┌────────────┐
│  "London"  │
└────────────┘

Variable Reassignment

city = "London"

city = "Paris"

Before

city
 │
 ▼
"London"

After

city
 │
 ▼
"Paris"

Python changes the reference.

The variable now points to another object.


What Happens to the Old Value?

Before

city
 │
 ▼
"London"

After

city
 │
 ▼
"Paris"


"London"

If no variable points to "London" anymore, Python's Garbage Collector automatically removes it later.


Copying Variables

a = 10

b = a

Python does not create another 10.

Both variables point to the same object.

        ┌─────┐
        │ 10  │
        └─────┘
         ▲   ▲
         │   │
         │   │
         a   b

Or

a ─────┐
       │
       ▼
      10
       ▲
       │
b ─────┘

Changing One Variable

a = 10

b = a

a = 20

Initially

a ─────┐
       │
       ▼
      10
       ▲
       │
b ─────┘

After

a
 │
 ▼
20


b
 │
 ▼
10

Python creates a new object (20) and makes a point to it.

b still points to 10.


Another Example

x = 100

y = x

z = y
          ┌──────┐
          │ 100  │
          └──────┘
           ▲ ▲ ▲
           │ │ │
           │ │ │
           x y z

Three variables point to one object.


Reassignment Example

x = 100

y = x

z = y

y = 500
x
 │
 ▼
100


z
 │
 ▼
100


y
 │
 ▼
500

Only y changes.


Variable Lifetime

message = "Hello"
message
 │
 ▼
"Hello"

Later

message = "Python"
message
 │
 ▼
"Python"

If "Hello" has no references left, Python removes it automatically.


Real Memory Model

Variable Area

name
age
city
salary

      │
      │
      ▼

Memory (Objects)

┌────────────┐
│ "Tony"     │
├────────────┤
│ 53         │
├────────────┤
│ "London"   │
├────────────┤
│ 50000      │
└────────────┘

Variables point to objects stored in memory.


Important Notes

  • A variable is not the value.
  • A variable is not the memory location itself.
  • A variable is a reference (name) to an object.
  • Python automatically manages memory.
  • Variables can point to different objects over time.

Easy Analogy

Imagine labeled boxes.

Label

name
 │
 ▼

"Ironman"

The label (name) tells you where to find the value.

Changing the label to another value

Before

name
 │
 ▼
"Ironman"


After

name
 │
 ▼
"Tony"

The label stays the same.

Only what it points to changes.


Quick Summary

Variable
    │
    ▼
Reference
    │
    ▼
Object in Memory
    │
    ▼
Value

Example

name = "Ironman"
name
 │
 ▼
┌──────────────────┐
│    "Ironman"     │
└──────────────────┘

Python creates the object first, then binds the variable name to that object.

Python Variable Naming Rules

Variable names are identifiers used to refer to objects (values) in Python.

name = "Ironman"
  • name → Variable (Identifier)
  • = → Assignment Operator
  • "Ironman" → Value (Object)

Variable Name Syntax

A variable name follows this pattern:

First Character
       │
       ▼
Letter (A-Z, a-z)
or
Underscore (_)

       +

Remaining Characters
       │
       ▼
Letters
Numbers
Underscore (_)

Example

student_name1
│
├── student
├── _
├── name
└── 1

Rule 1: Letters are Allowed

Variables may start with or contain English letters.

✅ Valid

name
student
price
total
Python
python
Age
name = "Tony"
student = "Peter"
price = 500

Why?

Letters are valid identifier characters.


Rule 2: Digits (0-9) are Allowed

Numbers are allowed after the first character.

✅ Valid

age1
version2
python3
student123
price2025
x1
age1 = 20
version2 = "2.0"

Rule 3: Variable Cannot Start with a Number

Python cannot parse identifiers beginning with digits.

❌ Invalid

1name
2age
100marks
123abc
9price

Example

1name = "Tony"

Output

SyntaxError: invalid decimal literal

✅ Correct

name1 = "Tony"
marks100 = 95

Rule 4: Underscore (_) is Allowed

The underscore is treated as a normal identifier character.

✅ Valid

student_name
first_name
last_name
_marks
_private
employee_salary
phone_number

Example

first_name = "Tony"

Rule 5: Spaces are NOT Allowed

Python treats spaces as separators between tokens.

❌ Invalid

student name
first name
user age
student name = "Tony"

Output

SyntaxError

✅ Correct

student_name = "Tony"
user_age = 20

Rule 6: Hyphen (-) is NOT Allowed

The hyphen is the subtraction operator.

❌ Invalid

student-name
total-price

Python reads

student - name

instead of one variable.

✅ Correct

student_name
total_price

Rule 7: Special Characters are NOT Allowed

These characters cannot appear in identifiers.

❌ Invalid

student@name
student#name
student$name
student%name
student^name
student&name
student*name
student!name
student?name
student.name
student,name
student:name
student;name
student/name
student\name
student+name
student=name
student(name)
student[name]
student{name}
student|name
student~name
student`name

These characters have special meanings in Python.

Use _ instead.

✅ Correct

student_name

Rule 8: Variable Names are Case Sensitive

Python treats uppercase and lowercase letters differently.

name = "Tony"

Name = "Steve"

NAME = "Bruce"

These are three different variables.

name
Name
NAME

Memory

name ─────► "Tony"

Name ─────► "Steve"

NAME ─────► "Bruce"

Rule 9: Python Keywords Cannot Be Variable Names

Keywords already have predefined meanings.

❌ Invalid

if = 10
for = 20
while = 30
class = "A"
return = 5
try = 1

Output

SyntaxError

Common Keywords

False
None
True
and
as
assert
async
await
break
case
class
continue
def
del
elif
else
except
finally
for
from
global
if
import
in
is
lambda
match
nonlocal
not
or
pass
raise
return
try
while
with
yield

Rule 10: Built-in Names Can Be Used (But Avoid It)

Python allows this.

list = [1, 2, 3]

But now

list("abc")

fails because list no longer refers to the built-in function.

Avoid names like

list
dict
set
tuple
str
int
float
bool
sum
max
min
len
type
print
input

Rule 11: Unicode Variable Names

Python supports Unicode identifiers.

नाम = "Ironman"

年龄 = 20

π = 3.14159

Although valid, English names are recommended for readability.


Valid Variable Names

name
student
student_name
student_name1
student1
_name
_marks
price
PRICE
Price
user_age
employee_salary
phone_number
email_address
address
salary
height
weight
version2
python3
data
count
counter
total_marks
max_value
min_value
first_name
last_name
middle_name
employee_id
customer_name
is_active
is_logged_in
has_permission

Invalid Variable Names

1name
2age
100marks

student-name
student name
student@name
student#name
student$name
student%name
student^name
student&name
student*name
student!name
student?name
student.name
student,name
student:name
student;name
student/name
student\name
student+name
student=name
student(name)
student[name]
student{name}
student|name
student~name
student`name

if
for
while
class
return
try
except
True
False
None

Good vs Bad Variable Names

❌ Poor

a = 25

x = 50000

n = "Tony"

d = "2026-01-01"

p = 99.5

Hard to understand.


✅ Better

age = 25

salary = 50000

name = "Tony"

joining_date = "2026-01-01"

percentage = 99.5

The purpose is immediately clear.


Naming Style (PEP 8)

Python recommends snake_case.

✅ Recommended

first_name
last_name
student_age
employee_salary
phone_number
email_address
product_price
maximum_speed
total_marks

❌ Not Recommended

FirstName

FIRSTNAME

firstName

First_Name

Memory Visualization

name = "Tony"

age = 53

salary = 90000
name
 │
 ▼
"Tony"

age
 │
 ▼
53

salary
 │
 ▼
90000

Complete Example

first_name = "Tony"
last_name = "Stark"
age = 53
salary = 1000000
is_hero = True

Memory

first_name ─────► "Tony"

last_name ──────► "Stark"

age ────────────► 53

salary ─────────► 1000000

is_hero ────────► True

Quick Revision Table

Rule Allowed
Letters
Digits after first character
Start with digit
Underscore _
Space
Hyphen -
Special characters
Keywords
Case-sensitive
Unicode ✅ (not recommended for most projects)
snake_case ✅ Recommended

One-Line Revision

Variable Name Rules

✅ Letters
✅ Digits (not first)
✅ Underscore (_)

❌ Start with digit
❌ Spaces
❌ Special characters
❌ Python keywords

Recommended:
snake_case
Meaningful names
Avoid built-in names

Variable Name Examples

Valid Variable Names

Variable Name Valid Reason
name Starts with a letter
student Only letters
student_name Uses underscore
student1 Number at the end
student_name1 Letters, underscore, number
_name Starts with underscore
_marks Underscore is allowed
a Single letter
x Single letter
age1 Number after letter
python3 Number at the end
version2 Valid identifier
price2025 Numbers allowed after first character
first_name snake_case
last_name snake_case
employee_salary snake_case
phone_number snake_case
email_address snake_case
is_active Boolean naming convention
has_permission Descriptive name
MAX_SIZE Constant naming style
userAge Valid (camelCase, but not PEP 8 recommended)
UserName Valid (PascalCase, but not recommended for variables)
π Unicode identifier
नाम Unicode identifier

Invalid Variable Names

Variable Name Invalid Reason
1name Starts with a number
2age Starts with a number
123abc Starts with a number
student name Contains a space
student-name Hyphen (-) is subtraction operator
student@name @ not allowed
student#name # not allowed
student$name $ not allowed
student%name % not allowed
student^name ^ not allowed
student&name & not allowed
student*name * not allowed
student!name ! not allowed
student?name ? not allowed
student.name . not allowed
student,name , not allowed
student:name : not allowed
student;name ; not allowed
student/name / not allowed
student\name \ not allowed
student+name + not allowed
student=name = is assignment operator
student(name) Parentheses not allowed
student[name] Square brackets not allowed
student{name} Curly braces not allowed
`student name`
student~name ~ not allowed
student`name Backtick not allowed
if Python keyword
for Python keyword
while Python keyword
class Python keyword
return Python keyword
import Python keyword
try Python keyword
except Python keyword
True Reserved keyword
False Reserved keyword
None Reserved keyword

Valid but Not Recommended

Variable Name Valid Reason
l Looks like 1
O Looks like 0
I Looks like 1 or l
x Too generic
temp Not descriptive
data Too generic
value Too generic
list Shadows built-in list()
dict Shadows built-in dict()
str Shadows built-in str()
int Shadows built-in int()
float Shadows built-in float()
print Shadows built-in print()
sum Shadows built-in sum()
max Shadows built-in max()
min Shadows built-in min()
type Shadows built-in type()

Quick Revision

Rule Example
Starts with letter name
Starts with underscore _name
Starts with number 1name
Contains spaces student name
Contains special characters student@name
Uses underscore student_name
Python keyword if
Case-sensitive name, Name, NAME are different
Unicode allowed π, नाम
Recommended style snake_case