如何在打印函数中定义变量? [英] How to define a variable inside the print function?

查看:66
本文介绍了如何在打印函数中定义变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

以下工作正常:

<预><代码>>>>打印(你好"+输入(告诉我你的名字:"))告诉我你的名字:dfsdf你好 dfsdf

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

<预><代码>>>>打印(你好",名称=输入(告诉我你的名字:"))告诉我你的名字:迈克回溯(最近一次调用最后一次):文件<pyshell#47>",第 1 行,在 <module> 中打印(你好",名称=输入(告诉我你的名字:"))类型错误:名称"是此函数的无效关键字参数

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

解决方案

从 Python 3.8 开始,使用 赋值表达式:

print("你的名字是:" + (name := input("告诉我你的名字:")))print("你的名字还是:" + name)

虽然可能"与建议"不同...

<小时>

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

name = input("告诉我你的名字:")print("你的名字是:" + name)

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

def input_and_print(问题):s = input("{} ".format(question))print("您输入的是:{}".format(s))input_and_print("你叫什么名字?")

此外,您可以让函数返回输入 s.

I am a newbie in this field, and I am trying to solve a problem (not really sure if it is possible actually) where I want to print on the display some information plus some input from the user.

The following works fine:

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

However if I want to assign user's input to a variable, I can't:

>>> 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

I have researched inside here and other python documentation, tried with %s etc. to solve, without result. I don't want to use it in two lines (first assigning the variable name= input("tellmeyourname:") and then printing). Is this possible?

解决方案

Starting from Python 3.8, this will become possible using an assignment expression:

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

Though 'possible' is not the same as 'advisable'...


But in Python <3.8: you can't. Instead, separate your code into two statements:

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

If you often find yourself wanting to use two lines like this, you could make it into a function:

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

input_and_print("What is your name?")

Additionally you could have the function return the input s.

这篇关于如何在打印函数中定义变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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