Variables in Python

Our first example will demonstrate variable declaration and initialization in Python. Here’s the full source code:

def main():
    # Variables are declared and initialized in one step
    a = "initial"
    print(a)

    # You can declare multiple variables at once
    b, c = 1, 2
    print(b, c)

    # Python infers the type of variables
    d = True
    print(d)

    # Variables without initialization are not allowed in Python
    # Instead, we can use None to represent an uninitialized variable
    e = None
    print(e)

    # In Python, all variable declarations use the same syntax
    f = "apple"
    print(f)

if __name__ == "__main__":
    main()

In Python, variables are dynamically typed and do not need explicit declaration. The interpreter infers the type based on the assigned value.

You can run this program by saving it as variables.py and using the python command:

$ python variables.py
initial
1 2
True
None
apple

Key points about variables in Python:

  1. Variables are created when you first assign a value to them.
  2. Python uses dynamic typing, so you don’t need to specify the type of a variable.
  3. You can assign multiple variables at once using tuple unpacking.
  4. Variables that are declared but not initialized are not allowed in Python. You can use None to represent an uninitialized state.
  5. Python doesn’t have a specific syntax for declaring constants, but it’s a convention to use uppercase names for values that shouldn’t be changed.

Understanding how variables work is crucial for writing effective Python code. In the next examples, we’ll explore more complex data structures and control flow in Python.