How do you detect specifically an integer input but also check to see if the input to something is blank?

huangapple go评论89阅读模式
英文:

How do you detect specifically an integer input but also check to see if the input to something is blank?

问题

我在想是否有可能让输入变量寻找一个整数输入,同时还能够检测用户是否没有输入。我想制作一个简单的应用程序,用户可以从一个编号列表中选择一个选项,如果用户将输入区域留空,希望程序默认选择第一个选项。

我目前有一个尝试循环,不断要求用户输入整数,写成这样:

  1. def inputNum():
  2. while True:
  3. try:
  4. userInput = int(input())
  5. except ValueError:
  6. print("输入不是整数");
  7. continue
  8. except EOFError:
  9. return ""
  10. break
  11. else:
  12. return userInput
  13. break
  14. selection = inputNum()

我有一种感觉这其中的部分显然是错误的,但我希望每个人都能理解大意并提供有用的反馈和答案。

英文:

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:

  1. def inputNum():
  2. while True:
  3. try:
  4. userInput = int(input())
  5. except ValueError:
  6. print("Input is not an integer");
  7. continue
  8. except EOFError:
  9. return ""
  10. break
  11. else:
  12. return userInput
  13. break
  14. 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.

答案1

得分: 0

不要在请求输入时将其转换为整数。将您的输入请求分为两个步骤:

  1. def inputNum():
  2. while True:
  3. userInput = input().strip()
  4. if not userInput:
  5. print('输入为空')
  6. continue
  7. try:
  8. userInput = int(userInput)
  9. except ValueError:
  10. print("输入不是整数");
  11. continue
  12. return userInput
  13. selection = inputNum()

示例:

  1. 输入为空
  2. abc
  3. 输入不是整数
  4. 123

输出:123

英文:

Don't convert to integer while requesting input. Split your input request into 2 steps:

  1. def inputNum():
  2. while True:
  3. userInput = input().strip()
  4. if not userInput:
  5. print('Input is empty')
  6. continue
  7. try:
  8. userInput = int(userInput)
  9. except ValueError:
  10. print("Input is not an integer");
  11. continue
  12. return userInput
  13. selection = inputNum()

Example:

  1. Input is empty
  2. abc
  3. Input is not an integer
  4. 123

Output: 123

huangapple
  • 本文由 发表于 2023年2月27日 16:28:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/75578223.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定