Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

How does Python know what "i" is when it is not defined, shouldn't there be an error? Probably a simple explanation, but I am new to learning Python.

def doubles (sum):
    return sum * 2
myNum = 2
for i in range (0,3):
    myNum = doubles(myNum)
    print (myNum)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
214 views
Welcome To Ask or Share your Answers For Others

1 Answer

Haha :-) People are marking down your question, but I know that is one question must have came in every person's mind. Specially those who learned Python through Online courses and not through a teacher in person.

Well let me explain that in layman's term,

The method that you used is specially used for 1) lists and 2) lists within lists. For eg,

example1= ['a','b','c'] # This is a simple list
example2 = [['a','b','c'],['a','b','c'],['a','b','c']] # This is list within lists.

Now, 'a','b' & 'c' are items in list.

So by saying,

for i in example1:
    print i

we are actually saying,

for item in the list(example1):
    print item

-------------------------

People use 'i', probably taken as abbreviation to item, or something else. I don't know the history.

But, the fact is that, we can use anything instead or 'i' and Python will still consider it as an item in list.

Let me give you examples again. example1= ['a','b','c'] # This is a simple list example2 = [['a','b','c'],['a','b','c'],['a','b','c']] # This is list within lists.

for i in example1:
    print i

[out]: a
       b
       c

now in example2, items are lists within lists. --- also, now i will use the word 'item' instead of 'i' --- the results regardless would be the same for both.

for item in example2:
    print item

[out]: ['a','b','c']
       ['a','b','c']
       ['a','b','c']

people also use singulars and plurals to remember things, so lets we have a list of alphabet.

letters=['a','b','c','d']
for letter in letters:
    print letter

[out]: a
       b
       c
       d

Hope that helps. There is much more to explain. Keep researching and keep learning.

Regards, Md. Mohsin


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...