-1

If i try to give a function an optional argument, this way it won't work:

def speed(self, max, now):
    self.min = 0
    self.max = max
    if now != None:
        self.now = now
    else:
        self.now = 0
    return self.max, self.now

Can someone help me to understand this and how to do it better? Do i really need the if statement? Maybe there is an easier and faster way with some kind of special argument?

Horst23
  • 60
  • 9
  • It's in a very early step of the official tutorial: [Default Argument Values](https://docs.python.org/3/tutorial/controlflow.html#default-argument-values). – Matthias Apr 03 '16 at 08:38

1 Answers1

2

Use a default argument value to set now to 0 when omitted:

def speed(self, max, now=0):
    self.min = 0
    self.max = max
    self.now = now
    return self.max, self.now

Now the caller can simply omit specifying a value for the now argument:

some_instance.speed(42)

would leave now set to 0.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343