Python Variables

In Python, variables are used to store data values. They act as containers for storing information that can be referenced and manipulated throughout the program. Python has dynamic typing, which means you don’t need to declare the variable type—it is determined automatically based on the value assigned.

 

Key Features of Python Variables


  1. Dynamic Typing: No need to specify data type.
    x = 10 # Integer
    y = "Hello" # String
    z = 3.14 # Float
    
  2. Case-Sensitive: Variable names are case-sensitive.
    myVar = 10
    MyVar = 20 # Different from myVar
    
  3. Name Rules:
    • Must start with a letter or an underscore (_).
    • Cannot start with a number.
    • Can contain letters, numbers, and underscores.
    • Cannot use reserved keywords like class, def, etc.
      # Valid variable names
      _name = "John"
      age = 25
      number_of_items = 10
      
      # Invalid variable names
      1name = "Invalid" # Starts with a number
      name@ = "Invalid" # Contains a special character
      
  4. Reassignment:

    Variables can be reassigned to a different type.

    x = 10
    x = "Hello" # x is now a string
    

 

Variable Assignment


  1. Single Assignment:
    x = 5
    name = "Alice"
    
  2. Multiple Assignment:

    a, b, c = 1, 2, 3 # Assign multiple variables at once
    x = y = z = 0 # Assign the same value to multiple variables
    

 

Types of Variables


Python variables can store various data types:

Data Type Description Example
int Integer (whole number) x = 10
float Floating-point number (decimal) y = 10.5
complex Complex number z = 3 + 5j
bool Boolean (True or False) is_valid = True
str String (text) name = “Alice”
list List (ordered, mutable collection) fruits = [“apple”, “banana”]
tuple Tuple (ordered, immutable collection) coordinates = (10, 20, 30)
dict Dictionary (key-value pairs) person = {“name”: “Alice”}
set Set (unordered, unique items) unique_numbers = {1, 2, 3}
frozenset Immutable version of a set frozen_numbers = frozenset([1, 2])
bytes Immutable sequence of bytes byte_data = b”Hello”
bytearray Mutable sequence of bytes byte_array_data = bytearray(5)
memoryview View on binary data memory_view = memoryview(b”Hello”)
NoneType Absence of value value = None

 

Variable Scope


  1. Global Variables:
    • Declared outside any function.
    • Accessible anywhere in the program.
      x = "global"
      def print_global():
          print(x) # Accessing the global variable
      
      print_global() # Output: global
      
  2. Local Variables:
    • Declared inside a function.
    • Accessible only within that function.
      def my_function():
          y = "local"
          print(y)
      my_function() # Output: local
      print(y) # Error: y is not defined
      
  3. Using global Keyword:
    • Modify a global variable inside a function.
    • x = "global"
      def change_global():
          global x
          x = "modified"
      change_global()
      print(x) # Output: modified
      

 

Best Practices for Variables


  • Use descriptive names to make your code self-explanatory.
    # Bad
    x = 10
    # Good
    item_price = 10
    
  • Use snake_case for variable names (e.g., total_price, user_name).
  • Avoid reserved keywords as variable names (e.g., class, def).
  • Initialize variables before using them.
  • Use constants for values that should not change. By convention, constants are written in all uppercase.
    PI = 3.14
    MAX_USERS = 100
    

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *