While Loops vs. For Loops

I’m still half forgetting the difference between while loops and for loops most of the time (and when to use each one), while working in both my Codecademy JavaScript course and my Udacity Introduction to Computer Programming course. Since I’m starting the while loops section on Codecademy now, might as well hammer out the difference once and for all, so I don’t have to keep leafing through my notes.

According to Codecademy introduction to while loops: “‘While’ loops are like ‘for’ loops, only they don’t need a counter—they continue to run until their condition is met.”

Mathbits.com (forgiving its goofy notebook-in-space motif) also offers a clear differentiation:

  • while loops must repeat until a certain condition is met
  • for loops are repeated for a specific number of times

With these in mind, here’s a reminder example I’ve made myself to make the purpose of each stick in my head:

  • Ke$hify For Loop: For length of ‘Kesha’, replace ‘s’ with $
  • Gaga While Loop: While naming songs, if “Gaga” is artist, add song to playlist

One thought on “While Loops vs. For Loops

  1. a while loop is a simple loop: you can just use while 1: and keep going until you break out with ctrl-c or the break command. you can also use a condition.

    a for loop “loops through” something: a range of numbers, the characters in a string, or the items in an array (or the lines of a file.)

    i like your ke$ha/gaga analogy.

    by the way, i find it too tedious to use a condition with while. i *always* use while 1, it is easier to break when youre done with it.

    this makes is easy to remember: you can break out of while loops and out of for loops: but apart from that “while 1” keeps going and “for 1” stops right there. even though its really for x in range(1)

    Liked by 1 person

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