LearnWave
Learn it. Master it.

Functions

Writing your own functions

Define and call a function with parameters.

A user defined function is one you write yourself. Its header starts with the keyword def, then the function's name, then its parameters in brackets, and ends with a colon. The body below it is indented; the first statement that is not indented is outside the function. Function names follow the same rules as other identifiers.

For example: def greet(name): print("Hello", name). Defining a function does not run it; it runs only when it is called: greet("Asha") prints Hello Asha.

Two words to tell apart:

  • A parameter is the name in the function header (name, above).
  • An argument is the value passed in the call ("Asha").

When the function is called, the parameter refers to the same object as the argument (they have the same id).

But if the function then assigns a new value to the parameter, for example num = num + 5, the parameter now refers to a new object (a new id), because integers are immutable. The variable passed in from outside is not changed (Program 7-5).

Arguments can be numbers, strings (fullname(first, last)) or lists (myMean(myList)). An argument can even be an expression, which is worked out before the call: greet("Mr " + surname).

A default parameter has a value that is used when no argument is given for it: def greet(name, msg = "Hello"). Then greet("Asha") uses msg = "Hello", while greet("Asha", "Welcome") uses "Welcome". Parameters with defaults must come last in the header: def calcInterest(principal = 1000, rate, time = 5) is an error, because rate, which has no default, comes after one that does.

Parameter in the header, argument in the call.

Practise this lesson

Questions that get harder as you improve, a Tutor that helps without giving the answer away, and progress you can see. Free for every learner.

No account, no email address. Opens the real product.