有没有一种方法可以将三元运算符与输入结合使用,在一次操作中为变量赋值?你知道吗
更详细的方式:
# assume this happened a while back.
myVariable = "user: "
# I'd like to get these two lines down to one.
myInputResult = input('Enter something, or just hit Enter for the default: ')
myVariable += "the user typed: " + myInputResult if myInputResult != '' else 'the user did not type anything'
我需要做的是引用input()
函数中的值,而不必首先将它赋给变量。你知道吗
我在其他语言中见过一种技术,但当您将赋值视为变量时,Python似乎不支持返回赋值:
myVariable += "the user typed " + x if (x = input("Enter something or nothing: ")) != '' else "the user did not type anything"
不起作用。你知道吗
请注意,即使input
可以返回默认值,但这还不够,因为当用户不输入任何内容时,静态文本会有所不同。你知道吗
variable方法很好,但是如果可能的话,我只是在寻找一种更简洁的方法来编写代码。你知道吗
顺便说一句,Python 3
Python没有内联赋值。您可以编写一个函数,将转换应用于truthy值,并保持falsy值(如空字符串)不变(这是
Optional.map
类型函数的“lite”版本):使用方法如下:
但这并不是一个巨大的进步。你知道吗
相关问题 更多 >
编程相关推荐