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

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

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

问题

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

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

def inputNum():
    while True:
        try:
            userInput = int(input())
        except ValueError:
            print("输入不是整数");
            continue
        except EOFError:
            return ""
            break
        else:
            return userInput
            break

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:

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.

答案1

得分: 0

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

def inputNum():
    while True:
        userInput = input().strip()
        if not userInput:
            print('输入为空')
            continue
        try:
            userInput = int(userInput)
        except ValueError:
            print("输入不是整数");
            continue
        return userInput

selection = inputNum()

示例:

输入为空
abc
输入不是整数
123

输出:123

英文:

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

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:

确定