空用户输入时的默认值 [英] Default values on empty user input
问题描述
如果用户将通过键盘输入值,则必须在此处设置默认值。这是用户可以输入值的代码:
Here I have to set the default value if the user will enter the value from the keyboard. Here is the code that user can enter value:
input = int(raw_input("Enter the inputs : "))
此处,值将分配给变量 input
输入值并按 Enter 后。是否有任何方法可以使我们不输入值而直接按 Enter 键,则将变量直接分配给默认值,例如 input = 0.025
?
Here the value will be assigned to a variable input
after entering the value and hitting Enter. Is there any method that if we don't enter the value and directly hit the Enter key, the variable will be directly assigned to a default value, say as input = 0.025
?
推荐答案
Python 3:
input = int(input("Enter the inputs : ") or "42")
Python 2:
input = int(raw_input("Enter the inputs : ") or "42")
它如何工作?
如果未输入任何内容,则输入
/ raw_input
返回空字符串。 Python中的空字符串为 False
, bool()->错误
。运算符或
返回第一个真实值,在这种情况下为 42
。
If nothing was entered then input
/raw_input
returns empty string. Empty string in Python is False
, bool("") -> False
. Operator or
returns first truthy value, which in this case is "42"
.
这不是复杂的输入验证,因为用户可以输入任何内容,例如十个空格符号,则为 True
。
This is not sophisticated input validation, because user can enter anything, e.g. ten space symbols, which then would be True
.
这篇关于空用户输入时的默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!