Python

Python Variables

Variables in Python are used to store data values. Unlike statically typed languages, Python is dynamically typed, which means you do not need to declare a variable type explicitly — Python determines it at runtime.

1. Creating Variables

Assign a value using the = operator:

x = 10        # Integer
        name = "Talha"   # String
        pi = 3.14        # Float
        
---

2. Rules for Variable Names

  • Must start with a letter or underscore (_)
  • Can only contain letters, numbers, and underscores
  • Case-sensitive (myVar and myvar are different)
  • Cannot use Python keywords (like if, for, class)
---

3. Multiple Assignments

Python allows assigning multiple variables in one line:

a, b, c = 10, 20, 30
        x = y = z = 5
        
---

4. Variable Types

Python automatically assigns types based on the value:

  • int → whole numbers
  • float → decimal numbers
  • str → strings
  • bool → True / False
  • list, tuple, set, dict → collections
---

5. Changing Variable Values

In Python, variables act as labels pointing to objects in memory. You can always reassign a variable to a new value. This is why we say Python variables are mutable by default.

However, the object itself may be mutable or immutable:

  • Mutable objects – their content can be changed without creating a new object (e.g., list, dict, set).
  • Immutable objects – their content cannot be changed. To “change” them, a new object is created (e.g., int, float, str, tuple).

Examples:

# Changing an integer (immutable object)
        x = 10
        x = x + 5   # x now points to a new integer object 15

        # Changing a string (immutable object)
        name = "Talha"
        name = name + " Abbas"  # Creates a new string object "Talha Abbas"

        # Changing a list (mutable object)
        nums = [1, 2, 3]
        nums[0] = 10   # Modifies the list in-place: nums = [10, 2, 3]
        nums.append(4) # Adds 4 to the same list object: nums = [10, 2, 3, 4]

        # Reassigning a list variable
        nums = [100, 200]  # nums now points to a new list object
        

Key Points:

  • Variable names can always be reassigned to point to new objects.
  • Immutable objects cannot be changed in-place; any “change” creates a new object.
  • Mutable objects can be updated directly without creating a new object.
---

6. Dynamic Typing

Python determines the variable type at runtime and can change it:

var = 10       # int
        var = "hello"   # now str
        var = 3.14      # now float
        
---

7. Type Conversion

You can explicitly convert variables from one type to another:

x = int(3.14)      # 3
        y = float(10)         # 10.0
        z = str(100)          # "100"
        
---

8. Constants

Python doesn’t have true constants, but by convention, uppercase names are used to indicate a value that should not change:

PI = 3.14159
        MAX_USERS = 100
        
---

9. Variable Scope

Scope defines where a variable can be accessed:

9.1 Local Variables

Declared inside a function and accessible only within it:

def my_func():
            x = 10
            print(x)   # 10
        

9.2 Global Variables

Declared outside functions and accessible anywhere:

x = 100

        def my_func():
            print(x)  # 100
        

9.3 Global Keyword

Used to modify a global variable inside a function:

x = 5

        def update():
            global x
            x = 10

        update()
        print(x)  # 10
        
---

10. Best Practices

  • Use meaningful variable names
  • Follow snake_case naming convention
  • Avoid using single-character names except in loops or small functions
  • Use constants for fixed values (uppercase)
---

11. Interview Questions

Q1. Can Python variables change type?

Yes, Python is dynamically typed.

Q2. What is the difference between local and global variables?

Local variables are defined in a function and accessible only there. Global variables are accessible anywhere.

Q3. How do you create a constant in Python?

Python has no true constants. By convention, uppercase variable names indicate constants.

Q4. Can you assign multiple variables in one line?

Yes, using comma separation:

a, b, c = 1, 2, 3