Why having a syntaxless string or integer doesn't throw syntax error?
I honestly must be missing something.
So I have this nice syntax.
"Hello darling" #THIS!
print "Hello world!"
Why the hello darling doesn't throw syntax error. I mean, there's no print
statement. The "Hello world" just sits there. And from the syntax highlight, the hello world is a string, not a comment.
This also works.
7
print "8"
And 7 is obviously an integer. The 7 just sits there, not referenced to a variable, just there. "Syntaxless"
Question: Why it works? Both 7 and "Hello Darling" is integer and string, but not comment. I mean, if this is a comment, well it make senses since the interpreter ignores comment, but this is not.
That is because you are creating those strings or ints and then not assigning them to any variable so python simply discards them after creating them.
For example, when you have
a = 5
python creates the int 5 and then assigns it to the variable a
. However, if you just have
5
python creates the int 5 but then doesn't store it anywhere. The same goes for strings. Syntactically, it is valid. Semantically, it is a complete waste.
Hope that helps
您只创建了一个名为"Hello Darling"
的字符串,这是可以的(除非浪费),因为在执行打印命令"Hello World"
后会抛出该字符串。
Syntax errors are only raised if the code you are trying to run contains mistakes that mean the Python interpreter cannot know what code to run. Code that ends up discarding the result is not a syntax error.
In both your cases, you specified perfectly correct syntax. There are no errors in the lines. Python doesn't care if they don't do anything logical.
Both result in executable code, both result in an expression that produces an object (a str
or int
) that is then not used and end up being discarded again.
Note that Python has a specific use for just a string on a line, if it is at the start of a function, class or module. Then the string is used, it is assigned as the docstring:
def foo():
"I am a docstring"
return 'bar'
print foo.__doc__
# prints I am a docstring
In CPython (the reference Python implementation), literal expressions by their own on a line that are otherwise unused are simply optimised away. Your "Hello darling"
and 7
lines never make it into the compiled bytecode.
上一篇: F#中的协程