Question

If I write this below two statements in a file sample.py

radius = 10

2*radius

and interpret(>>>python -i sample.py),

Why doesn't python stop with error at second statement (2*radius) which looks syntactically/semantically wrong and probably requires LHS(name) to bind the RHS value?

I see that neither Java nor C allowed such statements which are of no use and this has nothing to do with compiled/interpreted version.

Was it helpful?

Solution

Python allows expressions on their own without their being part of a statement (assignment or otherwise).

If it didn't, then any in-place function or method call would require an assignment as well:

listobject.sort()  # this is nothing more than an expression

would have to be written as:

ignored = listobject.sort()  # assign None to ignored

Python cannot know that your expression has no effect on the rest of the code; radius could refer to an object with an .__rmul__ method, which would be called when Python executes your 2 * radius expression.

So, in the end, Python calculates 2 * 10 for you, discards the outcome, and moves on.

OTHER TIPS

Python doesn't mind discarding the result of evaluating the expression. In fact, a docstring is merely a literal string that happens to be the first statement in a function. Such a string has no practical effect on the execution of the program.

It doesn't stop because python has no problem with it. It simply calculates 2*radius and then does nothing with the result and moves on through the rest of the code. Needless I say, it is a completely useless statement unless you are actually assigning the result to some variable

Because Python is not Java or C++, it allows that kind of expressions, and it indeed calculates it:

>>> radius = 10
>>> 2*radius
 20
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top