r/learnpython • u/Plane-Art-9868 • 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
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
totalbefore reassigning it back intototal.totalmust 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.
If
totaldidn't exist before doing that (if there was nototal = 0), the program will crash.---
I get what you're saying, but Python isn't a typed language. If I did this:
total = 0and 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: