What is the difference?

Hello there, I am new at python programming and while I was doing some practice I came across an error and could not figure out what is wrong? It might be a simple reason but as I mentioned that I am a beginner. Hope you guys help me.
Thank in advance.

The problem is script 1 is not working while script 2 is working properly. What is the reason of that? Seems like script 1 is sensible too but not working.

Script 1:

sum = 0
while True:
x = input()
sum = sum + int(x)
if x == ‘stop’:
break
print(sum)

Script 2:

sum = 0
while True:
x = input()
if x == ‘stop’:
break
else:
sum = sum + int(x)
print(sum)

Hi NaciMaci,

The difference is the order that you do the operations.

The second code checks if the user input is “stop” first. If it is the
word “stop”, it breaks out of the loop. Only if the word isn’t “stop”
does the code convert the string into an int.

The first code checks if the user input is “stop” second, after trying
to convert it to an int. So you try to convert the word “stop” into an
int, which of course is not possible and you get an error.

To give you an analogy, it is somewhat similiar to these two situations:

Case 1 (doesn’t work)

  1. buy a turkey
  2. roast the turkey until done
  3. turn the oven on

Case 2 (does work)

  1. buy a turkey
  2. turn the oven on first
  3. roast the turkey

Just as with cooking, in programming the order that you do things
matters.

1 Like