for i in range(5):
print(i, end=' ')
What does "for i in range" mean in Python?
python
for i in range(5, 0, -1):
for j in range(1, i + 1):
print(j, end="")
print()
python range and for loop understanding - Stack Overflow
So, I had a question where I was supposed to find the sum of the first natural numbers using Python.
Here's the problem:
Write a program to find the sum of the cubes of the first n natural numbers, where the value of n is provided by the user.
And this is the code that my professor used to allow the interpreter to produce the result:
= int(input("Enter a number:"))
sum = 0
for i in range (n+1): sum = sum + i*i*i
# for i in range starts as a loop, and then tries to get to (n + 1), whatever that may be
print("the sum of the first", n, "integers is", sum)
However, I can't seem to understand what "for i in range (n + 1): sum = sum + i * i * i" means. In other words, I don't understand what role this part of the code is doing to produce the result. Especially, I don't understand what the role of "for i in range (n + 1)" is doing. Does anyone mind explaining this to me?
When you call range() with two arguments, the first argument is the starting number, and the second argument is the end (non-inclusive). So you're starting from len(list_of_numbers), which is 5, and you're ending at 6. So it just prints 5.
To get the results you want, the starting number should be 0, and the end should be len(list_of_numbers)+1. If you call it with one argument, that's the end, and 0 is the default start. So use
for i in range(len(list_of_numbers)+1):
or if you want to pass the start explicitly:
for i in range(0, len(list_of_numbers)+1):
range gives you and iterator between (start, end) end not included.
So in your case the iterator is (start=len(list_of_numbers), end=6).
Since len(list_of_numbers) = 5, this translates to range(5,6) which is 1 element, 5, since 6 is excluded.
https://docs.python.org/3/library/functions.html#func-range