空用户inpu上的默认值

2024-06-16 10:45:41 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

在这里,输入值并按回车键后,该值将被分配给变量input。如果我们不输入值并直接按enter键,变量将被直接赋值给一个默认值,比如input = 0.025,有什么方法吗?


Tags: the方法代码用户inputrawintinputs
3条回答

一种方法是:

default = 0.025
input = raw_input("Enter the inputs : ")
if not input:
   input = default

另一种方法是:

input = raw_input("Number: ") or 0.025

同样适用于Python 3,但是使用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"

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

你可以这样做:

>>> try:
        input= int(raw_input("Enter the inputs : "))
    except ValueError:
        input = 0

Enter the inputs : 
>>> input
0
>>> 

相关问题 更多 >