如何跳过忽略错误并测试另一个条件python

2024-05-17 19:56:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前有以下代码。如果in1不是整数我目前面临的问题是,我的程序无法通过raisevalueerror行。你知道吗

def test(in1):

  if not isinstance(in1, int):
    raise ValueError('error')

如果有人有任何解决这个问题的方法,我会非常感激,谢谢


Tags: 方法代码test程序ifdefnot整数
1条回答
网友
1楼 · 发布于 2024-05-17 19:56:02

尝试先将in2转换为整数:

def test(in1, in2, in3):

  if not isinstance(in2, int):
      try:
          in2=int(in2)
      except:
          raise ValueError('error')

  elif in2 == 1:
    in1 = in1[-len(in3):] + in1[:-len(in3)]
  print(in1)

test("supermarket","3","cash")
test("supermarket",3,"cash")

输出:

supermarket
supermarket

相关问题 更多 >