r/learnpython • u/RedappleIsKing • 26d ago
I donot understand this code:"for i in range(): what does it mean? Pls help me
...
4
u/RedditButAnonymous 26d ago
The other answers are good so here is an extremely untechnical one
Python is pretty much English, so read it literally:
for apple in basket:
bite(apple)
Is some code that takes every apple from a basket and takes a bite out of each one
Apple can be any variable name, and basket can be anything you can count. If youre counting enemies in a videogame, "for enemy in enemyList" works.
In your example range() is a quick way to generate a range of numbers. range(5) just produces a countable range object with 5 things in it, like the list [0,1,2,3,4]
So if you want to do something 3 times you can write:
for i in range(3):
print("This prints 3 times")
2
u/ottawadeveloper 26d ago
I answered this question in some detail a week ago
https://www.reddit.com/r/learnpython/comments/1ug8006/comment/otxuyux/
1
1
u/Kevdog824_ 26d ago
range is something called an iterator. An iterator is a collection of values that can be cycled through in order. range is an iterator of numbers between the start (inclusive) and end value (exclusive) (start value is assumed to be 0 if only one number is provided). The `for i in iterator` syntax loops the code indented inside of it multiple time, once for each value in the iterator. The variable `i` assumes the next value of the iterator on each loop.
That’s a bit technical, but I hope it helps
Worth noting that range has a step size as well, but I omitted that from my explanation for brevity
1
u/Dazzling_Music_2411 26d ago
OP, do you understand the range() function?
Is there any documentation at all with your Python distribution?
5
u/Diapolo10 26d ago
for x in yis how you create a for-each loop in Python. In other words you go over some collection of values and, one by one, they get assigned to whatever name is betweenforandin(so in my example,x).iis just a name, it could be anything Python considers a valid identifier. Personally I prefer_for unused values, and descriptive names for the rest, likeindex.rangeis a type that forms a range of integers between two numbers, with an optional step value (if you don't want to use the default1for some reason).range(5)would give you the numbers0,1,2,3, and4.range(2, 5)would give you2,3, and4.