EMZETT.
Login

Function

In short: A function is a named block of code you call with inputs (parameters) and that can deliver a result (return value). It makes code reusable and readable.

In more detail: You write the logic once and call it as often as you like. In Java functions inside classes are called methods.

In detail

def area(width, height=1):
    return width * height
 
print(area(3, 4))  # 12
  • Parameters and arguments: parameters appear in the definition, arguments at the call.
  • Return: return ends the function and delivers a value. Without return Python gives None, Java with void nothing.
  • Scope: variables inside are local.
  • Recursion: a function calls itself, see Recursion.
  • Pure function: same result for same input, no side effects, see Pure function.
  • Higher-order functions: functions as values, see Higher-order function.
  • Names: use a verb (calculateSum), one task per function.

See also: Events, Mathematical functions