Python For Loops


So, working on learning Python, I’ll be blogging short bits of code and tutorials to help hone my own understanding- and hopefully someone out there will find it helpful.

So, a for loop is used in Python for iterating over a container, and for other loops where you can easily know ahead of time how many times you need to loop.

In the first case, for iterating over a container, here’s how you do it.

for x in container:
    print(x)</pre>

This loop will print each item in container, one after another, each on their own lines.  Whereas simply using print(x) will print the entire container in one line(wrapped in the REPL).

Now, let’s say you need to do something x number of times.  You could create a container with the necessary values, but Python provides the range() function to handle this.

The simple case is start from zero, go up by 1, last iteration is 1 less than your limit.

for x in range(10):
    print(x)</pre>

This will print the digits 0-9.

Range can do more, of course, giving you a great deal of flexibility with your loop.

#Basic format.  start defaults to zero,
#step size to +1.  end is not included
#in the range, start is.
range(start, end, step_size)

#5-9
for x in range(5,10):
    print(x)

#Step size
for x in range(5,10,3):
    print(x)  # Will print 5 and 8

#You can go backwards!
for x in range(10, 5, -1):
    print(x) #10,9,8,7,6

So, that’s it for Python for loops. Of course, using them effectively can be much more complicated than the basic syntax would make it look, but you can work that out on your own.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: