2024-09-26 18:20:23 发布
网友
在这里,如果用户要从键盘输入值,我必须设置默认值。以下是用户可以输入值的代码:
input = int(raw_input("Enter the inputs : "))
在这里,输入值并按回车键后,该值将被分配给变量input。如果我们不输入值并直接按enter键,变量将被直接赋值给一个默认值,比如input = 0.025,有什么方法吗?
input
input = 0.025
一种方法是:
default = 0.025 input = raw_input("Enter the inputs : ") if not input: input = default
另一种方法是:
input = raw_input("Number: ") or 0.025
同样适用于Python 3,但是使用input():
input()
ip = input("Ip Address: ") or "127.0.0.1"
input = int(raw_input("Enter the inputs : ") or "42")
它是如何工作的?
如果未输入任何内容,则raw_input返回空字符串。python中的空字符串是Falsebool("") -> False。运算符or返回第一个trufy值,在本例中为"42"。
False
bool("") -> False
or
"42"
这不是复杂的输入验证,因为用户可以输入任何内容,例如10个空格符号,然后是True。
True
你可以这样做:
>>> try: input= int(raw_input("Enter the inputs : ")) except ValueError: input = 0 Enter the inputs : >>> input 0 >>>
一种方法是:
另一种方法是:
同样适用于Python 3,但是使用
input()
:它是如何工作的?
如果未输入任何内容,则raw_input返回空字符串。python中的空字符串是
False
bool("") -> False
。运算符or
返回第一个trufy值,在本例中为"42"
。这不是复杂的输入验证,因为用户可以输入任何内容,例如10个空格符号,然后是
True
。你可以这样做:
相关问题 更多 >
编程相关推荐