#๐Ÿ”’ for loops

30 messages ยท Page 1 of 1 (latest)

clever niche
#

need help understanding this course like idk what those numbers in parenthesis mean

weak fernBOT
#

@clever niche

Python help channel opened

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.

tacit sequoia
#

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

clever niche
#

o so range(2, 5) would be 2 3 4

tacit sequoia
#

yes

clever niche
#

ok and the letter i in that code is just a variable?

tacit sequoia
#

yes, thats what we call the iterator variable

tacit sequoia
#

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"

clever niche
#

ohhh ok

tacit sequoia
weak fernBOT
tacit sequoia
#

10 doesnt show up because its exclusive

clever niche
#

okkk wow thanks alot

tacit sequoia
#

np

native hawk
#

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.

earnest valve
#

!d slice.stop btw

weak fernBOT
earnest valve
#

er...

#

not a very helpful modal

#

!d range.stop

weak fernBOT
earnest valve
#

that's a bit better, but not much. It's "start, stop, step"

weak fernBOT
#
Python help channel closed

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.