-1

I would like to define a function that takes two arguments, with the possibility of a third. I'm fairly certain this isn't possible, but considering the built-in range function has:

range(stop) -> range object
range(start, stop[, step]) -> range object

Maybe it's possible? Or maybe I have the wrong idea because range is actually an immutable sequence type?

For clarity's sake, the same function example(x,y) could be run like example(x,y,z)

Barmar
  • 741,623
  • 53
  • 500
  • 612
adhdj
  • 352
  • 4
  • 17
  • "I'm fairly certain this isn't possible" - did you try reading the [official tutorial's section on defining functions](https://docs.python.org/3.4/tutorial/controlflow.html#more-on-defining-functions)? I'm curious about how much research you actually did. – TigerhawkT3 Jan 21 '16 at 00:23
  • About 6 minutes of searching through stack exchange and zero tutorial reading. – adhdj Jan 21 '16 at 00:27
  • Although I have to admit, I didn't think about using the keywords 'optional' while searching. My fault entirely. – adhdj Jan 21 '16 at 00:28

2 Answers2

1
def example(x, y, z=None):
    if z is None:
        return x + y
    else:
        return x + y + z

then

>>> example(3, 4)
7

>>> example(3, 4, 5)
12
Hugh Bothwell
  • 55,315
  • 8
  • 84
  • 99
1

This is possible through default arguments (sometimes called keyword arguments)...

def example(x, y, z=None):
    ...

In the function, you'd check if z is None to see if it was provided.

You can also use *args here:

def example(x, y, *args):
    ...  # *args is a tuple of all of the rest of the positional arguments.

Here, you could use the len(args) to determine if the third argument was passed.

mgilson
  • 300,191
  • 65
  • 633
  • 696