Skip to main content
 首页 » 编程设计

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

2025年05月04日11Free-Thinker

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

以下工作正常:

>>> 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:") 然后打印)。 这可能吗?

请您参考如下方法:

从 Python 3.8 开始,使用 assignment expression 将成为可能:

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

尽管“可能”与“建议”不同......


但是在 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?") 

此外,您可以让函数返回输入的。