r/learnpython • • 11h 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

1 Upvotes

19 comments sorted by

9

u/This_Growth2898 10h ago

this code adds the digits

Numbers. Don't confuse them, it's important for programmers. The number 12 in decimal consists of two digits, 1 and 2.

Why does the total have to be 0?

Before you add anything to it, it's 0. In a loop, you accumulate the total value, adding 3, 5, and 4 to it; but there should be an initial value to add them to. Try removing the line total = 0 and you will get "name 'total' is not defined" because Python doesn't know how to add 5 to something that doesn't exist yet.

And why does it actually add the digits?

Again, it's number. Because

total = total + sensor_reading

line adds sensor_reading to total and assigns the result back to total, changing its value.

Also if I change the total or the less than to anything else it returns 0, or 18 usually. 

When you change the code, you get another code, maybe with a different behavior. Is this unexpected?

 I was informed that the directions in the book were incorrect. Is it a case of that here?

I don't know what your book says.

3

u/MezzoScettico 10h ago

Why does the total have to be 0?

The line "total = total + sensor_reading" means you're adding sensor_reading to whatever you previously had for "total".

Imagine going through the loop the first time, processing the first reading which is 3. You're going to add it to "total" to get the total so far.

It's pretty much the way you'd do it in your head. You keep a running total so far, and add each new number one at a time. The difference is that you would start with the 3 as your first running total, and then start adding with the 2nd number. But in the computer program, it's going to run into the line "total = total + sensor_reading" with the 3.

When you've only got one number, 3, what is the total so far? It's 3 obviously. So for total + 3 to give you the answer of 3, the value of "total" before you've added any numbers at all has to be 0.

And why does it actually add the digits?

All the digits up to the negative you mean. It does that because every digit got added to "total" by the line "total = total + sensor_reading". Let's trace the behavior.

Initial: total = 0.
sensor_reading = 3. Total = 0 + 3 = 3. 
sensor_reading = 5. Total = 3 + 5 = 8. 
sensor_reading = 4. Total = 8 + 4 = 12.

If you start with 0 and add 3, and add 5, and add 4, you're going to get the sum of 3 + 5 + 4.

Also if I change the total or the less than to anything else it returns 0, or 18 usually.

Change to what for example? I don't quite understand this..

1

u/SharkSymphony 6h ago

Why does the total have to be 0?

Because of this line: `total = total + sensor_reading`. In fact, just because of this expression: `total + sensor_reading`. For Python to be able to do this, it needs both of these variables to be defined. Try removing `total = 0` and observe what Python does the first time through the loop.

Why does it actually add the digits?

That same line. We take whatever value the `total` is, add a digit to it, and then store that updated value back in `total`. Super-common programming pattern.

1

u/scoberry5 5h ago

Also if I change the total or the less than to anything else it returns 0, or 18 usually.

Well, what you really mean is "If I change the instructions, it does exactly what I told it to do (even if I don't understand what I told it to do)."

So, for instance, if you change the less than to a greater than, it says "total is 0. Now go through all the sensor readings, starting with the first one. If it's greater than 0 (it is), then you're done with the loop. Now print out the total." So of course you'll get 0 -- that's what you told it to do.

If you change the total to start at something instead of 0, it'll add to that instead of adding to 0. So if you go back to the original code and start total at 6 instead of 0, you'll get 18 instead of 12. But if you start total at 1, you'll get 13, at 2 you'll get 14, etc.

1

u/ziggittaflamdigga 5h ago

sensor_readings = [ 3, 5, 4, -1, 6, 7]

This is the hard-coded readings from the “sensor”. In practice it may come from a file or as a function input.

total = 0

Initializes the variable to a reasonable number.

for sensor_reading in sensor_readings:

Iterates over the sensor_readings list. Will execute once for every item in the list and be available in the loop as sensor_reading.

if sensor_reading < 0:
break

If the sensor reading is less than 0 (assuming an error would report as negative on a real sensor and does not represent a valid reading) then it stops the loop before executing the remaining items. 6 and 7 will never be available in the loop as sensor_reading since it breaks on -1, and does not add -1 to the accumulated total.

total = total + sensor_reading

Accumulates the sensor reading if the break statement is not hit.

print("total is: " + str(total))

Prints the value of total.

1

u/notacanuckskibum 1h ago

Think of the line

Total = total + sensor_reading

As “take the value in total, add the sensor reading to it, then store the result back in total”

What’s the value of total the first time around the loop? If it wasn’t previously set to zero it could be anything , or it could give you an error. By setting it to zero before we start the loop we end up with the correct total

A human being might do it differently, skip the “total = 0” before the loop and inside the loop do

If this is the first time round the loop:

Total = sensor_value

Else

Total = total + sensor_value

Which would work, but isn’t a popular style in programming for several reasons, including that there is no obvious way to check if this is the first time round the loop.

•

u/cylonrobot 55m ago edited 2m ago

>Why does the total have to be 0?

Try deleting the line where you set the total to 0. Now run your script. You should get this error:

total = total + sensor_reading

^^^^^

NameError: name 'total' is not defined

IF you delete the line where total is set to 0, python will not know what you meant to do with the addition step later on. It doesn't know that you meant to add numbers, and it's trying to access a variable that doesn't exist.

By setting total=0, you're telling python, "ok dude, I'm going to use this variable called 'total'. It's going to be a number, and it's going to be a zero in the beginning."

Why zero? Because no addition has happened yet.

If you put the deleted line back, when python gets to the addition line, it knows that you mean addition of numbers.

A little experiment:

Try setting total to a non-numeric value

totals = "some text"

Then try running your code.

You should get this error:

total = total + sensor_reading

~~~~~~^~~~~~~~~~~~~~~~

TypeError: can only concatenate str (not "int") to str

1

u/Agawell 10h ago

Total = 0 initialises the variable with a value of 0 - so that when you add the numbers it’s the sum of the numbers

You could start with a different number for total but it wouldn’t make sense in this context and it would produce an incorrect value at the end

Then you loop through the numbers in the list, assigning each one in turn to the variable sensor_reading

If the number is less than 0 (ie the -1) then it exits the loop

The next line adds the valid number to the total, if the previous if statement was not triggered

Finally it prints the sum of the numbers up to the break

It’s not at all difficult to understand from the code - what exactly don’t you understand?

Are you having difficulty with the scope of the for and if statements? Indentation is the key here

Either get into the habit of adding more print statements so you can see what is going on or switch to using an ide with debugging built in so you can step through the code and understand it - pycharm works on all OSs and is free

1

u/Boothiepro 10h ago

The only idea that comes to my mind that could be wrong is using `continue` instead of `break` but that's a different idea and might not be taught yet and might not be what the code intends to do

1

u/CIS_Professor 7h ago

Why does the total have to be 0?

Because the variable, total, needs to exist before you can use it. And, because you are keeping a running total of the numbers being added together, you start with 0.

The right side of an assignment (that's anything with a single equal sign, =) 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

---

0

u/ducksauvage 11h ago

"total" acts an accumulator, a storage variable for your end result which is a sum of the first few readings. Before you've counted anything, it's 0.

You need to declare it before the for-loop, because "total" needs to exist to do "total = total + sensor_reading", otherwise you'll get an "undeclared variable exception".

As to your last question - nothing about this code seems wrong.

0

u/khludge 10h ago

"Total has to be zero" - you're setting total before the loop to ensure it's zero. It's not necessary in this case, but it's a good habit to get into as, in more complex cases, it will save you from a class of errors (eg assigning the wrong type of value to what you're expecting)

It adds the digits because of the line immediately after the if...break statement, which adds each digit from the list, in turn, to the running total - it executes that line every time around the loop unless the if condition us true.

How does it get each digit? That's what the for..in construct does - it pulls 1 value at a time from the list specified by the in part and assigns that value into the variable sensor-reading, for the duration of one loop (then next time around, the next value, ...)

When the loop gets as far as the -1 value, the if condition is true, so the break is triggered, which jumps execution to the first statement following the loop, skipping any statements (in this case, the running total) remaining between the break and the end of the loop

2

u/CIS_Professor 7h 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

0

u/Educational-Paper-75 10h ago

Your code adds all positive integers up until the first negative number in sensor_readings, keeping track of the sum of all sensor readings processed so far in variable total. In every execution of the body of the loop the value of total is updated by adding the current sensor_reading value to the sum computed so far correct. That's why total needs to be initialized to 0, otherwise total would not return the sum of all positive sensor readings before the first negative sensor readings when the loop finishes. Note that the first time a sensor reading is added total becomes just what it should be: the value of the first sensor reading. This is essentially how computers add a list of numbers: one at a time, and keeping track of the intermediate sum until all numbers are processed.

-1

u/Refwah 10h ago

If you didn’t initialise total as 0 then when you try and add a number to it you would get an error that you can’t add a number to ‘None’

-7

u/EnvironmentalDot9131 10h ago

You are using the wrong command 

2

u/SirGeremiah 9h ago

That is the vaguest possible reply, and seems incorrect, though it’s so vague we can’t even tell that.