TRICKY QUESTION ~ help plz c:


#1

Whats the difference between a print and a return


#2

http://stackoverflow.com/questions/7664779/python-what-is-the-formal-difference-between-print-and-return
A simple Google search can work wonders.


#3

Yea, you're right, thanks, and that page is really helpful, too. Mind if I as you another question here? I want you to look over my code and explain why it is unacceptable :sweat_smile:


#4

okay so I'm just gonna ask anyway.

n = [3, 5, 7]

def total(numbers):
    result= 0
    for i in range(len(numbers)):
        result = result + numbers[i]
    return result

Whats the point of numbers[i] ?

I understand why range() is used ( to call the list)
I understand why len() is used ( for the indexes)
and obv the = and + signs, but why call the variable i ? ...is it for the loop? what would happen if the i was omitted?


#5

i signifies each element in the range (or loop, whatever you want to call it).
It takes each individual element one at a time (3, then 5, then 7) and adds it to result.
You use the syntax numbers[i] to go through each element, with i being its index.
If you omitted the i than Python would attempt to add the entire list to 0, which would result in an error.
You could alternatively use a for-in loop like this:

for i in range(len(numbers)):
#Replace Top With Below
for i in numbers:

Then you would just have to add i instead of numbers[i].
I prefer to use a for-in loop in this situation as it results in shorter and easier to understand code.

More on indices and for-in loops.