Python Default values on empty user input

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22402548/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 00:53:34  来源:igfitidea点击:

Default values on empty user input

pythonuser-inputdefault-value

提问by lkkkk

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

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

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

Here the value will be assigned to a variable inputafter entering the value and hitting Enter. Is there any method that if we don't enter the value and directly hit the Enterkey, the variable will be directly assigned to a default value, say as input = 0.025?

Here the value will be assigned to a variable inputafter entering the value and hitting Enter. Is there any method that if we don't enter the value and directly hit the Enterkey, the variable will be directly assigned to a default value, say as input = 0.025?

采纳答案by aisbaa

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

How does it work?

How does it work?

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

If nothing was entered then raw_input returns empty string. Empty string in python is Falsebool("") -> False. Operator orreturns 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.

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

回答by piokuc

You can do it like this:

You can do it like this:

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

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

回答by Ber

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

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

回答by anuragal

One way is:

One way is:

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

Another way can be:

Another way can be:

input = raw_input("Number: ") or 0.025

Same applies for Python 3, but using input():

Same applies for Python 3, but using input():

ip = input("Ip Address: ") or "127.0.0.1"

回答by grepit

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

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"

回答by Georgy

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

You can also use clicklibraryfor 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:

Examples of input:

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

or

or

Enter the number [0.025]: 
    # Pressed enter wihout any input
0.025

回答by ePandit

Here is an example to validate user input to be a number and also set default value if he enters nothing.

Here is an example to validate user input to be a number and also set default value if he enters nothing.

while True:
    luckyNo = input("Enter your lucky number - [default:108]: ").strip()
    if luckyNo.isdigit(): # check if user entered a number
        luckyNo = int(luckyNo) # convert entered number to integer
        break
    else:  
        if not luckyNo: # user entered nothing
            print("You entered nothing. Using default value...")
            luckyNo = 108 # set default value
            break
        else: # user entered something other than a number
            print("Wrong input!. Try again.")

print("Your lucky number is " + str(luckyNo))