我遇到的问题是我需要一些代码来加错误,所以如果用户不输入数字,它应该告诉他们他们已经做了些什么错误。下面是我想错误捕获的代码,我不知道如何做到这一点。
if cmd in ('L', 'LEFT'):
Left_position = (int(input("How many places would you like to move left")))
if args:
step = int(args[0])
else:
step = Left_position
y -= step
答案 0 :(得分:0)
这一行:
%labels
如果输入不是可以转换为整数的字符串,则会抛出错误。要捕获它,请使用try块包围它:
Left_position = (int(input("How many places would you like to move left")))
答案 1 :(得分:0)
您可能需要稍微重新排列代码。据我所见,如果没有提供args
,您实际上只想询问用户输入内容。如果是这种情况,以下情况应该有效:
if args:
step = int(args[0])
else:
while True:
try:
Left_position = (int(input("How many places would you like to move left")))
break
except ValueError:
print 'This is not an integer! Please try again'
step = Left_position
y -= step
首先,如果有args
我们使用第一个元素并继续。如果还没有,我们进入一个(可能是无限的)循环,要求用户提供输入。如果这不能作为整数进行包装,则会打印一条错误消息,然后再次询问用户输入值。一旦提供了整数,它就会终止 - 只有在输入没有抛出错误时才能到达break
行。