0

I don't know what 'Count : Count' does in my code. Below is the function that this is used in on line 4

I tried printing it but it gave me an error. CommandList is a string variable as well as Command.

def GetPositionOfCommand(CommandList, Command):
    Position = Count = 0
    while Count <= len(CommandList) - len(Command):
        if CommandList[Count:Count + len(Command)] == Command:
            return Position
        elif CommandList[Count] == ",":
            Position += 1
        Count += 1
    return Position

Position = GetPositionOfCommand(Items[IndexOfItem].Commands, "get")
Rory Daulton
  • 21,934
  • 6
  • 42
  • 50
Anas
  • 3
  • 1
  • This is a syntax for Python's list slicing. Refer [linked answer](https://stackoverflow.com/questions/509211/understanding-pythons-slice-notation) to understand more about it. – Moinuddin Quadri Jan 01 '19 at 23:19
  • It seems to me that this question is not a duplicate. The OP is not quite confused by the slice, but rather by the incorrect grouping of items within the bracket. He or she thinks `Count:Count` is a separate expression. Therefore I answered the question. – Rory Daulton Jan 01 '19 at 23:23
  • Thank you, Mr Daulton. I understand it now. – Anas Jan 02 '19 at 11:45

1 Answers1

1

Your question is off, since Count: Count does nothing in the code you show. Rather, what acts is Count:Count + len(Command). That would be better written as Count: (Count+len(Command)).

Both CommandList and Command are strings or lists or similar data types (I'll say strings hereafter), while Count is an integer. In particular, Count is an index into CommandList.

The expression CommandList[Count:Count + len(Command)] is a slice of CommandList. In other words, that expression is a sub-string of the string CommandList. That sub-string begins at the index position held in Count and stops just before the index position Count + len(Command). That sub-string has the same length that the string Command has.

Therefore the entire line

if CommandList[Count:Count + len(Command)] == Command:

checks if the sub-string pointed to by variable Count is equal to the string Command. If the sub-string and the string are equal, the next line executes, namely the return statement.

Is that clear? Read up more on Python's slices--the link I gave you is a good start. Slices are just one reason Python handles lists and strings so much better than most other languages. The code is written a little confusingly, so it looks like Count:Count is an expression in itself. The code should have used different spacing and perhaps parentheses to show that the inner expression is Count + len(Command) and the colon is used after that. Order of operations shows itself again!

Rory Daulton
  • 21,934
  • 6
  • 42
  • 50