python中空用户输入的默认值

lkk*_*kkk 24 python user-input default-value

如果用户将从键盘输入值,我必须设置默认值.以下是用户可以输入值的代码:

input = int(raw_input("Enter the inputs : "))
Run Code Online (Sandbox Code Playgroud)

这里的值将input在输入值后分配给变量并点击'Enter',是否有任何方法,如果我们不输入值并直接点击'Enter'键,变量将直接指定默认值,如input = 0.025.

ais*_*baa 55

input = int(raw_input("Enter the inputs : ") or "42")
Run Code Online (Sandbox Code Playgroud)

它是如何工作的?

如果未输入任何内容,则raw_input将返回空字符串.python中的空字符串是False bool("") -> False.运算符or返回第一个trufy值,在这种情况下是"42".

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

  • @AnchithAcharya,我同意这是不好的做法,因为“输入”是一个内置函数,您将用语句的输出替换该函数。实际上,这可能不是什么大问题,但如果您稍后需要在函数中再次请求“input”,您会发现它无法按预期工作,因为“input”现在将是“int”。 (7认同)
  • 将变量命名为“输入”不是不好的做法吗? (3认同)

pio*_*kuc 12

你可以这样做:

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

Enter the inputs : 
>>> input
0
>>> 
Run Code Online (Sandbox Code Playgroud)


anu*_*gal 10

一种方法是:

default = 0.025
input = raw_input("Enter the inputs : ")
if not input:
   input = default
Run Code Online (Sandbox Code Playgroud)

另一种方法可以是:

input = raw_input("Number: ") or 0.025
Run Code Online (Sandbox Code Playgroud)

同样适用于 Python 3,但使用input()

ip = input("Ip Address: ") or "127.0.0.1"
Run Code Online (Sandbox Code Playgroud)


Geo*_*rgy 7

您也可以为此使用click,它为命令行界面提供了许多有用的功能:

import click

number = click.prompt("Enter the number", type=float, default=0.025)
print(number)
Run Code Online (Sandbox Code Playgroud)

输入示例:

import click

number = click.prompt("Enter the number", type=float, default=0.025)
print(number)
Run Code Online (Sandbox Code Playgroud)

或者

Enter the number [0.025]: 
 3  # Entered some number
3.0
Run Code Online (Sandbox Code Playgroud)