Control Flow: For Loops, While loops and range() BEHIND THE SCENES!
Welcome to this section on Control Flow!
Control flow is an essential element of programming. You can build very powerful programs with loops, so let's see how they work behind the scenes, and how range() works, because you will use it in this course and in your future programming projects.
So let's begin!
Let's start with WHILE LOOPS:
In While loops a block of code will be executed for as long as a condition is met. Every time the block of code is executed, the condition will be checked again, and if it evaluates to True, the code inside the loop runs again, otherwise it exits the loop and continues executing the code below it.
When learning loops, a good strategy is to analyze each step and how values change when the code is executed. In this case, we determine if the code will be executed, the values for the variables involved each time the loop runs and what will be printed on each iteration.
The value of n is updated every time the loop executes. When the condition is checked, the new value of n will determine if the loop runs again or if it stops.
Now let's study FOR LOOPS:
For loops may use the
range()
function.The range function
This function returns a series of integers that are determined by the numbers we use inside parentheses ( ).
The general structure of range( ) is
range( start, stop, step)
- The start point is the integer from where the sequence will start. (Will be included)
- The stop point is the integer at which the sequence will end (NOT Included)
- The step is the "jump" between one number and the next
You
can find more info on range() at this link
When we execute a for loop with range(), the value of the variable next to the for keyword will be update each time the loop runs, it will be assigned a number in the integer sequence returned by range(). The first time through the loop it will assign the first value in the collection of integers, the second time the second value will be assigned to the variable and so on.
The for loop stops when it reaches the end of the sequence of integers returned by range().
Alternative syntax
You may have noticed that I used "may use the range function". There is another syntax for using for loops when iterating over the elements in a string, tuple or list.
Hope it helps!
If you have any questions or comments on this topic, please share them on the forums or right below this topic! You classmates and Community TAs will always be there to help you.
Estefania.
Comments
Post a Comment