-
Notifications
You must be signed in to change notification settings - Fork 0
Programming Concepts 4: Loops
Loops make programming fun! Instead of tediously typing out a number of commands in sequence, you can write a loop that will execute the block of code it contains an arbitrary number of times. The two main loops used in programming are while and for loops. They act in a similar manner, but the way they are controlled differs slightly. Each loop is appropriate for different types of work.
while loops will execute a block of code if a conditional is true, and will continue to execute until the conditional is false. This can be thought of as a "conditional loop", an if statement that will continue to execute so long as the statement evaluates to true:
>>> i = 0
>>> while i < 10:
.... print('i: ' + str(i))
.... i += 1
i: 0
i: 1
i: 2
i: 3
i: 4
i: 5
i: 6
i: 7
i: 8
i: 9
>>> # Once i == 10, conditional is no longer true
>>> # Loop will not execute and program execution continuesA common design pattern is to set a boolean variable to control the loop. This is known as a "flag", and is set to true before the loop is executed to ensure the loop is run the first time. The body of the loop contains logic to set the flag to false if some condition is met. In this way the flag is switched, the loop is no longer executed, and we go on our way:
>>> flag = True
>>> while flag:
.... option = raw_input('Please select an option, or enter break to exit: ')
.... option = option.lower()
.... if option == 'foo':
.... # Do something here
.... elif option == 'bar':
.... # Do some other stuff here
.... elif option == 'break':
.... flag = False # Loop will not be executed again
.... else:
.... print('Enter a valid input')This can be useful for checking user input from the command line, to ensure a proper value is entered. For example, assume you have a prompt that asks the user to enter in a weekend day:
>>> weekends = ['saturday', 'sunday']
>>> day = raw_input('What day of the weekend works for you? ')
>>> while day.lower() not in weekends:
.... day = raw_input("That's not a day of the weekend. Try again: ") Be warned! Your while loop will continue as long as the conditional is true, so if the conditional is never evaluated to false the loop will never end, causing an infinite loop:
>>> while True: # Will never get set to False; infinite loop!
.... print("Help! I'm trapped in a while loop!")
Help! I'm trapped in a while loop!
Help! I'm trapped in a while loop!
Help! I'm trapped in a while loop!
Help! I'm trapped in a while loop!
Help! I'm trapped in a while loop!
Help! I'm trapped in a while loop!
Help! I'm trapped in a while loop!
Help! I'm trapped in a while loop!
Help! I'm trapped in a while loop!
Help! I'm trapped in a while loop!
Help! I'm trapped in a while loop!
Help! I'm trapped in a while loop!
Help! I'm trapped in a while loop!
Help! I'm trapped in a while loop!
Help! I'm trapped in a while loop!
Help! I'm trapped in a while loop!
Help! I'm trapped in a while loop!
Help! I'm trapped in a while loop!
Help! I'm trapped in a while loop!
Help! I'm trapped in a while loop!
Help! I'm trapped in a while loop!
Help! I'm trapped in a while loop!
Help! I'm trapped in a while loop!
Help! I'm trapped in a while loop!
Help! I'm trapped in a while loop!
Help! I'm trapped in a while loop!
Help! I'm trapped in a while loop!
Help! I'm trapped in a while loop!
Help! I'm trapped in a while loop!
Help! I'm trapped in a while loop!
Help! I'm trapped in a while loop!
Help! I'm trapped in a while loop!
Help! I'm trapped in a while loop!
Help! I'm trapped in a while loop!
Help! I'm trapped in a while loop!
Help! I'm trapped in a while loop!
Help! I'm trapped in a while loop!
# ...
# You get the ideafor loops also execute a block of code an arbitrary amount of times, but with a slight difference. These kinds of loops are given a range of values and loop over them. Each time the block executes, the next value in the range is used in the block. This process is known as "iteration", where you iterate over a range of elements:
>>> # `range` returns a list of numbers, which is what
>>> # we will iterate over. Like index splicing, we
>>> # pass it an inclusive start value and an exclusive
>>> # stop value
>>> for i in range(0, 10):
.... print(i)
0
1
2
3
4
5
6
7
8
9Many data structures in Python have built in iterators that allow you to loop over them. For example, to iterate over the contents of a list:
>>> names = ['Sarah', 'Abbie', 'Lisa', 'Jane']
>>> # The loop starts with the first element in the
>>> # list as the context variable `name`. On the next
>>> # iteration the next element from the list is used,
>>> # and so on...
>>> for name in names:
.... print('Hi ' + name + ' !')
Hi Sarah!
Hi Abbie!
Hi Lisa!
Hi Jane!