简体   繁体   English

变量分配和使用python

[英]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 . Python的解释器不会在函数调用时解释此类语法,而是会引发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. 该语法未在Python语法中定义,因此无法将通过分配存储的结果用作参数。

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 ) test '=' test用于设置命名参数

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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