While working on a Python project, I realized that during my editing I had left a string floating around in the middle of my code and it didn’t generate an error. For example, these few lines execute just fine:
print("Starting")
"This string does nothing"
["Neither does", "this list"]
print("Done")
Output:
Starting
Done
It seems to me that since there are no statements or function calls, those should generate syntax errors. Why is there no exception raised, and is there some use for a construct like this?
4
It’s an expression statement. In the REPL, the repr
of the result of an expression statement is printed if it’s not None
. You use this type of statement all the time when calling functions:
f(x)
It’s just that those functions typically have side effects, whereas literals do not. This is a common syntactic feature of imperative languages with a statement–expression distinction.
1