提问人:mxrgan 提问时间:2/27/2023 最后编辑:Karl Knechtelmxrgan 更新时间:2/27/2023 访问量:55
您如何专门检测整数输入,同时检查某物的输入是否为空?[复制]
How do you detect specifically an integer input but also check to see if the input to something is blank? [duplicate]
问:
我想知道是否可以让输入变量查找整数输入,但也能够检测用户是否没有输入。我想制作一个简单的应用程序,用户从编号列表中选择一个选项,并希望程序在用户将输入区域留空时默认为第一个选项。
我目前有一个 try 循环,它不断要求用户输入一个整数作为输入,这样写成:
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()
我有一种感觉,这其中的一部分是完全错误的,但我希望每个人都能理解事情的要点,并能帮助提供有用的反馈和答案。
答:
0赞
mozway
2/27/2023
#1
请求输入时不要转换为整数。将输入请求拆分为 2 个步骤:
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()
例:
Input is empty
abc
Input is not an integer
123
输出:123
上一个:如何将输入读取为数字?
评论
userInput
int
userInput == ""
.isdigit()
userInput.isdigit()
.isdigit()
EOFError
int
EOFError
eval
exec
"".isdigit()
False
userInput == ""