Tutorial by Examples

Using the def statement is the most common way to define a function in python. This statement is a so called single clause compound statement with the following syntax: def function_name(parameters): statement(s) function_name is known as the identifier of the function. Since a function def...
Functions can return a value that you can use directly: def give_me_five(): return 5 print(give_me_five()) # Print the returned value # Out: 5 or save the value for later use: num = give_me_five() print(num) # Print the saved returned value # Out: 5 or use the value f...
Arguments are defined in parentheses after the function name: def divide(dividend, divisor): # The names of the function and its arguments # The arguments are available by name in the body of the function print(dividend / divisor) The function name and its list of arguments are called...
Optional arguments can be defined by assigning (using =) a default value to the argument-name: def make(action='nothing'): return action Calling this function is possible in 3 different ways: make("fun") # Out: fun make(action="sleep") # Out: sleep # The argumen...
One can give a function as many arguments as one wants, the only fixed rules are that each argument name must be unique and that optional arguments must be after the not-optional ones: def func(value1, value2, optionalvalue=10): return '{0} {1} {2}'.format(value1, value2, optionalvalue1) Wh...
Arbitrary number of positional arguments: Defining a function capable of taking an arbitrary number of arguments can be done by prefixing one of the arguments with a * def func(*args): # args will be a tuple containing all values that are passed in for i in args: print(i) fun...
There is a problem when using optional arguments with a mutable default type (described in Defining a function with optional arguments), which can potentially lead to unexpected behaviour. Explanation This problem arises because a function's default arguments are initialised once, at the point whe...
The lambda keyword creates an inline function that contains a single expression. The value of this expression is what the function returns when invoked. Consider the function: def greeting(): return "Hello" which, when called as: print(greeting()) prints: Hello This can ...
First, some terminology: argument (actual parameter): the actual variable being passed to a function; parameter (formal parameter): the receiving variable that is used in a function. In Python, arguments are passed by assignment (as opposed to other languages, where arguments can be passed by...
Closures in Python are created by function calls. Here, the call to makeInc creates a binding for x that is referenced inside the function inc. Each call to makeInc creates a new instance of this function, but each instance has a link to a different binding of x. def makeInc(x): def inc(y): ...
A recursive function is a function that calls itself in its definition. For example the mathematical function, factorial, defined by factorial(n) = n*(n-1)*(n-2)*...*3*2*1. can be programmed as def factorial(n): #n here should be an integer if n == 0: return 1 else: ...
There is a limit to the depth of possible recursion, which depends on the Python implementation. When the limit is reached, a RuntimeError exception is raised: def cursing(depth): try: cursing(depth + 1) # actually, re-cursing except RuntimeError as RE: print('I recursed {} times!'....
Functions in python are first-class objects. They can be defined in any scope def fibonacci(n): def step(a,b): return b, a+b a, b = 0, 1 for i in range(n): a, b = step(a, b) return a Functions capture their enclosing scope can be passed around like any other...
Functions allow you to specify these types of parameters: positional, named, variable positional, Keyword args (kwargs). Here is a clear and concise use of each type. def unpacking(a, b, c=45, d=60, *args, **kwargs): print(a, b, c, d, args, kwargs) >>> unpacking(1, 2) 1 2 45 60 ()...
All parameters specified after the first asterisk in the function signature are keyword-only. def f(*a, b): pass f(1, 2, 3) # TypeError: f() missing 1 required keyword-only argument: 'b' In Python 3 it's possible to put a single asterisk in the function signature to ensure that the rema...
One method for creating recursive lambda functions involves assigning the function to a variable and then referencing that variable within the function itself. A common example of this is the recursive calculation of the factorial of a number - such as shown in the following code: lambda_factorial ...

Page 1 of 1