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 salesperson should get. But it can just as easily calculate the sales bonuses for every salesperson in the organization.
Imagine 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 salesperson. It would be time consuming for you, and make it easy to make an error. Additionally, it might cause an issue as what happens if your company hires a new salesperson, 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 tests 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.
There are people, especially on the Internet, who will purposefully create an infinite loop.
while True :
# do something
Eventually, in the code, they will add a break statement if a condition is met. The issue is that this is bad logic. The while
loop has a condition, why not use that? See the issue with this problem.
Just like with a flowchart- you want a single entry point for your code, and a single exit point. This allows for multiple exit points, which can make debugging your code and finding logic errors very difficult. This is why I would never want to see this type of code, no matter how often you see people using it online.
Note: Often the people using it are relatively new at coding, and are sharing their wisdom without having experienced coding for truly large projects. This issue becomes, while it might be easy to do for a small project, and easy to maintain, as projects grow, minor problems like this can grow.
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 large 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)
In future languages, you will see that Python’s for loop behaves like a foreach
loop in many other languages. Python doesn’t have a standard for loop like you might see in languages such as Java, C/C++, JavaScript, PHP, and more.
Working with Loops in Python was originally found on Access 2 Learn