简体   繁体   English

python3中的异常处理

[英]Exception handling in python3

I was doing one hackerrank challenge via my company website.我正在通过公司网站进行一项 hackerrank 挑战。 The question is a simple ValueError raise exception based on the condition - Given two integers a and b - if a > 150 or b < 100 then raise exception.问题是基于条件的简单 ValueError 引发异常 - 给定两个整数 a 和 b - 如果 a > 150 或 b < 100 则引发异常。 Second condition is if sum of the two integers is greater than 400, then also raise the ValueError exception.第二个条件是如果两个整数之和大于 400,那么也会引发 ValueError 异常。 If no condition satisfies then print "All values in range".如果没有条件满足,则打印“范围内的所有值”。 I have written below code and it passed 7 out of 9 test case.我写了下面的代码,它通过了 9 个测试用例中的 7 个。 Now I am not able to figure where could be my code is failing for those two test cases.现在我无法确定我的代码在这两个测试用例中可能在哪里失败。 It outputs - All values in range - message in the failed test cases.它输出 - 范围内的所有值 - 失败测试用例中的消息。 Can someone point what more I can add to the code to pass the remaining two test cases.有人可以指出我还可以添加到代码中以通过剩余的两个测试用例吗?

def handle_excl():
    a = int(input())
    b = int(input())
    sums = a + b
    
    
    if (a > 150) or (b < 100):
        raise ValueError('Input integers value out of range.')
    elif sums > 400:
        raise ValueError('Their sum is out of range')
    else:
        print('All in range.')

Above is the main code and please help how can I resolve the two failed test cases?以上是主要代码,请帮助我如何解决两个失败的测试用例?

This is in response to a comment I made about the fact that elif and else conditions are unnecessary in this case:这是为了回应我关于在这种情况下不需要 elif 和 else 条件这一事实的评论:

def checkvals(a, b):
  if (a > 150) or (b < 100):
    raise ValueError('Input integers value out of range')
  if a + b > 400:
    raise ValueError('Sum out of range')
  print('All in range')

Your code is correct, you just have to remove the fullstop(.) sign in this line-> print("All in range.")您的代码是正确的,您只需要删除这一行中的句点 (.) 符号-> print("All in range.")

def handle_excl():
    a = int(input())
    b = int(input())
    sums = a + b

    if (a > 150) or (b < 100):
        raise ValueError('Input integers value out of range.')
    elif sums > 400:
        raise ValueError('Their sum is out of range')
    else:
        print('All in range')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM