在Python 2.7中为函数中的变量分配一个打印语句 [英] Assign a print statement to a variable in a function in Python 2.7

查看:268
本文介绍了在Python 2.7中为函数中的变量分配一个打印语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  def namer(fn,ln = 'Smith'):
#返回值,默认值
r = print您的名字是,fn,ln
返回r

但是当我运行模块时,它说:

  Traceback (最近一次调用最后一次):
在< module>文件中的第1行< pyshell#1>
导入m8
文件m8.py,第3行
r = print您的名字是,fn,ln
^
SyntaxError:无效语法

任何解释?

解决方案

正如你所说的,在Python2.x中, print 是一个语句。一个语句不是一个对象,你不能将它分配给任何东西,你可以执行它。



为什么要返回 print 语句?为什么不打印字符串或被调用的函数会执行打印语句?


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?

解决方案

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?

这篇关于在Python 2.7中为函数中的变量分配一个打印语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆