2

I was wondering if it is possible to simultaneously assign a variable and use it as a parameter for a function. for example:

number = 10
print(number*=2)

with the output being:

>>>20

also, if this was repeated:

>>>40
  • 1
    No, it isn't, as the error message should indicate. Why would you want it to be? – jonrsharpe Feb 11 '16 at 21:23
  • 1
    Python doesn't have this facility. The closest I know is the decrement/increment expression in C: an evaluation with a side effect. – Prune Feb 11 '16 at 21:25

2 Answers2

0

Python's interpreter doesn't interpret such syntax on function call and will raise a SyntaxError. Since you want to write an operation it doesn't make any difference where you do that.

You can simply do that at the top level of your function or globally before passing to function.

Mazdak
  • 105,000
  • 18
  • 159
  • 188
0

You can't. This syntax is not defined in the Python grammar and so it is not possible to use the result stored through an assignment as a parameter.

test: or_test ['if' or_test 'else' test] | lambdef
[after some depth, you will have a comparaison, which is...]
comparison: expr (comp_op expr)*
argument: ( test [comp_for] |
            test '=' test |
            '**' test |
            '*' test )

As you can see an argument is basically an expression, possibly through a ternary operation/list comprehension. (the test '=' test is for setting a named argument)

c.f https://docs.python.org/3/reference/grammar.html

Community
  • 1
  • 1
Maxime Lorant
  • 34,607
  • 19
  • 87
  • 97