Python Variables

Variables

Variables in Python are containers for storing data values.

Variable Assignment

Python has no command for declaring variables – they are created when you first assign a value.

 # Basic assignment
 x = 5           # Integer
 y = "Hello"     # String
 z = 3.14        # Float
Python is dynamically typed – variables can change type after assignment
var = 4       # Integer
var = "Four"  # Now a string

Variable Naming Rules

  • ✅ Must start with letter or underscore
  • ✅ Can contain letters, numbers, and underscores
  • ✅ Case-sensitive (Age ≠ AGE ≠ age)
  • ❌ Cannot use reserved keywords
 # Valid names
 my_var = 1
 _var2 = "test"
 MAX_COUNT = 100  # Convention for constants

 # Invalid names
 2var = 5      # Error
 my-var = 10   # Error
 $amount = 5   # Error

Data Types

Common Data Types
  • int – integer
  • float – decimal
  • str – text
  • bool – True/False
Examples
 a = 5           # int
 b = 5.0         # float
 c = "Python"    # str
 d = True        # bool

Type Conversion

 # Explicit conversion
 x = int(3.9)    # 3 (truncates decimal)
 y = float(3)    # 3.0
 z = str(3.14)   # "3.14"

Type Checking

 print(type(x))
 print(isinstance(y, float))  # True

Assigning Multiple Values

Multiple Assignment
 a, b, c = 1, 2, 3
 print(a, b, c)  # 1 2 3
Same Value
 x = y = z = 0
 print(x, y, z)  # 0 0 0

Output Variables

 name = "Alice"
 age = 25
 print(name, "is", age, "years old")  # Alice is 25 years old

 # Using f-strings (Python 3.6+)
 print(f"{name} is {age} years old")  # Alice is 25 years old

Global Variables

 global_var = "I'm global"

 def myfunc():
     # Accessing global variable
     print(global_var)

     # Modifying global variable
     global local_var
     local_var = "I'm local"
     global another_var
     another_var = "New global"

 myfunc()
 print(local_var)       # Error - local variable
 print(another_var)     # "New global"

Variable Best Practices

Do
  • Use descriptive names
  • Use snake_case naming
  • Initialize variables properly
Don’t
  • Use ambiguous names like x, y
  • Use reserved keywords
  • Reuse variable names carelessly
Remember: Python variables are references to objects. Assignment creates new references, not copies!