2
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?

4
  • 1
    Because the 2nd id doesn't have an underscore, so x doesn't get increased for it.
    – Robert
    Commented Apr 28, 2023 at 20:18
  • 1
    Why do you expect it print 2 2 3? If you change x = 0 to x = 1 it does print what you expect. Commented Apr 28, 2023 at 20:18
  • If you just want to output "2", remove the indentation on the final print() statement
    – moo
    Commented Apr 28, 2023 at 20:25
  • Note: id() is a built-in Python function. You are hiding it with a local variable of the same name here. Commented Apr 29, 2023 at 6:44

2 Answers 2

3

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.

0

Let's start by going trought the loop step by step:

  • x equals 0

  • Loop 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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.