The following code doesn't work in python
x = 11
print(x += 5)
while this code does
x = 11
x += 5
print(x)
why is that?
The following code doesn't work in python
x = 11
print(x += 5)
while this code does
x = 11
x += 5
print(x)
why is that?
x += 5 is a statement, not an expression. You can only use expressions as arguments in function calls.
I'm assuming you are used to a C-like language, where x += 5 is an expression, but in Python it's not.
The problem is the due to the difference between a Statement and an Expression. This question has an excellent answer which explains the difference, the key point being:
Expression: Something which evaluates to a value. Example: 1+2/x
Statement: A line of code which does something. Example: GOTO 100
The print
statement needs a value to print out. So in the brackets you put an expression which gives it the value to print. So this can be something as simple as x
or a more complicated expression like "The value is %d" % x
.
x += 5
is a statement which adds 5 to x
but it doesn't come back with a value for print
to use.
So in Python you can't say
print(x += 5)
any more than you could say:
y = x += 5
However, in some other languages, Statements are also Expressions, i.e. they do something and return a value. For example, this you can do this in Perl:
$x = 5;
$y = $x += 5;
print $y;
Whether you would want to do that is another question.
One of the benefits of enforcing the difference between statements and expressions in Python is that you avoid common bugs where instead of something like:
if (myvar == 1) {
//do things
}
you have the following by mistake:
if (myvar = 1) {
//do things
}
In second case, C will set myvar
to 1 but Python will fail with a compile error because you have a statement where you should have an expression.
In Python, function calls only accept expressions, not statements.
Anything with an equals in it is a statement.
It's the same reason you can't do:
if x += 5:
print x
See the Python Language Reference (3.2 version, 2.7 version) for full details.