0

How to match positive integer in Python?

match n:
    case >=0:
        print('positive int')

Causes a syntax error


More succinctly than

match n:
    case n if n >= 0:

I want to match all of these cases:

case n is not a non-negative integer
case n == 0
case n == 1
case n > 1
theonlygusti
  • 11,032
  • 11
  • 64
  • 119
  • 3
    Using a guard is the way (although I would put `case int() if n >= 0`). What's the problem? – wim May 22 '23 at 18:26
  • 1
    What version of python are you using? – Daweo May 22 '23 at 18:29
  • 1
    Match is cool when it fits your problem, but if it doesn't fit, remember that everything `match` can do can also be done with good old-fashioned `if`/`else` statements. – Tim Roberts May 22 '23 at 18:43
  • I'm guess this is a toy example, but you can flip things and `match n >= 0` – JonSG May 22 '23 at 18:43
  • If you don't like `match n: case n if n >= 0:` then just write `if n>=0:` – khelwood May 22 '23 at 18:44
  • 1
    Just being pedantic but zero is not a positive number – DarkKnight May 22 '23 at 18:46
  • @wim problem is, feels so defeating to use match statement when it leads to more verbose code than ugly if/elif chains – theonlygusti May 22 '23 at 19:17
  • @JonSG yeah it's just one case. I would like to have cases for all of "n not non-negative int", "n == 0", "n == 1", "n > 1" – theonlygusti May 22 '23 at 19:19
  • You don't have a chain. Maybe if you show us a chain, we can help improve that. – Kelly Bundy May 22 '23 at 19:19
  • @theonlygusti Yes, well this may be a case where an if/elif is just better than structural pattern match (you're checking a value condition, after all, not really matching on any "structure") – wim May 22 '23 at 19:21

0 Answers0