Default values on empty user input
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
.
You can do it like this:
>>> try: input= int(raw_input("Enter the inputs : ")) except ValueError: input = 0Enter the inputs : >>> input0>>>
One way is:
default = 0.025input = 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"