#๐ for loops
30 messages ยท Page 1 of 1 (latest)
@clever niche
Remember to:
- Ask your Python question, not if you can ask or if there's an expert who can help.
- Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
- Explain what you expect to happen and what actually happens.
:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.
a range is, as advertised, a "range" of numbers. for example, the range of numbers from 1 to 10 is range(1, 11). The reason we write 1, 11 instead of 1, 10 in this case is because the second number is "exclusive." In other words, a range of range(a, b) has all numbers from a to b "except" b. So a range(1, 3) contains 1 and 2.
normally you see ranges with just one number, ie range(5). This just means the starting number is 0
in the case where you see 3 numbers, like range(a, b, c), it still means a range from a to b, but we instead "count by c".
to explain, a range(0, 11, 5) contains 0, 5 and 10
o so range(2, 5) would be 2 3 4
yes
ok and the letter i in that code is just a variable?
yes, thats what we call the iterator variable
wat if it was 0, 10, 5)
its defined in the for loop and represents the current thing you are looping over
if you do for i in x, on the first loop, i is the first element of x. in the second loop, its the second element. and so on
it doesnt to be i either, it can be anything. for exampls for element in x
and then your variable would be called "element"
ohhh ok
!e
for i in range(0, 10, 5):
print(i)
:white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | 0
002 | 5
10 doesnt show up because its exclusive
okkk wow thanks alot
np
To elaborate on Karma's "exclusive remark and demo", Python ranges are half open - includes the start, excludes the end. Also with indexing.
>>> s = 'abcdef'
>>> s[0:3]
'abc'
>>> s[3:6]
'def'
See that end end index of the first substring is the start index of the second substring? Using half open ranges lets us do this. If ranges included the end we'd be in a world of pain doing +1 and -1 kind of things at the boundary.
!d slice.stop btw
The value of the stop parameter
that's a bit better, but not much. It's "start, stop, step"
This help channel has been closed and it's no longer possible to send messages here. If your question wasn't answered, feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.