-1

I've been reading a book, and got stuck on the topic of optional arguments.

• Can define defaults for arguments that need not be passed

>>> def func(a, b, c=10, d=100):
    print a, b, c, d

>>> func(1,2)
   1 2 10 100            

I don't get this ... how? Spent the hour googling and cannot understand it.

Reading this book and on that topic. I just do not get why func(1,2) gives me 1,2,10,100. I mean, how does it know?

Shadow
  • 8,749
  • 4
  • 47
  • 57
BNS
  • 11
  • 1
  • 4
    Default arguments (thos that have an = sign after them and specify a value) are optional. If you don't specify the value, they take the one defined on the function definition. – Saul Axel Martinez Ortiz Mar 23 '18 at 05:24
  • ah ok. so this is a default thing? If possible, could you give an example on how to use it in practise? Thanks for helping! – BNS Mar 23 '18 at 05:37

2 Answers2

0

The best way to understand topics like this is to experiment in an IDE.

def func(a, b, c=10, d=100):
    pass

If you call func with 2 arguments (like you have in your example) then c and d use their default arguments, which are specified in the function signature above.p

You can override the defaults simply by specifying them - take this example where I'm sending 3 arguments to this function

>>> func(1,2,3)
<<< 1 2 3 100
Shadow
  • 8,749
  • 4
  • 47
  • 57
0

If you don't formally define c and d, the call becomes:

func(1,2,10,100)

If you don't formally define d, the call func(1,2,5) is identical to:

func(1,2,5,100)

Hope that helps...

hd1
  • 33,938
  • 5
  • 80
  • 91