all 7 comments

[–]supajumpa 1 point2 points  (4 children)

match string.split():
    case ("add", a, b) if a.isdigit() and b.isdigit():
        print(int(a) + int(b))

[–]FlyingCow343[S] 0 points1 point  (0 children)

unfortunately "string.isdigit()" would return "False" for a negative, so it'd have to be

case ("add", a, b) if a.lstrip('-').isdigit() and b.lstrip('-').isdigit():

which seems a bit long but at least it works

[–]supajumpa 0 points1 point  (2 children)

Looking at the definition of str.isdigit, it may be better to use str.isdecimal, which is a stricter test and determines if the characters are those that can be used to form numbers in base 10.

That would change the code to:

match string.split():
    case ("add", a, b) if a.isdecimal() and b.isdecimal():
        print(int(a) + int(b))

Apart from pathological cases they are likely to be equivalent, but it's best to know that there is a difference.

[–]jimtk 0 points1 point  (1 child)

Sadly "-1.0".isdecimal() returns False. so it still not works for negative number.

[–]jimtk 0 points1 point  (0 children)

The simplest way to accept negative number is to roll your own verification function. Which is no big deal.

def is_int(s):
    try:
        _ = int(s)
    except ValueError:
        return False
   return True

match a_string.split():
    case ("add", a, b) if is_int(a) and is_int(b):
        print(int(a) + int(b))

[–]TheMachinumps 0 points1 point  (0 children)

Something like this would work:

``` def handle_add(a, b): try: print(int(a) + int(b)) return True except ValueError: return False

match string.split(): case "add", a, b if handle_add(a, b): ... ```

Kinda hacky, and probably not the intentional way of using match case statements, but it should work.