Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
215 views
in Technique[技术] by (71.8m points)

Basic Python loop

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

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

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...