Reputation: 155
I cannot follow this code, and was hoping someone can explain it to me
def negative(temperatures):
days = 0
for t in temperatures:
if t < 0:
days += 1
return days
Can someone please explain line 5?
So from what I understand the function scans for negative temperatures in the array 'temperatures
', assigns the first index that is <0
to t
, and then line 5 takes days
, which = 0
, and then adds 1
to it, why does this equal one?
Upvotes: 1
Views: 336
Reputation: 7206
Notionally a += b "adds" b to a,storing the result in a.
Syntax:
A += B
A: Any valid object.
B: Any valid object.
Equivalent to A = A + B.
days += 1
is the same as
days = days + 1
Note:
you are using here variable days like "counter" (you are counting how much days had temterature <0)
you have list of temperatures ,probably something like : temperatures = [3,18,-2,4,-6]
you are passing over all items in your list temperatures:
for t in temperatures:
you are checking every item if its less than 0:
if t < 0:
if temperature is negative: variable days(started from 0) will increase for 1
for exemple: in first step days = 0
days = days + 1 -> 0+1 = 1
in next step days = 1
days = days + 1 -> 1+1 = 2
in next step days = 2
days = days + 1 -> 2+1 = 3
NOTE : difference between = and ==
OPERATOR = Assign value of right side of expression to left side operand, its not relational operators which compare if both operands are equal, that is ==
example:
myNumber = 5
This assigns 5 to variable myNumber.
if (myNumber == 5):
print(myNumber)
This tests for equality. The two use are not interchangeable.
Upvotes: 3