Saturday, July 11, 2015

"for" loops

"for" loops in Python iterate over a given range. You can iterate through a string, list, dictionary, or over a range of values. Here is an example of each.

Iterating through values:
for i in range(10):
    print i
What would you expect the output to be? The output would be the numbers 0 through 9, each on a separate line. Why 0 through 9 and not 1 through 10? Well most programming languages start counting at 0. If you had an array that held 4 values called nums then nums[0] would be the first value and nums[3] would hold the last value. This is an important concept in programming and can cause bugs and other issues if not addressed properly in your code. With a little practice you will be able to grasp this way of thinking fairly quickly. If you did want to iterate from 1 to 10 your for statement would be "for i in range(1,11):"

Iterating through a string:
for letter in "Python is cool":
    print letter
This is a great way to break down strings in to individual characters. It will start with the first and end with the last. Open your compiler and experiment with using for loops this way. Once you get the hang of it you will find it really is handy for dealing with strings.

Iterating through a list:

cards = ["ACE", "QUEEN", "KING", "JACK"]

for card in cards:
    print "The card is: " + card


As you can see the for loop is a powerful way to execute a block of code several times. Next we will learn how "while" and "do" loops work in Python. Stay tuned!

No comments:

Post a Comment