如果用户从键盘输入值,我必须设置默认值。这是用户可以输入值的代码:
input = int(raw_input("Enter the inputs : "))
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:
inp = int(input("Enter the inputs : ") or "42")
Python 2:
inp = int(raw_input("Enter the inputs : ") or "42")
它是如何工作的?
如果没有输入任何内容input
/raw_input
返回空字符串。 Python 中的空字符串是False
, bool("") -> False
。操作员or
返回第一个真值,在本例中是"42"
.
这不是复杂的输入验证,因为用户可以输入任何内容,例如十个空格符号,则将是True
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)