1

I am writing if statement in Python and I need to assign multiple values.

In order to style it, I want all my assignment in one line. So I tried comma to separate them.

if True:
    a=0.5, b=0.5
    print(a), print(b)

This would have a syntax error:

SyntaxError: can't assign to literal

However, when I use semicolon it works.

if True:
    a=0.5; b=0.5
    print(a), print(b)

Why can comma work in print but not in assignment?

1
  • 1
    Change a=0.5, b=0.5 to a, b = 0.5, 0.5. As for the ;, it marks the end of a statement. So a=0.5; is one statement that is separate from b=0.5. Commented Dec 27, 2017 at 2:38

2 Answers 2

3

Simply put, commas in python are used to unpack tuples. When you use a comma in a print function, you're actually using two tuples. Semicolons are used as a separator, as they would be used in a language such as JS or C++, and are equivalent to a newline. A literal is essentially the opposite of a variable; a constant or fixed value.

If you want to do two assignments in one line, what you can do is; a, b = 0.5, 0.5

However, in your case, you can assign variables as such; a = b = 0.5

Sign up to request clarification or add additional context in comments.

Comments

1

Commas in Python are used for things like function arguments and creating tuples and lists. If you notice the command-line output when running this

>>> print(a), print(b)
0.5
0.5
(None, None)

the (None, None) is the resulting tuple created from the output value of two print statements put together with a comma. None, None is the same as (None, None).

The printed 0.5 values are the so-called side-effect of the print statement. It is what ends up on your screen when printing -- but the return value of a print is actually None.

Also notice the effect of

>>> a=0.5, 0.6
>>> print(a)
(0.5, 0.6)

a is assigned both of the two values following the equal sign since there is a comma. And now we are getting closer to the solution, these two statements are identical:

a=0.5, b=0.5
a = (0.5, b) = 0.5

so Python attempts to assign the last 0.5 to the value of the previous statement, which it can't. Basically doing a literal assignment giving a syntax error:

>>> (0.6, 0.7) = 0.5
SyntaxError: can't assign to literal

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.