Python Loop – Simple Examples to Learn

A Python loop is what you can use to make computers do repeated processes that humans would quickly grow tired of. However, computers do not grow tired of repeated processes.

Python Loop
A Python loop can be used to repeat a process many times.

A Python loop usually will contain an iteration variable. This variable will change each time it goes through the loop.

Avoid an infinite loop, because those cause the CPU to crash. The iteration variable controls how many times the Python loop will run.

Beware the Infinite Python Loop

Below is an example of an infinite loop. You can see the error in logic that would cause the loop to never stop.

x = 3
while x > 0:
++++x = x + 1
++++print ‘I am going to crash!’

 

If you started the value of x at zero or below, then the above Python loop would never run. That would be called a zero trip loop.

How to ‘Break’ the Loop

Another way to force out of a loop is to use the Python reserved word ‘break’. Look at the example below of how this can be used. The loop will stop when the user enters ‘done’.

A Python loop with break.
User input ‘done’ will cause the loop to stop.

Skip and Continue

Another useful statement for a Python loop is ‘continue’. The continue statement stops the current iteration and jumps to the top of the loop for the next iteration. Thus, ‘continue’ does not stop a loop, it just allows you to skip certain iterations.

while True:
++++word = raw_input(‘ ‘)
++++if word == ‘skip’:
++++++++continue
++++if word == ‘done’:
++++++++break
++++print word
print ‘Done!’

 

The above example demonstrates a Python loop that will skip an iteration if the user enters the word ‘skip’.

From the Indefinite to the Definite Python Loop

These examples thus far of ‘while’ loops are often called indefinite loops. They will run until a logical condition becomes false. The examples here have been simple, but with more complex code comes the need for extra precaution. At some point the condition must become false, or else the loop will be infinite.

A definite loop is a type of loop that will iterate a finite number of times. The Python reserved word used to construct an infinite loop is ‘for’.

Python For Loop
Another Screenshot from Dr. Chuck’s Python Course at Coursera

A for loop does not just have to iterate through a set of numbers. It can iterate through a set of strings as well.

cities = [‘Los Angeles’, ‘Dallas’, ‘New York’, ‘Rome’] for city in cities:
++++print city, “is a famous city.”

 

A for Python loop takes on the responsiblity of advancing the iteration variable. In essence, the iteration variable moves through all the values in the sequence.

Give Your Loop Intelligence

Loop idioms are how you construct a loop. The idea is to give the loop intelligence. Start by knowing what the Python loop wants, and then approach that by writing one line of code at a time. Think of this process in three steps.

  1. Set some variables for the loop.
  2. Do something to each variable.
  3. Return a result.

Imagine you have a list of 100,000 numbers, and you need to find the largest number. The example below demonstrates with a small set of numbers, but the same loop would apply no matter the size of the number set.

Find the Largest Value Loop
A Python loop for finding the largest value from a list.

Finding the average of a list of numbers is a classic programming problem. To accomplish this, you need to introduce a count variable. The count variable will keep track of the amount of members in a set. Look at the following example.

count = 0
sum = 0
set = [89, 78, 90, 87, 94] for value in set:
++++sum = sum + value
++++count = count + 1
print ‘The average is’, sum / count

 

Use a conditional if statement within a Python loop to filter values. For example:

for value in [89, 78, 90, 87, 94]:
++++if value >= 90:
++++++++print value, “is one of your best grades!”
print “Good Job!”

 

You can also search using a Boolean variable.

A_grade = False
for value in [89, 78, 90, 87, 94]:
++++if value >= 90:
++++++++A_grade = True
++++++++print “You got an A!”
++++++++break

 

In the above example, the condition will change to true on the third iteration. The break statement will then prematurely stop iterating through the list.

It is easy to see that a loop could be integral to many types of Python functions.

Do you have what it takes to learn Python? Boost your career potential, and get on the Python specialization track at Coursera. Financial aid may be available to those who qualify.

 

Leave a Reply

Your email address will not be published. Required fields are marked *