6 Antworten
+ 7
There's more to it than meets the eye (pun intended)
In a more traditional language you might have pseudo code like this.
letters = ['a', 'b', 'c'];
Int count;
chr tempVar;
for (count = 0; count <len(letters) ; count++) {
tempVar = letters[count];
printf(tempVar);
}
Python is doing all of this in the background
if in Python you say
for this in that:
It returns each element in that as the temp variable this.
So to make your prog more readable you would say
for letter in letters:
i is just the name of the temp variable, it could be any allowable word.
+ 9
First know that this can be x,y,z or anything like we love to use variable x in mathematics. So, first we replace i/I to another variable.
Letters = ['a','b','c']
"""Here we declared a variable Letters which inherits a list and the list have 3 elements"""
for z in letters:
print(z)
"""This is iteration. Means for every element in Letters, print that element"""
So, then we get the elements one by one in the output.
Note that your code will get a ValueError because you did not declared a, b, c as strings.
write, Letters = ['a','b','c'] for instance.
+ 5
The for loop loops over an iterable, anything that has more than one element, like a list, tuple, string...
for l in letters:
print(l)
This means that l successively becomes each letter from letters.
This is the same as if you wrote:
l = letters[0]
print(l)
l = letters[1]
print(l)
l = letters[2]
print(l)
For more details, you can also look here:
https://code.sololearn.com/cSdiWZr4Cdp7/?ref=app
+ 2
You may find answer in https://docs.python.org/2.3/whatsnew/section-slices.html
+ 1
The i is normally used as iterator on a for sentence. That is why it is called i.
For example:
for i in range(5):
print(i)
Here the i is first 1, then 2, 3, and 4.
letters=[“a”,”b”,”c”,”d”]
for i in letters:
print(i)
Here, the i would be a, then b, c and d
0
letters=["a","b","c"] # you have entered three letters in a list data type
for l in letters: # {l} will take the value from letters firstly it will take [a] then [b] and then [c]
print(l) # print one by one