Very basic question regarding spaces within a line of code

Hello all,

Thanks for taking the time to answer this really basic question. I’ve been learning Python as my first language (except for a Visual Basic course I took at community college years ago) and often throughout my learning there will be spaces that seem extra. In other words, when I don’t use them the code still runs just fine.

I know that tabs/spaces are important when indenting, but how about a basic declaration of a variable etc…? See the below example which works just fine with or without the extra spaces.

wait_time = random.randint(1, 60)


As you say, leading tabs or spaces at the beginning of a line are used for indentation, which is important.

Otherwise, spaces are nearly always optional. (But strongly recommended.) The only place I can think of where they are not optional is between words:

importmath  # no, must be `import math`

foritemincollection:  # no, must be `for item in collection:`

Apart from that, breaking symbols up with spaces is done to make it easy for humans to read. The interpreter doesn’t care.

Thank you!

You might also want to consult PEP 8, which not only describes the “standard” Pythonic code style, but also goes into some detail into the reasons behind many of the guidelines

Sure, to the interpreter, it may (usually) mean the same thing, but following a consistent, readable, and conventional style will ensure others (or, quite often weeks, months or years down the line, you) can more easily understand your code, which is often just as important.

As a new user to Python, I recommend you spend as little time worrying about stylistic formatting as possible, and instead focus on running correct code. In conjunction, I recommend you use a formatting tool like black to take care of that, running it once per day or before Git pushes

1 Like