I was wondering if it was possible to have an input variable look for an integer input but also be able to detect if the user leaves no input. I was wanting to make a simple app where the user chooses an option out of a numbered list and want the program to default to the first option if the user leaves the input area blank.
I currently have a try loop that continually asks the user for an integer as an input written like this:
def inputNum():
while True:
try:
userInput = int(input())
except ValueError:
print("Input is not an integer");
continue
except EOFError:
return ""
break
else:
return userInput
break
selection = inputNum()
I have a feeling part of this is blatantly wrong, but I hope everyone gets the gist of things and can help provide helpful feedback and answers.
userInputtoint, you can check if it is blank withuserInput == "". Similarly, you can check if it is an integer with string's.isdigit(), souserInput.isdigit(). Doing the try/catch the way you have also works for checking if it is an integer, although it may lead to unexpected effects..isdigit()?EOFErroronint. It causesEOFErrorwhen the string will be interpreted as Python code, for example usingevalorexec(do not use such tools here). Once you understand how to check for an empty string, there isn't a meaningful question any more; so I closed this as a duplicate of the canonical for how to check for an empty string."".isdigit()returnsFalseif that's what you're asking. If you want to specifically check if a string is empty, doinguserInput == ""would do that.