Python #4: The “for” Loop

There’s another nice way to get the computer do do things a number of times: the “for” loop. This time, we get to specify exactly how many times we want the thing to happen. Try this little program:

The loop names a variable “i” and tells the computer to keep going, adding one each time, for ten repetitions. If you run the program, you’ll see it starts at zero and ends at nine. This is because the computer starts counting at zero. If we want to make it do one to ten we need to make a little change.

The  “range”  command lets us specify a start and end point, separated by commas. We can also tell the machine what steps to go in.

So, if I alter my program to this:

It will count down from 10 to 1 in steps of -1.

Simples!

antiloquax

Advertisements

Tags: , ,

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: