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

Shreya Reddy :

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.

Mathieu :

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 chech_index(lst, index):
    try:
        if lst[index] > 0:
            print ("Positive")
        else:
            print ("Negative")
    except:
        print ("Index our of range")

P.S. I considered 0 as negative, you can change that part yourself :)

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=367674&siteId=1