You can learn about Control Statements in Python Programs with Outputs helped you to understand the language better.
Python Programming – Notion Of Iterating Computation (Loops)
Many jobs that are required to be done with the help of a computer are repetitive in nature. For example, the calculation of wages of different workers in a factory is done using the formula (No. of hours worked) x (wage rate). This calculation will be performed by an accountant for each worker every month. Such types of repetitive calculations can easily be done with the help of a program that has a built-in loop. Figure 5.21 shows the flow diagram of the loop statement.
- Python Programming – Flowcharts for Sequential, Decision-Based and Iterative Processing
- Python Programming – Conditional and Iterative Statements
- Introduction to Python Programming – Interpreter
What is a Loop?
A loop is defined as a block of instructions repeated a certain number of times. Figure 5.22 illustrates a flowchart showing the concept of looping. It shows the flowchart for printing values 1, 2, 3…, 20. In Step 5 of Figure 5.22, the current value of A is compared with 21. If the current value of A is less than 21, steps 3 and 4 are repeated. As soon as the current value of A becomes more than 21, the path corresponding to “NO” is followed, and the repetition process stops.
By default, statements in the script are executed sequentially from the first to the last. But the sequential flow can be altered either by conditional execution where a block of one or more statements will be executed if a certain expression is true or by repetitive execution where a block of one or more statements will be repetitively executed as long as a certain expression is true.
Python uses the while and for keywords to constitute a conditional loop, by which repeated execution of a block of statements is done until a Boolean expression is true.