PDA

View Full Version : Trouble understanding for loops. (Python)



horizons187
February 2nd, 2013, 08:08 PM
So I understand that a for loop will do something for each something in a list but is the first variable you pick for the loop completely arbitrary? For example:



a = [1, 2, 3]
for i in a
print(i)


is the I completely arbitrary and made up? Meaning it could be any variable there?

Bachstelze
February 2nd, 2013, 08:14 PM
Any variable that is not already in use, yes.

lavinog
February 3rd, 2013, 05:08 AM
Don't forget you need a colon at the end of the for line:


a = [1, 2, 3]
for i in a:
print(i)


You can replace 'i' with any variable name you want.
You might see that i is used a lot in examples because it is common to use it to represent an index or iterator.

iMac71
February 3rd, 2013, 09:05 AM
Variable names should be sufficiently clear for allowing people, who read the source code, to understand the meaning (and consequentially the purpose) of each variable.
A single letter variable name may be used as index, e.g. in mathematics programs to indicate a specific element of a vector, but it is generally preferable to use longer variable names, for the reason above explained.
Each programming language has its own rules about variable names: for Python, you might read the PEP 8 (http://www.python.org/dev/peps/pep-0008/#naming-conventions)

greenpeace
February 3rd, 2013, 12:36 PM
is the I completely arbitrary and made up? Meaning it could be any variable there?

Yes, in the same way that assigning names for your variables at any point in your code is arbitrary.


a = 1
banana = 2
charles = 3

Just make sure it's clear to the person reading it (which could be you in 6 months time!) what it is used for. Programs full of a=1, tr=32, vfm=2 can be very difficult for someone else to follow.

AstroLlama
February 3rd, 2013, 02:54 PM
you could even use a word:

for item in list:
print(item)

horizons187
February 4th, 2013, 06:19 AM
Thank you all so much for the replies.