Repetition structures, or loops, allow a statement, or set of statements to run repeatedly.
As we’ve mentioned before, computers are stupid. They are bad at doing complex things, and in order to do something complex, you have to break it down into its simplest forms.
However, what they are good at, is doing lots of things, very, very quickly. They excel at doing small, simple tasks quickly. So you might have a program which is to determine if, and how much of a bonus a sales person should get. But it can just as easily calculate the sales bonuses for every sales person in the organization.
Image if you had to write that code, asking for how much sales they were responsible for, and then making that calculation. Then redoing it again, and again, for every sales person. It would be time consuming for you, and amake it easy to make an error. Additionally, it would potentially cause an issue as what happens if your company hires a new slaes person, or someone leaves? You would have to modify the code all over again.
This is where using loops becomes so helpful. You can create a loop, and reuse the same code over and over making it easier to write and maintain.
There are two main types of loops. The book refers to them as condition controlled and count-controlled loops. Other places call them conditional loops and counter loops. Both are correct, it is just a matter of which method they used.
While Loop
The while loop is a condition controlled loop that follows a general form of:
while <condition> :
loop body
statement...
The condition is just like the condition in an if statement. It must have a Boolean result. Typically it might be something in pseudo-code like, while the value is greater than zero, or while not at the end of a file.
Full example:
again = "Y"
while again == "Y" :
# Notice how this input is much easier to use as an end user than the next one.
# Here we use spaces, and a colon to show that some input is required
sales = float(input("How much sales did the sales person make this month: "))
# This input has no space, and is harder to read/user
rate = float(input("What is the commission rate"))
commission = rate * sales
# The format command is used to display the amount in a "friendly" way to the end user
# By only making the first two digits after the decimal to display, instead of all of them
print("The sales commission is: ", format(commission, '.2f'))
again = input("Would you like to run another commission calculation?")
You’ll noticed in this example that we set up the continue variable before the loop. That’s because the while loop is a pretest loop. Meaning that it test the condition, and only runs the loop body if the condition is true. That also means that the loop body may never run.
Infinite Loops
Usually, an infinite loop is a bad thing. That means that the loop always runs, and never exits. There can be several reasons for this, a condition variable not being updated, a logic error in the condition itself.
Depending upon what the loop is doing, it could slow a machine, fill up hard drive space, eat up RAM, or any number of other things. Infinite loops should be avoided if possible.
For Loop
The for loop is a count controlled loop, or counter loop. That means it will run through a set number of values, like in an array, or for a set number of times.
The general form is:
for variable in [value1, value2, value3,...] :
loop statement
loop statement
...etc...
An example of this is in real life might be:
for num in [1,2,3,4,5] :
print (num)
for name in ['John', 'Sam', 'Jake', 'Sue'] :
print(name)
Of course, this works fine for a short set of numbers or names, however, if you had a long set of numbers, you wouldn’t want to write them out to a hundred. Instead, you can use the range function.
for num in range(5) :
print(num)
But what if you don’t want every number between, one and five, or you want to start at a different number, or skip numbers…
range(1,10,2) # count from 1 to 10, but skip every other number
Of course, you can type in hard coded numbers, or you can use a variable, so you pull numbers from an end user.
range(start, stop, increment)
Working with Loops in Python was originally found on Access 2 Learn