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?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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:
The
printstatement 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 asxor a more complicated expression like"The value is %d" % x.x += 5is a statement which adds 5 toxbut it doesn’t come back with a value forprintto use.So in Python you can’t say
any more than you could say:
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:
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:
you have the following by mistake:
In second case, C will set
myvarto 1 but Python will fail with a compile error because you have a statement where you should have an expression.