hi
On the site realpython.com, I saw that was said that yield is a statement.
what is the difference between a statement and an expression in Python? plz, explain.
thanks
It's always a good idea to start with documentation:
Expression:
Quote:A piece of syntax which can be evaluated to some value. In other words, an expression is an accumulation of expression elements like literals, names, attribute access, operators or function calls which all return a value. In contrast to many other languages, not all language constructs are expressions. There are also statements which cannot be used as expressions, such as while. Assignments are also statements, not expressions.
Statement:
Quote:A statement is part of a suite (a “block” of code). A statement is either an expression or one of several constructs with a keyword, such as if, while or for.
(Oct-16-2023, 12:48 PM)perfringo Wrote: [ -> ]It's always a good idea to start with documentation:
Expression:
Quote:A piece of syntax which can be evaluated to some value. In other words, an expression is an accumulation of expression elements like literals, names, attribute access, operators or function calls which all return a value. In contrast to many other languages, not all language constructs are expressions. There are also statements which cannot be used as expressions, such as while. Assignments are also statements, not expressions.
Statement:
Quote:A statement is part of a suite (a “block” of code). A statement is either an expression or one of several constructs with a keyword, such as if, while or for.
hi
is it true that expression is oneline code, while statement is a block code?
i read above , but i can not understand the difference.
All code are statements. Only code that returns a value is an expression.
i = 0 # Statement
i == 0 # Statement and expression
while i < 5: # A statment that contains an expression, i < 5 is an expression
print(i) # only a statement. No returned value
i = i + 1 # A statement, i + 1 is an expression
(Oct-17-2023, 10:58 AM)deanhystad Wrote: [ -> ]All code are statements.
(Oct-17-2023, 10:58 AM)deanhystad Wrote: [ -> ]print(i) # only a statement. No returned value
This is not correct. As mentioned in the definition, referenced by @
perfringo
(Oct-16-2023, 12:48 PM)perfringo Wrote: [ -> ]an expression is an accumulation of expression elements like literals, names, attribute access, operators or function calls which all return a value.
In python3
print
is a function. When call
print(i)
it returns (i.e. evaluates to)
None
.
Any function call, incl. call of
print()
is an expression. In your example (and normally) we just throw away the value
None
as we don't care.
Compare with python2 where
print
is indeed statement
python3
>>> spam = print('eggs')
eggs
>>> spam is None
True
>>>
python2
>>> spam = print 'eggs'
File "<stdin>", line 1
spam = print 'eggs'
^
SyntaxError: invalid syntax