Please explain a for loop


#1



https://www.codecademy.com/courses/python-beginner-en-4XuFm/0/5?curriculum_id=4f89dab3d788890003000096


hi, I am at this exercise yet I am still confused about for loops. as in when you type for (something) in (something else). could someone kindly explain the use of for loops and how you use them. thank you


Replace this line with your code.


#2

Hi Hammaadkhan!
I would be heppy to explain a for loop as best I'm able!
Lets start with an example:

for letter in 'abcdefghijklmnopqrstuvwxyz':
  print letter

for number in range(11):
    print number

The above two For loops will result in every letter of the alphabet printed on its own line and every number 1 - 10 on its own line.

Lets break it down.
for obviouly tells the interpriter that you want to start a for loop.
letter Acts as a temporary variable for use in the for loop where each part of the object you are iterating is stored.
'abcdefghijklmnopqrstuvwxyz' is the object the for loop will be iterating through. This can be anything that iterable. Like a list, dictionary, tuple, range, or even a string like i've done here.

If I've lost you don't worry, the following is what made this really click for me.
This code:

for letter in 'abc':
  print letter

Is really just a simplified version of this code:

letter = 'a'
print letter
letter = 'b'
print letter
letter = 'c'
print letter

So you can really read a for loop in plain english like this
for each letter in string 'abcdefghijklmnopqrstuvwxyz':
Do the following code
print letter

We use loops in code so that we don't need to type the same line of code over and over again.
I hope this explanation helps you to understand for loops a bit better!
Let me know if I can help further!!
Joe


#3

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.