liveBook · Manning

Initialization

As explained in Get Programming: Learn to code with Python

Initialization is the process of establishing initial values or a starting state for a program entity, component, resource, or computation before subsequent operation.

Initialization gives something its starting value. In Python, initializing a variable with `=` binds a name to an object. You can then use that name in an expression. If you assign the name again later, you update it; that is different from giving it its first value. section 4.2

Start with values you can use

`a = 1` initializes `a`, and `b = 2` initializes `b`. Then `c = a + b` initializes `c` with the expression’s result, `3`. In a minutes-conversion program, `minutes_to_convert = 123` similarly supplies a starting input before the conversion. section 4.2 section 6.2

A `while` loop needs a starting value for the variable its condition checks. For example, set `x = 0` before `while x < 3`, then increase `x` each time through the loop. Without the first assignment, Python does not know which `x` the loop means. A `for` loop handles its loop variable automatically. section 18.2

Objects need a starting state too. A class’s `__init__` method usually sets its data attributes—the values belonging to each object. `self.radius = 0` gives a new circle a radius of zero; `self.stack = []` gives a new stack an empty list. Here, `self` refers to the object being initialized. section 31.2 section 32.1

Quick check: in `x = 0; x = 2`, which assignment initializes `x`, and which updates it? When writing a loop or class, ask what values must exist before the rest of its code can work. section 4.2 section 18.2

How Get Programming: Learn to code with Python covers it

How deep it goes
Defines variable initialization as name binding and shows how `__init__` establishes object attributes through small Python examples.
Examples
Uses arithmetic variables, a minutes-conversion input, a loop counter, a circle’s radius, and an empty stack.
What it assumes
Starts with creating variables before extending initialization to loops and classes.
What you can do after
Build it from scratch by assigning starting values to variables and defining initial attributes in a class’s `__init__` method.
How it connects
Connects initialization to assignment, expressions, while loops, classes, methods, and data attributes.

Also explained in

Compare how 5 books explain initialization →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Get Programming: Learn to code with Python. The section links point to the parts of the book it draws on.