简体   繁体   English

如何使用异常处理在python中打印指定索引中的数字是正数还是负数?

[英]How can I print whether the number in the specified index is positive or negative in python using exception handling?

My aim: Declare a list with 10 integers and ask the user to enter an index.Check whether the number in that index is positive or negative number.If any invalid index is entered, handle the exception and print an error message.(python) My code:我的目标:声明一个包含 10 个整数的列表,并要求用户输入一个索引。检查该索引中的数字是正数还是负数。如果输入了任何无效的索引,则处理异常并打印错误消息。(python)我的代码:

try:
    lst=[1,2,3,4,5,-6,-7,-8,9,-10]
    index=input("Enter an index : ")
    def indexcheck(lst, index):
        index=input("Enter an index")
        if index in lst[index]:
            if lst[index]>0:
                print('Positive')
            elif lst[index]<0:
                print('Negative')
            else:
                print('Zero')

except IndexError:
    print("Error found")

Where am I going wrong and how can I correct it?我哪里出错了,我该如何纠正? I am a beginner.Please do help.我是初学者,请帮忙。 Thanks in advance.提前致谢。

There are following issues with your code:您的代码存在以下问题:

  1. You need to convert the str object returned by input to int .您需要将input返回的str对象转换为int

     index = int(input("Enter an index: "))
  2. You also need to call your function indexcheck .您还需要调用函数indexcheck The python interpreter will only execute it's code when you will call it. python解释器只会在你调用它时执行它的代码。

  3. if index in lst[index]: is not the right way to check for index value being valid for your list. if index in lst[index]:不是检查索引值是否对您的列表有效的正确方法。

  4. Since you are already trying to check for index validity and your intentional was to use only valid indexes on your list, so you can't get IndexError exception.由于您已经在尝试检查索引有效性并且您有意仅在列表中使用有效索引,因此您无法获得IndexError异常。 You should instead check for ValueError exception (thrown by int(input(...)) if str can't be converted to an int ).如果str无法转换为int您应该检查ValueError异常(由int(input(...))抛出)。

I have tired to modify your code as less as possible.我已经厌倦了尽可能少地修改您的代码。 My intention is to show the right way of doing things with your code.我的目的是展示用你的代码做事的正确方法。 Try this:尝试这个:

try:
    lst = [1,2,3,4,5,-6,-7,-8,9,-10]
    def indexcheck(lst):
        index = int(input("Enter an index: "))
        if 0 > index >= len(lst):
            print("Index: %d not found" % (index))
            return
        if lst[index] > 0:
            print('Positive')
        elif lst[index] < 0:
            print('Negative')
        else:
            print('Zero')
    indexcheck(lst)

except ValueError:
    print("Value entered can't be converted to an int")

You don't have to put the try/except block around the entirety of your code.您不必在整个代码中放置 try/except 块。 For instance, you could do the following:例如,您可以执行以下操作:

lst=[1,2,3,4,5,-6,-7,-8,9,-10]
index=int(input("Enter an index : "))

try:
    if lst[index] > 0:
        print ("Positive")
    else:
        print ("Negative")
except:
    print ("Index our of range")

You could wrap this in a function:您可以将其包装在一个函数中:

def check_index(lst, index):
    try:
        if lst[index] > 0:
            print ("Positive")
        else:
            print ("Negative")
    except:
        print ("Index our of range")

PS I considered 0 as negative, you can change that part yourself :) PS 我认为 0 为负数,您可以自己更改该部分:)

Here's the code:这是代码:

def indexcheck(lst, index):
    if 0 <= index < len(lst):
        if lst[index] > 0:
            return 'Positive'
        elif lst[index]<0:
            return 'Negative'
        else:
            return 'Zero'
    else:
        raise Exception("Index out of range")


lst = [1, 2, 3, 4, 5, -6, -7, -8, 9, -10]
index = int(input("Enter an index : "))
indexcheck(lst, index)
  1. You are defining a function but not calling it.您正在定义一个函数但没有调用它。
  2. input("Enter an index : ") returns a string. input("Enter an index : ")返回一个字符串。 You need to convert that into an int as all the lst indices are integers.您需要将其转换为int因为所有lst索引都是整数。

The working code is given below:工作代码如下:

def fun():
    try:
        lst=[1,2,3,4,5,-6,-7,-8,9,-10]
        index=int(input("Enter an index : "))
        def indexcheck(lst, index):
            if lst[index]>0:
                print('Positive')
            elif lst[index]<0:
                print('Negative')
            else:
                print('Zero')

        indexcheck(lst, index)

    except IndexError:
        print("Error found")

fun()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使Python打印整数是正数还是负数 - Make Python print whether a integer is positive or negative 如何通过使用python在excel中查找指定数据(正数首先出现而负数在附近) - How to find specified data in excel by using python (positive number first appeared and negative number nearby) 如何在列表中的正数之后打印第一个负数? - How can I print first negative number after a positive number in a list? 如何打印正索引和负索引及其相应元素? - how can I print both positive and negative indexes together with its corresponding element? 将Python中的负索引转换为正索引 - Convert negative index in Python to positive index 如何知道python中2个列表中相同索引处的值是正面还是负面相同? - how to know values at the same index in 2 lists in python are the same in positive or negative? 如何将负数转换为正数? - How to convert a negative number to positive? 如何正确分类图像中正(亮)圈和负(暗)圈的数量 - How can I correctly classify the number of positive (bright color) circles and negative (dark color) circles in the image 如何检查列表中的整数或浮点数是正号还是负号? - How can I check if an integer or float number in a list is positive or negative in sign? 如果条形编号为负数而正数条形为另一种颜色,我如何为图表设置条件格式? xlxswriter - how can i have conditional formatting for a graph if the bar number is negative and another colour for positive bar? xlxswriter
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM