我是这个领域的新手,我正在尝试解决一个问题(不确定是否真的可能)我想在显示器上打印一些信息以及来自用户的一些输入.
以下工作正常:
>>> print (" Hello " + input("tellmeyourname: "))
tellmeyourname: dfsdf
Hello dfsdf
Run Code Online (Sandbox Code Playgroud)
但是,如果我想将用户的输入分配给变量,我不能:
>>> 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
Run Code Online (Sandbox Code Playgroud)
我在这里和其他python文档进行了研究,尝试过%s等等来解决,没有结果.我不想在两行中使用它(首先分配变量name= input("tellmeyourname:")然后打印).这可能吗?
从Python 3.8开始,使用赋值表达式可以实现:
print("Your name is: " + (name := input("Tell me your name: ")))
print("Your name is still: " + name)
Run Code Online (Sandbox Code Playgroud)
虽然'可能'与'可取'不一样......
但在Python <3.8:你不能.相反,将您的代码分成两个语句:
name = input("Tell me your name: ")
print("Your name is: " + name)
Run Code Online (Sandbox Code Playgroud)
如果你经常发现自己想要使用这样的两行,你可以将它变成一个函数:
def input_and_print(question):
s = input("{} ".format(question))
print("You entered: {}".format(s))
input_and_print("What is your name?")
Run Code Online (Sandbox Code Playgroud)
此外,您可以让函数返回输入s.