python - 空用户输入的默认值

标签 python user-input default-value

如果用户从键盘输入值,我必须在这里设置默认值。这是用户可以输入值的代码:

input = int(raw_input("Enter the inputs : "))

在输入值并点击 Enter 后,此处的值将分配给变量 input。有没有什么方法,如果我们不输入值直接按Enter键,变量会直接赋值给一个默认值,比如input = 0.025 ?

最佳答案

Python 3:

input = int(input("Enter the inputs : ") or "42")

Python 2:

input = int(raw_input("Enter the inputs : ") or "42")

它是如何工作的?

如果没有输入,则 input/raw_input 返回空字符串。 Python 中的空字符串是 False, bool("") -> False。运算符 or 返回第一个真值,在本例中为 "42"

这不是复杂的输入验证,因为用户可以输入任何内容,例如十个空格符号,则为 True

关于python - 空用户输入的默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22402548/

相关文章:

python - Google App Engine appcfg.py data_upload 身份验证失败

python - 打开CV错误: error while displaying rectangle

python - 具有匹配标题的两个数据帧列之间的关联

python - 列表输出被复制

c - 获取 char 和整数作为输入或仅获取 char 作为输入

html - 防止用户生成的内容破坏布局?

mysql - 在 CakePHP 中更新时重置为 MySQL DEFAULT 值

python - 在使用 Python 的 argparse 时知道用户是否指定了参数

user-input - SML/新泽西州 : getting user input

斯卡拉 2.9 : plans for type inference of function parameters with default arguments?