简体   繁体   中英

variable assigning and using python

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

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.

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 )

cf https://docs.python.org/3/reference/grammar.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM