DEV Community

Discussion on: Why does the # in print(" This is a # hash") not get ignored by interpreter in Python ?

Collapse
dusekdan profile image
Daniel Dušek

Because python interpretter does something called tokenization prior to interpretting. It basically goes character by character and decides in what context it currently is. To better explain let's consider print("#").

In the first step, the interpretter reads 'p' and realizes that it can be one of X contexts. A variable context, constant context, function call context, and maybe some other contexts as well. It goes on and reads the rest of the characters up to the point it finds an opening bracket '('. In that moment it realizes it's a function call context.

It knows that in function call context it can expect some operands/parameters. These can be again a variable, a literal or another function call. Literals are typically implied by what they are (a number) or by double quotes. By the double quotes, it figures that the parameter will be a string literal. And string literal can contain almost any characters, including the pound sign (#). So it treats it as such and won't start a comment.

Does that make sense or should I explain better?

Collapse
ddsry21 profile image
DDSRY Author

Thanks