Skip to main content

Python Variables

1. What is a Variable?

  • A variable is a named location in memory used to store data.
  • It acts as a container for storing values that can be used and manipulated throughout a program.

2. Variable Naming Rules

  • Valid Names:
    • Must start with a letter (a-z, A-Z) or an underscore (_).
    • Can contain letters, numbers (0-9), and underscores.
    • Case-sensitive (age, Age, and AGE are different variables).
  • Invalid Names:
    • Cannot start with a number.
    • Cannot contain spaces or special characters (e.g., @, #, $).
    • Cannot be a Python keyword (e.g., if, else, for, while).
Examples:

3. Assigning Values to Variables

  • Use the assignment operator = to assign a value to a variable.
  • Python is dynamically typed, so you don’t need to declare the type of a variable explicitly.
Examples:

4. Multiple Assignments

  • You can assign multiple variables in a single line.
Examples:

5. Variable Types

  • Python variables can hold data of different types:
    • Integer: Whole numbers (e.g., 10, -5)
    • Float: Decimal numbers (e.g., 3.14, -0.001)
    • String: Text (e.g., "Hello", 'Python')
    • Boolean: True or False
    • List: Ordered, mutable collection (e.g., [1, 2, 3])
    • Tuple: Ordered, immutable collection (e.g., (1, 2, 3))
    • Dictionary: Key-value pairs (e.g., {"name": "Alice", "age": 25})
    • Set: Unordered, unique elements (e.g., {1, 2, 3})
Examples:

6. Dynamic Typing

  • Python is dynamically typed, meaning the type of a variable is determined at runtime and can change.
Example:

7. Type Checking

  • Use the type() function to check the type of a variable.
Example:

8. Variable Scope

  • Local Scope: Variables defined inside a function are local to that function.
  • Global Scope: Variables defined outside a function are global and can be accessed anywhere.
Example:

9. Deleting Variables

  • Use the del keyword to delete a variable.
Example:

10. Constants

  • Python doesn’t have built-in support for constants, but by convention, use uppercase names for constants.
Example:

11. Best Practices

  • Use descriptive variable names (e.g., user_age instead of ua).
  • Follow naming conventions (e.g., snake_case for variable names).
  • Avoid using single-letter variable names unless in loops or mathematical contexts.