The default mode of execution of a program is from top to bottom. However in the course of the execution of a program, the Python interpreter comes across some statements that change the default mode of execution.
Such statements are called a branch. A branch is an instruction in a computer program that causes a computer to begin executing a different instruction sequence and thus deviate from its default behaviour of executing instructions in order.
Branching is implemented as a series of control statements in high level programming languages. In the Python programming language, these include:
The IF Statement works by evaluating a programmer specified boolean condition and checking if it evaluates to true or false.
If the condition evaluates to true, certain actions are carried out. An evaluation to false means that alternate actions are carried out.
A loop ensures that code is repeated. However in programming when you want ensure that you loop an infinite number of times, you use a WHILE loop.
The WHILE loop consists of a block of code and a condition/expression. The condition/expression is evaluated, and if the condition/expression is true, the code within all of their following in the block is executed. This repeats until the condition/expression becomes false.
In the Python programming language, the WHILE loop has an ELSE branch just like the IF statement.
When you want to loop a fixed number of times in the Python programming language, you use a FOR loop.
A FOR loop has two parts: a header specifying the iteration, and a body which is executed once per iteration. The header often declares an explicit loop counter or loop variable, which allows the body to know which iteration is being executed. FOR loops are typically used when the number of iterations is known before entering the loop.
Branching statements allow the flow of execution to jump to a different part of the program.
Mastering them is important in the journey of learning how to program.