Assign a print statement to a variable in a function in Python 2.7

蹲街弑〆低调 提交于 2019-12-03 00:55:16

问题


I'm trying to assign a print statement to a variable in a function:

def namer(fn, ln='Smith'):
    # return value, default value
    r = print "Your name is ", fn, ln
    return r

But when I run the module, it says:

Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    import m8
  File "m8.py", line 3
    r = print "Your name is ", fn, ln
            ^
SyntaxError: invalid syntax

Any explanation?


回答1:


As you noted, in Python2.x, print is a statement. A statement is not an object, you cannot assign it to anything, you can just execute it.

Why would you want to return the print statement? Why not the string to be printed or a function that, when called would execute the print statement?




回答2:


The print statement only prints the value to your monitor. It doesn't make any sense to assign it to a variable.

If your code is meant to store the string in the variable r, then:

r = "Your name is " + fn + " "+ ln

This would work provided fn is a string, if not:

r= "Your name is " + str(fn) +" "+ ln




回答3:


Although it doesn't make sense to assign a print statement it makes sense to assign a print function to variable.

In this case you need to use the following import (only if using python 2)

from __future__ import print_function

A possible use case

import logging

use_print = True
if use_print:
    log_fun = print
else:
    log_fun = logging.info

log_fun('Spam')

The following statement will also be syntactically correct but it won't make sense

r = print('Something')

You will end up printing "Something" and assign None to r which is the return value of print function



来源:https://stackoverflow.com/questions/29097841/assign-a-print-statement-to-a-variable-in-a-function-in-python-2-7

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!