Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using print() with compound operators in python

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?

like image 909
Mahmoud Hanafy Avatar asked Dec 09 '25 01:12

Mahmoud Hanafy


2 Answers

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.

like image 164
Dave Webb Avatar answered Dec 10 '25 15:12

Dave Webb


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.

like image 38
Roel Schroeven Avatar answered Dec 10 '25 14:12

Roel Schroeven



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!