[英]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:您的代码存在以下问题:
You need to convert the str
object returned by input to int
.您需要将input返回的
str
对象转换为int
。
index = int(input("Enter an index: "))
You also need to call your function indexcheck
.您还需要调用函数
indexcheck
。 The python interpreter will only execute it's code when you will call it. python解释器只会在你调用它时执行它的代码。
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]:
不是检查索引值是否对您的列表有效的正确方法。
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)
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.