Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/python-2.7/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 尝试,除非结构不起作用。用户输入整数,如果没有,则给出错误。如何修复?_Python_Python 2.7 - Fatal编程技术网

Python 尝试,除非结构不起作用。用户输入整数,如果没有,则给出错误。如何修复?

Python 尝试,除非结构不起作用。用户输入整数,如果没有,则给出错误。如何修复?,python,python-2.7,Python,Python 2.7,根据我可以从您所写的内容中分解出来的内容,您应该做的第一件事是提示用户输入这样一个列表: 1,2,3,4 因此,您的代码应该这样编写以接受此输入: print ("please enter values as check([x,y,z])to find min and max") def check(iterable): try: (iterable) = int(iterable) except: print("please Enter nu

根据我可以从您所写的内容中分解出来的内容,您应该做的第一件事是提示用户输入这样一个列表:

1,2,3,4

因此,您的代码应该这样编写以接受此输入:

print ("please enter values as check([x,y,z])to find min and max")
def check(iterable):
    try:
        (iterable) = int(iterable)

    except:

        print("please Enter number")

    else:
        print("************************")
    it = iter(iterable)
    first = next(it)     # Raises an exception if the input is empty
    minimum = maximum = cumsum = first
    n = 1
    for x in it:
        n += 1
        cumsum += x
        if x < minimum:
            minimum = x
        if x > maximum:
            maximum = x

    return "min:" + str(minimum), "max:" + str(maximum)
然后,您要做的是使用用户输入调用检查方法:

检查用户输入

在try/except的check方法中,现在必须确定如何转换字符串,如下所示:

user_input = input("please enter values as #,#,# to find min and max ")
为此:

# pure string
"1,2,3,4"
因此,如果您只是这样做:

# list of ints
[1, 2, 3, 4]
为了简化上述内容,您可以使用所谓的列表理解,并在一行中完成这一切:

# Convert to a list of strings by splitting on comma
iterable = iterable.split(',')
# Iterate over array and convert each element to an int
for i, v in enumerate(iterable):
    iterable[i] = int(iterable[i])
你最终会得到你的整数列表。现在,如果您最终提供如下输入:

user_input = input("please enter values as #,#,# to find min and max ")
1、a、5

转换为整数列表的逻辑将失败,因为“a”不是整数,它将输入您的except

之后,您应该能够继续执行其余逻辑,以确定如何获得最大值和最小值

因此,您的代码应该如下所示:

iterable = [int(x) for x in iterable.split(",")]

请输出您当前收到的错误。我只是玩弄了一下你的代码,发现了一些bug,但除此之外,我不知道在那之后你想做什么。请提供更多的上下文,以便我们能更好地帮助您。此外,我不建议您将您的输入作为一种方法。提示用户输入如下列表:1,2,3。然后,将其转换为整数列表,并将其用作您的结构,以执行逻辑以获得最小值和最大值。例如:如果我输入10,20,30 out put is,请输入数字“最小值:10”,“最大值:30”。输出是正确的,但显示的打印错误。您不是在尝试查找最小值和最大值吗?所以你的输入应该只是一个数字列表。比如:454842222,2245345。对吗?正确,但使用try:except:我正在尝试验证用户输入的唯一整数,若用户输入字符串出现错误,请输入数字。我在尝试例外结构上做得很好?谢谢,但我正在做一个学校作业,我必须使用尝试:例外:。有没有办法修复我的代码?您知道try-except结构不起作用的原因吗?正如我在解决方案中解释的,您将iterable=[intx for x in iterable.split]放在try中。但是,正如我提到的,你的代码中还有其他的bug,我在我的解决方案中也强调了这些bug。请仔细阅读我的解决方案。全部都在那里。user_input=input请输入值为,,以查找最小和最大def checkuser_input:try:iterable=[intx for x in iterable.split,]checkuser_input除了:print请只输入数字,其他:print…….我没有得到任何输出。我做错什么了吗?