what is an expression and a statement in python?
Answers
Explanation:
Here’s a general rule of thumb: If you can print it, or assign it to a variable, it’s an expression. If you can’t, it’s a statement.
Here are some examples of expressions:
2 + 2
3 * 7
1 + 2 + 3 * (8 ** 9) - sqrt(4.0)
min(2, 22)
max(3, 94)
round(81.5)
"foo"
"bar"
"foo" + "bar"
None
True
False
2
3
4.0
All of the above can be printed or assigned to a variable.
Here are some examples of statements:
if CONDITION:
elif CONDITION:
else:
for VARIABLE in SEQUENCE:
while CONDITION:
try:
except EXCEPTION as e:
class MYCLASS:
def MYFUNCTION():
return SOMETHING
raise SOMETHING
with SOMETHING:
None of the above constructs can be assigned to a variable. They are syntactic elements that serve a purpose, but do not themselves have any intrinsic “value”. In other words, these constructs don’t “evaluate” to anything. Trying to do any of the following, for example, would be absurd, and simply wouldn’t work:
x = if CONDITION:
y = while CONDITION:
z = return 42
foo = for i in range(10):
Now as for your mentioning of print in Python… it varies. In Python 2, print is a statement, which means it is a single command that does not “evaluate” to anything, and therefore cannot be assigned to a variable. However, in Python 3, print is a function, which is a specific kind of expression.
“But wait!” you object. “If print is an expression, how come we can’t assign it to a variable?”
As it turns out, in Python 3 (but not Python 2) you can assign it to a variable:
x = print(42)
print("The value of x is:")
print(x)
If you run this code, you get the following:
42
The value of x is:
None
Aha! As it turns out, the print function in Python 3 does have a value. Specifically, its value is None, just like any other function that doesn’t specifically return anything: