Defining and calling

def stores a function. A call runs it.

def greet(): print('Hi')print('A')greet()print('B')def stores the function under the name greet. The body does not run.prints Athe call: Python jumps into the bodyprints Hi, then goes back to where the call wasprints Bdef stores a function. A call runs it.The lines of the body wait until the name is called, with parentheses. The program printsA, Hi, B: the body runs at the call, not where it is written.

def stores. greet() runs. Output: A, Hi, B.

Defining and calling · Going deeper

Order of definition and call, and naming

CodeGivesNotegreet() before the def lineNameErrorThe name does not exist until def has rungreetthe function itselfNo parentheses: nothing runsgreet()runs the bodyParentheses make the calldef total_price():a valid nameSame rules as variable namesdef 2go():SyntaxErrorA name cannot start with a digitdef f(): with no bodyIndentationErrorA body is required: write pass to leave it emptydef f(): twicethe second one winsA later def replaces the earlier oneA function must be defined before the line that calls it runs.One function may call another that is defined further down, as long as both exist by the time the call happens.

Define before the call runs.

Return values

return hands a value back. print only shows it.

returnsdef add(a, b): return a + bx = add(2, 3)x is 5Nothing is printed. The value comes back to the caller.printsdef show(a, b): print(a + b)y = show(2, 3)y is None5 appears on the screen. Nothing comes back.return hands a value back. print only shows it.A call is replaced by the value the function returns. A function that reaches its endwithout a return statement returns None.

return gives the caller a value. No return gives None.

Return values · Going deeper

More about return

The function bodyThe call givesNotereturn 1, then print(2)1return ends the function at once; the print never runsreturnNoneA bare return returns Noneno return at allNoneSo does reaching the endx * 2NoneWorking a value out is not returning itreturn 1, 2(1, 2)Several values come back as one tupleif n < 0: return 'neg''neg' or 'pos'Several return statements: the firstreturn 'pos'one reached is the one that countsExactly one return runs in any call, and it is the last thing that call does.print(show(2, 3)) prints 5 and then None: the function prints, then print shows what came back.

return ends the function at once.

Check yourself

def f(x): x * 2print(f(3))

What does this print?

Parameters and arguments

Arguments fill parameters by position, or by name

def power(base, exp=2): return base ** expbase and exp are parameters: names in the def line.The values in a call are arguments.power(3)9exp takes its default, 2power(3, 3)27positional: filled left to rightpower(exp=3, base=2)8keyword: any orderpower(2, exp=5)32positional first, then keywordArguments fill parameters by position, or by name.A parameter with a default may be left out of the call. In a call, positional argumentscome first and keyword arguments after them.

Positional, keyword, default.

Parameters and arguments · Going deeper

Invalid calls, and sep and end

def power(base, exp=2):CodeGivesNotepower()TypeErrorbase has no default and got no valuepower(1, 2, 3)TypeErrorMore arguments than parameterspower(2, base=3)TypeErrorbase is given twicepower(exp=2, 3)SyntaxErrorA positional argument after a keyword onedef f(a=1, b):SyntaxErrorParameters with defaults go lastprint('a', 'b', sep='-')a-bsep and end are keyword arguments of print()print('a', end='')a, and no new lineTheir defaults are a space and a new lineEvery parameter must end up with exactly one value.Too few, too many and twice the same are all TypeError, raised when the call runs.

One value per parameter, or TypeError.

*args and **kwargs

* collects extra arguments in a tuple, ** in a dictionary

def total(*args):total(1, 2, 3)123args is the tuple (1, 2, 3)def info(**kwargs):info(name='Ada', age=36)'name': 'Ada''age': 36kwargs is the dictionary {'name': 'Ada', 'age': 36}One star collects extra arguments into a tuple. Two stars, into a dictionary.*args takes any number of positional arguments, even none. **kwargs takes any number ofkeyword arguments: each name becomes a key. The names args and kwargs are only a habit;the stars do the work.

*args is a tuple. **kwargs is a dictionary.

*args and **kwargs · Going deeper

Combining them

def f(a, *args, **kwargs):CallaargskwargsNotef(1, 2, 3, x=4)1(2, 3){'x': 4}a first, the rest are collectedf(1)1(){}Nothing extra: both are emptyf(1, x=4, y=5)1(){'x': 4, 'y': 5}Keywords go to kwargsf()TypeErrora still needs a valuedef total(*args): total(1, x=2) is a TypeError: nothing is there to take a keyword argumentdef f(**kwargs, *args): is a SyntaxError: *args comes before **kwargsThe order in a def line: ordinary parameters, then *args, then **kwargs.

Order: ordinary, *args, **kwargs.

Check yourself

def f(a, b=2, *args): return a + b + len(args)print(f(1, 5, 9, 9))

What does this print?

Scope

A name made inside a function lives only inside it

x = 10def f(): x = 5 print(x)f()print(x)Global namesx is 10f is a functionNames inside this call of fx is 5Printed5the x inside f10the global x, untouchedA name made inside a function lives only inside it.Assigning to x inside f makes a second, local x that hides the global one for the lengthof the call. That is shadowing. When the call ends, the local x is gone.

Local x hides global x. Prints 5, then 10.

Scope · Going deeper

The global keyword, and what goes wrong

x = 10 at the top of the programInside the functionGivesNoteprint(x)10Reading a global name needs nothing specialx = 5a local xAssigning makes a local name; the global stays 10global x, then x = 5the global is 5global says: this name is the global onex += 1UnboundLocalErrorIt assigns, so x is local, and has no value yety = 1, then print(y) outsideNameErrorA local name does not exist outsidedef f(n): n = n + 1caller unchangedA parameter is a local name tooPython decides local or global by one test: is the name assigned anywhere in the function?If it is, the name is local throughout that function, unless a global statement says otherwise.

global x reaches the outer name.

Check yourself

x = 1def f(): global x x = x + 1f()f()print(x)

What does this print?

Lesson complete

You finished “Functions”

Answer the questions along the way to see your score here.

Open in a new tab