Default values on empty user input

我们两清 提交于 2019-12-02 21:35:21
input = int(raw_input("Enter the inputs : ") or "42")

How does it work?

If nothing was entered then raw_input returns empty string. Empty string in python is False bool("") -> False. Operator or returns first trufy value, which in this case is "42".

This is not sophisticated input validation, because user can enter anything, e.g. ten space symbols, which then would be True.

piokuc

You can do it like this:

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

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

One of the way is -

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

Another way can be -

input = raw_input("Enter the inputs : ") or 0.025

Most of the above answers are correct but for Python 3.7, here is what you can do to set the default value.

user_input = input("is this ok ? - [default:yes] \n")
if len(user_input) == 0 :
    user_input = "yes"
Ber

You could first input a string, then check for zero length and valid number:

input_str = raw_input("Ender the number:")

if len(input_str) == 0:
    input_number = DEFAULT
else:
    try:
        input_number = int(input_str)
    except ValueError:
        # handle input error or assign default for invalid input

You can also use click library for that, which provides lots of useful functionality for command-line interfaces:

import click

number = click.prompt("Enter the number", type=float, default=0.025)
print(number)

Examples of input:

Enter the number [0.025]: 
 3  # Entered some number
3.0

or

Enter the number [0.025]: 
    # Pressed enter wihout any input
0.025
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!