我想从列表中获取两个值,然后添加它们。我想用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: ')
b = input('Second value: ')
mylist = [a, b]
tryint()
我尝试将tryint()
更改为print(tryint())
,但随后仅显示"None"
。也没有错误消息。
答案 0 :(得分:1)
我将以您的代码作为我们如何改进代码的起点
首先解决您的问题
# 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)
答案 1 :(得分:0)
有很多方法可以完成您正在做的事情,但是我将向您展示出错的地方:-
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