-1

I am writing a function that needs to take in an ordered pair coordinate (represented in a tuple). The problem is that I don't know a way to require it to have exactly two elements in the parameters of the function. Is there a better way to handle this kind of situation (like a better data type to use)? I can't think of anything.

def function(coordinate: tuple):
    pass
Barmar
  • 741,623
  • 53
  • 500
  • 612
Lavaa
  • 25
  • 4

1 Answers1

1

A tuple needs to be of a given length for some non-specific function to be executed properly.

We can check the number of elements in the tuple element by using the len() function on it that comes with python directly. Wrapped in a short if condition we can only execute the said function when we have guaranteed that the given tuple has 2 elements in it. Otherwise we may print a short error message for the user.

if len(your_tuple) == 2:
    function(your_tuple)
else:
    print("Please enter only 2D coordinates")
Stephen Ostermiller
  • 23,933
  • 14
  • 88
  • 109
passwortknacker
  • 121
  • 2
  • 8