Answer the question
In order to leave comments, you need to log in
What are these expression statements?
In Python, expressions can also be used as statements (that is, on a separate line).
However, since the result of evaluating such expressions is not stored, it makes sense to use this feature only if the expression performs some useful side effect.
I understood it this way:
There is a simple expression - 2 + 2. It can be written on a separate line, but the result will not be saved, but we can assign the result to a variable. But then it would be an assignment instruction.
Answer the question
In order to leave comments, you need to log in
Of course, it makes no sense to write 2 + 2 without assignment in a separate line. The result will not be saved, and this expression does not create a side effect.
However, you could, in an expression, call some function with a side effect.
Strictly speaking, any function call in a block of code in python is such an expression if its result (and it always is) is not assigned.
You have to be careful with side effects. If you do something like this:
def my_global_effect_function():
my_global_list.append('anything')
return 3
my_global_list = []
my_global_effect_function() + 5
I had to read
it to the end .
In Python, expressions can also be used as statements (i.e., on their own line). However, since the result of evaluating such expressions is not stored, it makes sense to use this feature only if the expression performs some useful side effect. Expressions are commonly used as statements in two situations:
To call functions and methods
Some functions and methods do a lot of work without returning any value. In other programming languages, such functions are sometimes called procedures. Because they don't return values that might need to be stored, you can call these functions in expression statements.
To display values in an interactive shell
During an interactive session, the interpreter automatically displays the results of the expressions you enter. From a technical point of view, they are also expression statements and play the role of a shortened version of the print statement.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question