81

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?

ivanleoncz
  • 9,070
  • 7
  • 57
  • 49
lkkkk
  • 1,999
  • 4
  • 23
  • 29

7 Answers7

161

Python 3:

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

Python 2:

inp = 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.

Timur Shtatland
  • 12,024
  • 2
  • 30
  • 47
aisbaa
  • 9,867
  • 6
  • 33
  • 48
  • 13
    Isn't it bad practise to name the variable as 'input'? – Anchith Acharya Feb 04 '21 at 13:24
  • 1
    It depends on the context, if the message would say "enter how many apples you have", then yes `input` would be very bad name. – aisbaa Feb 05 '21 at 13:15
  • 7
    @AnchithAcharya, I would agree it's bad practice as `input` is a built-in function and you would be replacing that function with the output of the statement. In practice it may not be a big deal, but if you needed to ask for `input` again later in the function you would find it not working as expected as `input` would now be an `int`. – NimbusScale Mar 19 '21 at 18:29
15

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"
ivanleoncz
  • 9,070
  • 7
  • 57
  • 49
anuragal
  • 3,024
  • 19
  • 27
14

You can do it like this:

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

Enter the inputs : 
>>> input
0
>>> 
Jayanth Koushik
  • 9,476
  • 1
  • 44
  • 52
piokuc
  • 25,594
  • 11
  • 72
  • 102
  • There are [many reasons not to use exceptions for control flow](https://stackoverflow.com/questions/729379/why-not-use-exceptions-as-regular-flow-of-control). – kmf May 31 '22 at 12:25
11

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
Georgy
  • 12,464
  • 7
  • 65
  • 73
2

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
Jayanth Koushik
  • 9,476
  • 1
  • 44
  • 52
Ber
  • 40,356
  • 16
  • 72
  • 88
2

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"
grepit
  • 21,260
  • 6
  • 105
  • 81
  • 7
    This is the same idea as in [Ber's answer](https://stackoverflow.com/a/22402660/7851470). Also, you might wanna change "Python 3.7" to just "Python 3" because [`input`](https://stackoverflow.com/questions/4915361/whats-the-difference-between-raw-input-and-input-in-python3-x) was there before that as well. – Georgy Jul 05 '19 at 11:59
0

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))
ePandit
  • 2,905
  • 2
  • 24
  • 15