Tuesday, June 2, 2020

Iterations – For Loop


In “for” loop, there’s no condition after it. So we don’t think about conditions. Because they’re checked internally without any intervention.

Variable after the “for” keyword is the control variable of the loop. It counts the loop’s turns & does it automatically.

The “in” keyword explains a syntax element describing the range of possible values being assigned to the control variable.

The “range ()” function use for generating all the desired values of the control variable. In this case, the range () function starts its job from 0 & finishes it one step before the value of its argument.

Let’s consider about the below program.






Output is















The “range ()” function invocation may be equipped with two arguments & not just one. Given below an example.






Output is










 The range () function accepts only integers as its arguments & generates sequences of integers.

The third argument is an increment - it's a value added to control the variable at every loop turn. Consider the below program.





Output is







If the set generated by the range () function is empty, the loop won't execute its body at all. See below example.






There is no output.


The set generated by the range () has to be sorted in ascending order. There's no way to force the range () to create a set in a different form. This means that the range ()’s second argument must be greater than the first.

Consider the below example also.






Again there’s no output.


Look at the below program.








Output is





















Given below the final example with “time” module.










Output is













No comments:

Post a Comment