-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?

1
  • It's in a very early step of the official tutorial: Default Argument Values. Commented Apr 3, 2016 at 8:38

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.