liveBook · Manning

Block

As explained in Get Programming: Learn to code with Python

A code block is a grouped region of code treated as a unit, with boundaries and scope or execution behavior determined by its language or context.

In Python conditionals, a code block is the indented group of statements that runs when its condition is true. If the condition is false, the program skips that group and continues. section 13.2

Indentation shows which statements belong together:

  • A conditional block follows an if statement and is indented beneath it. section 13.2
  • Blocks can contain nested conditionals, each with its own indented block. Separate conditionals in a series are checked one after another. section 13.3
Listing 13.2. A general way to write a simple if conditional
<some code before>               #1
if <conditional>:                #2
    <do something>               #3
<some code after>                #1

A general if-statement outline shows how the indented block sits between code before and after the condition. section 13.2

Listing 13.4. Combining conditionals by nesting or by putting them in series
Nested code                                   Unnested code
num_a = int(input("Number? "))                num_a = int(input("Number? "))
num_b = int(input("Number? "))                num_b = int(input("Number? "))
if num_a < 0:                      #1          if num_a < 0:             #1
    print("num_a: is negative")                   print("num_a is negative")
    if num_b < 0:                  #2          if num_b < 0:             #2
        print("num_b is negative")                print("num_b is negative")
print("Finished")                  #3           print("Finished")        #3

Compare nested and unnested conditionals to see how a block controls whether a second decision is reached. section 13.3

How Get Programming: Learn to code with Python covers it

How deep it goes
Explains indentation, conditional execution, and nested blocks, but does not treat blocks beyond conditional statements.
Examples
Uses positive, negative, and zero checks, plus nested decisions about hunger and chocolate prices.
What you can do after
Apply Python if statements to write, test, and debug programs that make decisions.
How it connects
Connects code blocks with if statements, Boolean conditions, nested conditionals, and flowcharts.

Also explained in

Compare how 5 books explain block →

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.