How do you detect specifically an integer input but also check to see if the input to something is blank?
Question:
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.
Answers:
Don’t convert to integer while requesting input. Split your input request into 2 steps:
def inputNum():
while True:
userInput = input().strip()
if not userInput:
print('Input is empty')
continue
try:
userInput = int(userInput)
except ValueError:
print("Input is not an integer");
continue
return userInput
selection = inputNum()
Example:
Input is empty
abc
Input is not an integer
123
Output: 123
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.
Don’t convert to integer while requesting input. Split your input request into 2 steps:
def inputNum():
while True:
userInput = input().strip()
if not userInput:
print('Input is empty')
continue
try:
userInput = int(userInput)
except ValueError:
print("Input is not an integer");
continue
return userInput
selection = inputNum()
Example:
Input is empty
abc
Input is not an integer
123
Output: 123