In Python, is there a way to assign a result to a variable and immediately print it? In other words, I am looking for a one-line equivalent to
a = something()
print(a)
(just once, not every assignment should be automatically printed).
There are REPLs, e.g. for Scala, where this happens automatically:
scala> val count = 1
count: Int = 1
As of Python 3.8, the answer to this has changed.
Now, you can assign a value to a variable and return that same value using "assignment expressions" (colloquially called "the Walrus operator").
So, this is valid Python:
print("Hello, {}".format((w := "world"))
Which will print "Hello, world" and assign the string "world" to the variable "w" all in one line.
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