Default values on empty user input

PythonUser InputDefault Value

Python Problem Overview


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 input after entering the value and hitting Enter. Is there any method that if we don't enter the value and directly hit the Enter key, the variable will be directly assigned to a default value, say as input = 0.025?

Python Solutions


Solution 1 - Python

Python 3:

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

Python 2:

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

How does it work?

If nothing was entered then input/raw_input returns empty string. Empty string in Python is False, bool("") -> False. Operator or returns first truthy 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.

Solution 2 - Python

You can do it like this:

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

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

Solution 3 - Python

One way is:

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

Another way can be:

input = raw_input("Number: ") or 0.025

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

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

Solution 4 - Python

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

Solution 5 - Python

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"

Solution 6 - Python

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

Solution 7 - Python

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))

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionlkkkkView Question on Stackoverflow
Solution 1 - PythonaisbaaView Answer on Stackoverflow
Solution 2 - PythonpiokucView Answer on Stackoverflow
Solution 3 - PythonanuragalView Answer on Stackoverflow
Solution 4 - PythonGeorgyView Answer on Stackoverflow
Solution 5 - PythongrepitView Answer on Stackoverflow
Solution 6 - PythonBerView Answer on Stackoverflow
Solution 7 - PythonePanditView Answer on Stackoverflow