Python 不从列表中获取值的函数
我想从列表中获取两个值,然后添加它们。我想用try和except块来做。皮查姆没有问题。但输出显示为“无”或“无”。代码如下:Python 不从列表中获取值的函数,python,list,Python,List,我想从列表中获取两个值,然后添加它们。我想用try和except块来做。皮查姆没有问题。但输出显示为“无”或“无”。代码如下: def tryint(): global mylist try: mylist = list[map(int, mylist)] ans = mylist[0] + mylist[1] return ans except: pass a = input('First value:
def tryint():
global mylist
try:
mylist = list[map(int, mylist)]
ans = mylist[0] + mylist[1]
return ans
except:
pass
a = input('First value: ')
b = input('Second value: ')
mylist = [a, b]
tryint()
我尝试将
tryint()
更改为print(tryint())
,但它只是显示“无”
。也没有错误消息。我将使用您的代码作为改进代码的起点
首先是你的解决方案的问题
# What you are trying to do is supply two parameters
# this is better accomplished by supplying the parameters
def tryint():
global mylist
try:
# As mentioned list is a method call so you need to use ()
mylist = list[map(int, mylist)]
# Try to only put the code you suspect might cause an exception
# in your try/except block.
ans = mylist[0] + mylist[1]
return ans
# Always provide the exception you are expecting or at least `Exception`
# If your code isn't going to handle the exception don't handle it.
except:
pass
a = input('First value: ')
b = input('Second value: ')
mylist = [a, b]
tryint()
接下来,让我们改进您的原始解决方案
# The function now excepts two parameters
def try_int(a, b):
try:
# Only type conversion is in the try block
a = int(a)
b = int(b)
# Only ValueError and TypeError are handled
except (ValueError, TypeError):
return None
# At this point we can assume we have integers and safely
# do the addition.
return a + b
a = input("First value: ")
b = input("Second value: ")
print(try_int(a, b))
现在,我们传入输入并仅解析处理期望值的输入
但我们可以通过立即向用户提供反馈做得更好
def input_int(msg):
# Keep trying until a valid value is added
while True:
value = input(msg)
# Allow the user an out be entering nothing
if not value:
return None
try:
# Return a valid value
return int(value)
except ValueError:
# Provide feedback
print("Expected an integer value, please try again")
a = input_int("First value: ")
if a is None:
exit()
b = input_int("Second value: ")
if b is None:
exit()
# At this point we know we have two integers
print(a + b)
有很多方法可以做你正在做的事情,但我将向你展示你犯错误的地方:-
def tryint():
global mylist
try:
mylist = list(map(int, mylist)) # Here you have to use parrenthesis instead of square brackets.
ans = mylist[0] + mylist[1]
return ans
except Exception as e: # This is how you write exception handling.
pass
a = input('First value: ')
b = input('Second value: ')
mylist = [a, b]
tryint()
输出
First value: 5
Second value: 4
9
不要链接到代码;在问题本身中至少举一个例子来说明你的问题。你在第4行使用大括号而不是圆括号
(
)mylist=list[map(int,mylist)]
应该是mylist=list(map(int,mylist))
在你的用例中使用global
关键字是一种不好的做法,您应该这样做:a=int(输入('First value:')
其次,在不指定异常的情况下,避免使用except
。在本例中,您正在捕获一个SyntaxError
,并默默地忽略它。Python中的默认返回值是None
,因此返回的值就是这个值。您使用的是global,因此每次创建新列表时,它都会打印None,而不需要在此处处理异常。