Sometimes it is a little confusing for me to keep in mind that the upperbound for a for loop is excluded by default. Is there any way to make it inclusive?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Yes,
for i in range(upper + 1)or if you like,for i in range(lower, upper + 1)will work,A lot of programming languages use zero-based indexing, so the non-inclusive upper bound is a common practice (this is due to memory addressing and adding an offset)
Just an example: If you had an array of size 5,
ar, starting with index 0, your largest valid index value would be 4 (i.e., 0, 1, 2, 3, 4), but your loop construct would refer to the size of the array (5) like so:for i in range(5):or more common and better:
for i in range(len(ar)):.. ensuring you only get legal index values 0 .. 4.