Haaalp! I know C, C#, Java, BASIC, and Assembly and Python is breaking my head!

A regular for loop would look something like this

for i in range(n): # you can also use xrange(n)
    $ do stuff

The range method can take in 3 arguments. Start, Stop and Step. (range(start, stop, step)) You do not have to If the start argument is omitted it will default to 0, and if the step argument is omitted it will default to 1, but you always need to give a stop value.

Also remember that the range method creates a list that goes up to but not including the stop argument. So range(4) would be [0,1,2,3]

You can iterate through pretty much anything. Examples:

#strings
for i in "Hello World":
    print i, # if you add a comma at the end of a print it won't make a new line
>>> H e l l o  W o r l d

(I will use triple arrows to show what it outputs)

Another example would be arrays:

list = [1,1,2,3,5,8]
for numbers in list:
    print numbers, 
>>> 1 1 2 3 5 8

Dictionaries (map)

d = {'a': 'apple', 'b': 'berry', 'c': 'cherry'}
for key in d:
    print key, d[key]
>>> a apple
>>> c cherry
>>> b berry

You can also use multiple variables like this

choices = ['pizza', 'pasta', 'salad', 'nachos']

print 'Your choices are:'
for index, item in enumerate(choices):
    print index+1, item
>>> 1 pizza
>>> 2 pasta
>>> 3 salad
>>> 4 nachos

The cool thing is that you can use for / else loops. The else statement is executed after the for, but only if the for ends normally—that is, not with a break.

fruits = ['banana', 'apple', 'orange', 'tomato', 'pear', 'grape']

print 'You have...'
for f in fruits:
    if f == 'tomato':
        print 'A tomato is not a fruit!' # (It actually is.)
        break
    print 'A', f
else:
    print 'A fine selection of fruits!'

This code will break when it hits 'tomato', so the else block won't be executed.

/r/learnpython Thread