What do I add to result if using the range( ) method?
Answer
If you chose to write your loop with the range() method, you’ll need to access your list items with the current number in your range. In the code below, i holds the value of the current range value for our loop and we use that to access an index in our list.
for i in range(len(some_list)):
print i # This will print a number, starting at 0, going up to the list length
result += some_list[i] # Access the current value in our list
Would it be correct to say that ‘for i in range(0, len(some_list):’, the i refers to each index. So you have to then use it in conjunction with the list to retrieve the value. And that the ‘for i in some_list:’ the i refers to the value itself?
@danyala Yes, that’s correct. You can test it yourself by running these in your Python interpreter:
example_list = ['foo', 'bar', 'baz']
# len(example_list) returns the number 3
# so range(3) would produce the same result
for i in range(len(example_list)):
print(i)
# output:
0
1
2
example_list = ['foo', 'bar', 'baz']
for i in example_list:
print(i)
# output:
foo
bar
baz
Guys, just would like to know the last line in the code about printing is it right or not?
n = [3, 5, 7]
def total(numbers): #function
result = 0 #variable
for i in range(len(numbers)): #for i or any other name in range(len(of the argument that is in the function))
result += numbers[i] #whenever it tells you add the amount to the result then this is the way, after the result was 0, now it is result = result + numbers from the argument(note that this is the second time to be used) and since we are dealing with a list then numbers[i] or any name we choose.
return result
print total[n]
Do you have a specific question related to your code? We should refrain from posting full solutions or working code on the forums without questions associated with the code.