default values on empty user input in python

2019-03-18 01:43发布

Here I have to set the default value if the user will enter the value from keyboard. Here is the code that user can enter value:

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

here the value will assign to variable input after entering value and hit 'Enter', is there any method that if we don't enter value and directly hit the 'Enter' key and the variable will directly assign default value say as input = 0.025.

5条回答
叼着烟拽天下
2楼-- · 2019-03-18 02:21

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
查看更多
我想做一个坏孩纸
3楼-- · 2019-03-18 02:22

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
查看更多
太酷不给撩
4楼-- · 2019-03-18 02:32
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.

查看更多
Melony?
5楼-- · 2019-03-18 02:39

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"
查看更多
该账号已被封号
6楼-- · 2019-03-18 02:48

You can do it like this:

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

Enter the inputs : 
>>> input
0
>>> 
查看更多
登录 后发表回答