问题描述:
ids = ["XF345_89", "XER76849", "XA454_55"]
x = 0
for id in ids:
if '_' in id:
x = x + 1
print(x)
This was from a coding exercise on a Udemy video I am learning Python from. Obviously the intended output is just ‘2’ and you do this by unindenting the print function, but just curious why the incorrect answer is the way it is?
解决方案 1:[1]
I do not see anything wrong. It should definitely print (note: not “returning”) 1, 1, 2.
It goes through your list:
["XF345_89", "XER76849", "XA454_55"]
x
becomes 1 after visiting item 0 ("XF345_89"
);x
is still 1 after visiting item 1 ("XER76849"
), because it does not have a _
;x
becomes 2 after visiting item 2 ("XA454_55"
).
Because you print x
after visiting the item whether changing happened or not, so it prints 1, 1, 2.
解决方案 2:[2]
Let’s start by going trought the loop step by step:
-x equals 0;
-Loops starts;
-“XF345_89” contains a ‘_’, x now equals to 1;
-“XER76849” doesn’t contain a ‘_’, x still equals to 1;
-“XA454_55” contains a ‘_’, x now equals to 2.
Result: x = 2
As you can see, this is the only logical solution from the code you provided.
Maybe you want x to start from one?
If yes, changing x from 0 to 1 should solve the issue, the example sets x to 0 probably because numbers normally start from 0 in programming like in arrays.
ids = ["XF345_89", "XER76849", "XA454_55"]
x = 1
for id in ids:
if '_' in id:
x = x + 2
print(x)
# Outputs 2,2,3
If this wasn’t the issue, please let me know.
参考链接:
Copyright Notice: This article follows StackOverflow’s copyright notice requirements and is licensed under CC BY-SA 3.0.
Article Source: StackOverflow
[1] charlesz
[2] vitopigno