How to define default value if empty user input in Python?

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.

Leave a Comment