简体   繁体   中英

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:

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 .

     index = int(input("Enter an index: "))
  2. You also need to call your function indexcheck . The python interpreter will only execute it's code when you will call it.

  3. if index in lst[index]: is not the right way to check for index value being valid for your list.

  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. You should instead check for ValueError exception (thrown by int(input(...)) if str can't be converted to an int ).

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. 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 :)

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. You need to convert that into an int as all the lst indices are integers.

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM