liveBook · Manning

Branch

As explained in Get Programming: Learn to code with Python

A branch is an alternative program-execution path selected by the result of a condition.

A branch is an alternative program-execution path chosen by a condition. In Python, an if-elif-else block checks decisions in order and runs the first block whose condition is True; else runs when none match. section 14.2

Use branches to:

  • Choose between outcomes, such as reporting whether a number is positive, negative, or zero. section 14.2
  • Create several paths by nesting conditionals inside one another. section 15.3
  • Handle expected user choices while clearly stating the allowed input. section 15.0 section 15.1

A number decision

num = int(input("Enter a number: ")) if num > 0: print("num is positive") elif num < 0: print("num is negative") else: print("num is zero") For 2, the first branch runs. For -3, the second runs. For 0, neither condition is true, so else runs. Only one message is printed. section 14.2

Figure 15.1. The boxes represent choices for the user. The text below the boxes represents the situation. The gray arrows show the path with the choice made. The dotted black lines to a smiley face or a sad face represent the end of the program, with survival or not. Out of five possible outcomes, only one leads to survival.

Trace the decision boxes and arrows to see how each choice leads to another situation and eventually to an outcome. section 15.3

How Get Programming: Learn to code with Python covers it

How deep it goes
Explains first-true if-elif-else execution, nesting, optional else blocks, and path tracing, but stops short of advanced control flow.
Examples
Uses number-sign checks, capitalized commands, and a survival adventure with five outcomes and one successful path.
What you can do after
Build it from scratch by writing branching stories that respond to expected user choices.
How it connects
Connects branches with conditionals, if statements, elif, else, nested conditionals, user input, and flowcharts.

Also explained in

Compare how 6 books explain branch →

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.