Python Variables

Python Variables

1. What is a Variable?

  • A variable is a named location in memory that stores data.
  • It acts as a container for values.
  • Example:

    x = 10
    name = "Alice"
    

2. Rules for Variable Names

✅ Can contain letters, numbers, and underscores (_)

 ✅ Must start with a letter or underscore (not a number) 

Case-sensitive (Name and name are different) 

❌ Cannot use Python keywords (for, if, class, etc.) Example:

user_name = "John"
UserName = "Mike"  # different from user_name

3. Assigning Values

  • Single assignment:

    age = 25
    
  • Multiple assignment:

    x, y, z = 1, 2, 3
    
  • Same value to multiple variables:

    a = b = c = 0
    

4. Variable Types (Dynamic Typing)

  • No need to declare type — Python decides at runtime.
x = 5        # int
x = "Hello"  # now str

5. Data Types Commonly Used

  • int – integers (e.g., 10, -5)
  • float – decimal numbers (e.g., 3.14)
  • str – text strings (e.g., "Python")
  • boolTrue or False
  • list, tuple, set, dict — collections

6. Constants

  • Python doesn’t have true constants — by convention, use UPPERCASE names.
PI = 3.14159

7. Deleting Variables

x = 10
del x

8. Type Casting

  • Convert between data types:
x = int("10")       # string to int
y = float(5)        # int to float
z = str(3.14)       # float to string

9. Checking Variable Type

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

10. Global & Local Variables

x = "global"

def test():
    x = "local"
    print(x)  # local

test()
print(x)      # global

Previous Post Next Post