简体   繁体   中英

How to assign result to a variable AND print result in one command in Python?

In R , when you assign something to a variable, you can wrap your code in brackets to also print the result:

> a<-1+2
> a
3

>(a<-1+2)
3

Is there an equivalent feature in python?

No. You can't mix statements and expressions in the same "command".

You can, however, use ; to have both on the same "line":

a = 1 ; print(a)
# 1

There is no single statement which allows to that.

First we have assignment statements . Which allow to, well, make assignments.

And then you have either a print function (for Python 3.x) or a print statement (for Python 2.x). But neither of them cannot be mixed with the aforementioned assignemnt statement.

So no, you cannot do that in a single statement. You can, of couse, cheat that into one line by using ; but that is something not very readable which I would not recommend.


Bonun non-aswering rambling

From a readability point of view, assigning and printing are two very different things which should not be mixed.

Moreover, if you are (for instance) using a logging library instead of direct print usage, then the "single statement" you are looking for would become useless. In fact, I think that that is a rationale behind moving print from statement to function.

So, you don't have a single statement for assign-and-print and, I will add, that kind of statement doesn't seem a good idea in the Python language.

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