The For Loop in Python

Life is 10% what happens to us and 90% how we react to it. If you don't build your dream, someone else will hire you to help them build theirs.

The For Loop in Python

An important Python control structure to discuss, is the for loop, which will execute a suite of code for each element in some kind of sequence that the for loop is passed. So as we’ve seen with the ‘range’ function, in a previous chapter, it generates elements, like from zero through 4, if given a value, a single value, like 5. It’ll start at zero and go up to, but not including, that integer number. So executing a For loop, with each element in that range, it’ll print each element, in this case followed by a space, and we can see that it went and printed out zero through 4. And then this other print statement just causes the new line to occur for the next print that might be used.

 # The for loop executes a suite of code for each element 
 for elem in range(5):
   print(elem, end=' ') 
   print() 
 
 for elem in range(5, -1, -1):    
	print('Countdown:',elem) 
	
 for char in 'string':    
	print(char, end=' ') 
	print() 
	
 The output : 
 0 1 2 3 4 1 2 3 4 5 
 Countdown: 5 Countdown: 4 Countdown: 3 Countdown: 2 Countdown: 1 Countdown: 0 
 s t r I n g 1 3 5

In this For loop, we use a conditional ‘if’ to see if the key is equal to beta. If so, it will continue and go to the next element in that list of keys in this dictionary. The ‘continue’ will generally cause the For loop to go to the next element. So instead of going down to print out the key, and the dictionary’s value for that key, it simply continues when the key is ‘beta’. Otherwise, if the key is not ‘beta’, it’s going to be printing out what that key name is and then the value in the dictionary greek that’s associated with that key. So here we can see it printed out; ‘gamma’ and the value associated with that 3 and then ‘alpha’ and the value associated with that 1. It never did print out ‘beta’ because, at that time, it would continue past that element.

 greek = {'alpha': 1, 'beta': 2, 'gamma': 3} 
 for key in greek:    
	if key == 'beta':   
		continue
    print(key, greek[key]) 
   
   The output : gamma 3 alpha 1

It’s not uncommon to have nesting of loops, in this case, in the final example, we see a outer for loop that starts at 2, goes up to, but not including, 10, so essentially values 2 through 10. And then another for loop, for an inner or nested loop, that will start at the value 2 and go up to, but not including, what that outer value is.

 for outer in range(2,10):    
	for inner in range(2, outer):        
		if not outer % inner:            
			print(outer, '=', inner, '*', int(outer / inner))
			break    
		else:        
			print(outer, 'is prime')
 
 The output is:
2 is prime 3 is prime 4 = 2 * 2 5 is prime 6 = 2 * 3 7 is prime 8 = 2 * 4	 9 = 3 * 3

So through this example, I hope you can see how to use a for loop to either go through a loop a certain number of times, or start at and end at whatever values you may want even by using stepping, also how for loops are commonly used to iterate over or process, basically, each element that might be in some kind of sequence like a string, a tuple, a list. Or you could also consider the keys of a dictionary, a sequence that the for loop can iterate over. Like the other looping structure, ‘while’, we also do see that you can either continue to go back to the top of that for loop right away, or you can use break to exit that for loop before you’re finished with processing all the elements of it.