如何在打印函数中定义变量?

How to define a variable inside the print function?

我是这个领域的新手,我正在尝试解决一个问题(不确定是否真的可行),我想在显示器上打印一些信息和用户的一些输入。

以下工作正常:

>>> print (" Hello " + input("tellmeyourname: "))
tellmeyourname: dfsdf
 Hello dfsdf

但是,如果我想将用户的输入分配给一个变量,我不能:

>>> print (" Hello ", name = input("tellmeyourname: "))
tellmeyourname: mike
Traceback (most recent call last):
  File "<pyshell#47>", line 1, in <module>
    print (" Hello ", name = input("tellmeyourname: "))
TypeError: 'name' is an invalid keyword argument for this function

我在这里和其他 python 文档中进行了研究,尝试使用 %s 等来解决,但没有结果。我不想在两行中使用它(首先分配变量 name= input("tellmeyourname:") 然后打印)。 这可能吗?

不,这是不可能的。好吧,除了像

这样的东西
 x=input("tell me:");print("blah %s"%(x,));

但这并不是真正的一行...只是看起来像

从 Python 3.8 开始,可以使用 assignment expression:

print("Your name is: " + (name := input("Tell me your name: ")))
print("Your name is still: " + name)

尽管 'possible' 与 'advisable' 不同...


但在 Python <3.8:你不能。相反,将您的代码分成两个语句:

name = input("Tell me your name: ")
print("Your name is: " + name)

如果你经常发现自己想像这样使用两行,你可以把它做成一个函数:

def input_and_print(question):
  s = input("{} ".format(question))
  print("You entered: {}".format(s))

input_and_print("What is your name?")

此外,您可以使用函数 return 输入 s