r/learnpython • • 5d ago

I'm confused by the escape loop

Hi, I've just got to the escape loop part of my learning, I have wrote my code following the books directions. Here it is:

sensor_readings = [ 3, 5, 4, -1, 6, 7]
total = 0
for sensor_reading in sensor_readings:
    if sensor_reading < 0:
        break
    total = total + sensor_reading
print("total is: " + str(total))

Now as far as I understand, this code adds the digits up until the negative, which in this case is 12. Why does the total have to be 0? And why does it actually add the digits? Also if I change the total or the less than to anything else it returns 0, or 18 usually. I get the break part, but I don't understand the code leading up to it. I posted a while ago about another section, and I was informed that the directions in the book were incorrect. Is it a case of that here? Thanks

3 Upvotes

19 comments sorted by

View all comments

Show parent comment

3

u/CIS_Professor 4d ago

It is necessary in this case because he's trying to do something with total before reassigning it back into total. total must exist before using it.

The right side of an assignment is always evaluated first, with the result then assigned to the variable on the left.

total = total + sensor_reading

If total didn't exist before doing that (if there was no total = 0), the program will crash.

Traceback (most recent call last):
  File "f:\papabear11\desktop\NEW\test.py", line 8, in <module>
    total = total + sensor_reading
            ^^^^^
NameError: name 'total' is not defined

---

it will save you from a class of errors (eg assigning the wrong type of value to what you're expecting)

I get what you're saying, but Python isn't a typed language. If I did this:

total = 0

and then did this:

total = 'a'

That might be in error - a logic error - but Python will not throw an exception . . . at least not until you tried something like this:

total = 'a'
total = total + sensor_reading    # where sensor_reading is an int