Python 提示用户只输入大于1的整数的错误处理

Python 提示用户只输入大于1的整数的错误处理,python,python-3.x,function,error-handling,integer,Python,Python 3.x,Function,Error Handling,Integer,我试图编写一个Python函数,要求输入大于1的整数,并返回或打印输入值 例如,在运行代码时: 错误案例1: 输入一个大于1:1的整数 输出:请输入一个大于1的数字: 错误案例2: 输入一个大于1的整数:abc345 输出:请仅输入整数值: 如果只是为了处理错误情况1,那么很容易,我们可以使用while循环。但为了也包括非整数输入的情况,我的代码总是崩溃 以下是我的功能: def mult_digits(): x = input("Enter an integer gre

我试图编写一个Python函数,要求输入大于1的整数,并返回或打印输入值

例如,在运行代码时:
错误案例1:
输入一个大于1:1的整数
输出:请输入一个大于1的数字:

错误案例2:
输入一个大于1的整数:abc345
输出:请仅输入整数值:

如果只是为了处理错误情况1,那么很容易,我们可以使用while循环。但为了也包括非整数输入的情况,我的代码总是崩溃

以下是我的功能:

    def mult_digits():
        x = input("Enter an integer greater than 1: ")    
        while type(x) is not int:
            try:
                while int(x) <= 1:
                    x = input("Please enter a number greater than 1: ")
                    x = int(x)
            except ValueError:
                  x = input("Please enter integer values only: ")
                  x = int(x)       
        print(f"Yes, you have entered {x}.")
def多位数():
x=输入(“输入一个大于1的整数:”)
当类型(x)不是int时:
尝试:

而int(x)我认为你把事情弄得太复杂了。基本上,如果有人输入一个值,您首先通过
int(..)
函数传递它,如果没有错误,您将检查它是否大于1,这样我们就可以编写
while
循环,不断迭代直到值有效,如:

def mult_digits():
    msg = "Enter an integer greater than 1: "
    valid = False
    while not valid:
        x = input(msg)  
        try:
            x = int(x)
        except ValueError:
            msg = "Please enter integer values only: "
        else:
            valid = x > 1
            if not valid:
                msg = "Enter an integer greater than 1: "
    print(f"Yes, you have entered {x}.")
因此,我们只需在
while
循环中执行检查(理想情况下,您也可以将其封装在一个方法中),如果
int(…)
引发
错误,则内容仍然无效,我们甚至可以更改
msg
。如果转换本身没有引起任何错误,我们可以检查约束,并再次给出有用的消息


我们一直这样做,直到
valid
设置为
True
,然后我们打印值。

我觉得你把事情弄得太复杂了。基本上,如果有人输入一个值,您首先通过
int(..)
函数传递它,如果没有错误,您将检查它是否大于1,这样我们就可以编写
while
循环,不断迭代直到值有效,如:

def mult_digits():
    msg = "Enter an integer greater than 1: "
    valid = False
    while not valid:
        x = input(msg)  
        try:
            x = int(x)
        except ValueError:
            msg = "Please enter integer values only: "
        else:
            valid = x > 1
            if not valid:
                msg = "Enter an integer greater than 1: "
    print(f"Yes, you have entered {x}.")
def mult_digits():
    x = input("Enter an integer greater than 1: ")
    while True:
        try:
            while int(x) <= 1:
                x = input("Please enter a number greater than 1: ")
                x = int(x)
            if x > 1:
                    break
        except ValueError:
            x = input("Please enter integer values only: ")

    print(f"Yes, you have entered {x}.")
因此,我们只需在
while
循环中执行检查(理想情况下,您也可以将其封装在一个方法中),如果
int(…)
引发
错误,则内容仍然无效,我们甚至可以更改
msg
。如果转换本身没有引起任何错误,我们可以检查约束,并再次给出有用的消息

我们一直这样做,直到
valid
设置为
True
,然后打印值。

def mult\u digits()
def mult_digits():
    x = input("Enter an integer greater than 1: ")
    while True:
        try:
            while int(x) <= 1:
                x = input("Please enter a number greater than 1: ")
                x = int(x)
            if x > 1:
                    break
        except ValueError:
            x = input("Please enter integer values only: ")

    print(f"Yes, you have entered {x}.")
x=输入(“输入一个大于1的整数:”) 尽管如此: 尝试: 而int(x)1: 打破 除值错误外: x=输入(“请仅输入整数值:”) 打印(f“是,您已输入{x}”。)
尝试以下操作

def mult_digits():
x=输入(“输入一个大于1的整数:”)
尽管如此:
尝试:
而int(x)1:
打破
除值错误外:
x=输入(“请仅输入整数值:”)
打印(f“是,您已输入{x}”。)

试试这个

所以我在工作时看到了它,当它被发布到CodeReview时。我想回答,但不得不等到回家。我将您的块分为两个块,一个获取输入(我讨厌冗余代码),另一个执行检查并调用输入。我还为数字和非数字添加了一条清晰的错误消息。我在这里发布完整的代码:

# -*-coding: utf-8-*-
# !/usr/bin/python3.6

import sys


def multi_digits():
    digit = get_input()
    x = True

    while x:
        if digit in '23456789':
            print(f'Yes,you have entered {digit}.')
            x = False
        # In elif it looks like int(digit) may throw an error if it isn't a digit but
        # because of the way if statements work this wont happen. The if statement excutes
        # digit.isdigit() first, if it returns false it doesn't care about the second condition so
        # int(digit) only is checked after we confirm digit is actually a digit.
        elif digit.isdigit() and int(digit) <= 1:
            print('Invalid input: Digit was not greater than 1')
            digit = get_input()
        else:
            print('Invalid input: no letters allowed')
            digit = get_input()


def get_input() -> str:
    return input('Enter an integer greater than 1: ')


def main():
    multi_digits()


if __name__ == '__main__':
    main()
#-*-编码:utf-8-*-
# !/usr/bin/python3.6
导入系统
def多位数()
数字=获取输入()
x=真
而x:
如果“23456789”中的数字为:
打印(f'是,您已输入{digit}'
x=假
#在elif中,如果int(digit)不是一个数字,但是
#因为如果语句起作用,这种情况就不会发生。if语句免除了
#首先是digit.isdigit(),如果返回false,则不关心第二个条件,因此
#int(数字)仅在我们确认数字实际上是一个数字后才进行检查。
elif digit.isdigit()和int(digit)str:
返回输入('输入一个大于1的整数:')
def main():
多位数()
如果uuuu name uuuuuu='\uuuuuuu main\uuuuuuu':
main()

所以我在工作时看到了这一点,当时它被发布到了CodeReview上。我想回答,但不得不等到回家。我将您的块分为两个块,一个获取输入(我讨厌冗余代码),另一个执行检查并调用输入。我还为数字和非数字添加了一条清晰的错误消息。我在这里发布完整的代码:

# -*-coding: utf-8-*-
# !/usr/bin/python3.6

import sys


def multi_digits():
    digit = get_input()
    x = True

    while x:
        if digit in '23456789':
            print(f'Yes,you have entered {digit}.')
            x = False
        # In elif it looks like int(digit) may throw an error if it isn't a digit but
        # because of the way if statements work this wont happen. The if statement excutes
        # digit.isdigit() first, if it returns false it doesn't care about the second condition so
        # int(digit) only is checked after we confirm digit is actually a digit.
        elif digit.isdigit() and int(digit) <= 1:
            print('Invalid input: Digit was not greater than 1')
            digit = get_input()
        else:
            print('Invalid input: no letters allowed')
            digit = get_input()


def get_input() -> str:
    return input('Enter an integer greater than 1: ')


def main():
    multi_digits()


if __name__ == '__main__':
    main()
#-*-编码:utf-8-*-
# !/usr/bin/python3.6
导入系统
def多位数()
数字=获取输入()
x=真
而x:
如果“23456789”中的数字为:
打印(f'是,您已输入{digit}'
x=假
#在elif中,如果int(digit)不是一个数字,但是
#因为如果语句起作用,这种情况就不会发生。if语句免除了
#首先是digit.isdigit(),如果返回false,则不关心第二个条件,因此
#int(数字)仅在我们确认数字实际上是一个数字后才进行检查。
elif digit.isdigit()和int(digit)str:
返回输入('输入一个大于1的整数:')
def main():
多位数()
如果uuuu name uuuuuu='\uuuuuuu main\uuuuuuu':
main()

非常感谢您的详细回答,这是一种有趣的方法。非常感谢您的详细回答,这是一种有趣的方法。非常感谢您的帮助,并感谢您的详细解释!非常感谢您的帮助,也感谢您的详细解释!