I'd like to flexibly assign a value to a variable in python, no matter where in my code that variable is.
For instance, given a variable x in an If statement...
if(x == 5):
print "that's odd."
else:
print "Woot."
I'd like to be able to assign x right in the if statement like this:
if((x=3) == 5):
print "that's odd."
else:
print "Woot."
Is that possible? Here's another example. Let's say I have a line that's:
y = x + 10
I'd like to assign x right there:
y = (x=3) + 10
So I'm looking for a way to find a variable anywhere in my code and give it a value assignment. Is there a pythonic syntax for that?
In Python 3.8+, you can use assignment expressions (operator :=
):
if (x := 3) == 5:
print("that's odd")
y = (x := 3) + 10
"In Python, assignment is a statement, not an expression, and can therefore not be used inside an arbitrary expression. This means that common C idioms like:
while (line = readline(file)) {
...do something with line...
}
or
if (match = search(target)) {
...do something with match...
}
cannot be used as is in Python. "
http://effbot.org/pyfaq/why-can-t-i-use-an-assignment-in-an-expression.htm
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With