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.
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)
您也可以为此使用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)
| 归档时间: |
|
| 查看次数: |
49682 次 |
| 最近记录: |