#1 Data Analytics Program in India
₹2,499₹1,499Enroll Now
5 min read
•Question 3 of 41easy

Variables in Python

How variables work in Python.

What You'll Learn

  • How Python variables differ from other languages
  • Variable naming conventions and rules
  • Dynamic typing and type inference
  • Variable scope and memory management

Understanding Python Variables

In Python, variables are references to objects in memory. Unlike languages like C or Java, Python doesn't require explicit type declarations. When you assign a value to a variable, Python automatically determines the type.

Think of variables as labels or name tags attached to objects, rather than containers that hold values.

Variable Assignment

code.pyPython
# Simple assignment - creates a reference to an object
x = 5
name = "Alice"
is_active = True

# Multiple assignment - assign multiple variables at once
a, b, c = 1, 2, 3
print(a, b, c)  # 1 2 3

# Tuple unpacking
coordinates = (10, 20)
x, y = coordinates

# Same value to multiple variables
x = y = z = 0

# Swapping values (Python's elegant way)
a, b = b, a  # No temp variable needed!

Variable Naming Rules

Python has strict rules for variable names:

RuleValidInvalid
Start with letter or underscorename, _private2name
No special charactersmy_varmy-var, my@var
No spacesuser_nameuser name
Case sensitiveName ≠ name-
No reserved wordsmy_classclass, def
code.pyPython
# Valid variable names
my_var = 1
_private = 2
myVar2 = 3
CamelCase = 4
CONSTANT = 5

# Invalid names (will cause SyntaxError)
# 2myvar = 1      # Can't start with number
# my-var = 1      # Hyphens not allowed
# my var = 1      # Spaces not allowed
# class = 1       # Reserved keyword

Naming Conventions (PEP 8)

code.pyPython
# Variables and functions: snake_case
user_name = "john"
total_count = 42

# Constants: UPPERCASE
MAX_SIZE = 100
PI = 3.14159

# Classes: PascalCase
class UserProfile:
    pass

# Private variables: leading underscore
_internal_value = "private"

# Dunder (magic) methods: double underscore
__init__, __str__, __repr__

Dynamic Typing

Python is dynamically typed - variables can change type at runtime:

code.pyPython
x = 5           # x is int
print(type(x))  # <class 'int'>

x = "hello"     # x is now str
print(type(x))  # <class 'str'>

x = [1, 2, 3]   # x is now list
print(type(x))  # <class 'list'>

x = {"a": 1}    # x is now dict
print(type(x))  # <class 'dict'>

Type Checking

code.pyPython
x = 42

# Using type()
print(type(x))  # <class 'int'>
print(type(x) == int)  # True

# Using isinstance() - preferred, handles inheritance
print(isinstance(x, int))  # True
print(isinstance(x, (int, float)))  # Check multiple types

Variable Scope

code.pyPython
# Global scope
global_var = "I'm global"

def my_function():
    # Local scope
    local_var = "I'm local"
    print(global_var)  # Can access global
    print(local_var)   # Can access local

my_function()
# print(local_var)  # Error! Not accessible outside function

# Modifying global inside function
count = 0

def increment():
    global count  # Declare intent to modify global
    count += 1

increment()
print(count)  # 1

Memory and References

code.pyPython
# Variables are references
a = [1, 2, 3]
b = a  # b points to same list

b.append(4)
print(a)  # [1, 2, 3, 4] - a is also modified!

# To create a copy instead
a = [1, 2, 3]
b = a.copy()  # or b = a[:]
b.append(4)
print(a)  # [1, 2, 3] - a unchanged

# Check if same object
print(a is b)  # False (different objects)
print(a == b)  # May be True (same values)

# id() shows memory address
print(id(a), id(b))  # Different addresses

Interview Tip

When asked about Python variables:

  1. Explain they're references to objects, not containers
  2. Mention dynamic typing vs static typing
  3. Discuss naming conventions (PEP 8)
  4. Explain scope: local, global, nonlocal
  5. Be ready to explain mutable vs immutable object references