Functions

suggest change

Introduction

Functions in Python provide organized, reusable and modular code to perform a set of specific actions. Functions simplify the coding process, prevent redundant logic, and make the code easier to follow. This topic describes the declaration and utilization of functions in Python.

Python has many built-in functions like print(), input(), len(). Besides built-ins you can also create your own functions to do more specific jobs—these are called user-defined functions.

Syntax

Remarks

5 basic things you can do with functions:

Assign functions to variables:

def f():
  print(20)
y = f
y()
# Output: 20

Define functions within other functions (https://stackoverflow.com/documentation/python/228/functions/8717/nested-functions ):

def f(a, b, y):
    def inner_add(a, b):      # inner_add is hidden from outer code
        return a + b
    return inner_add(a, b)**y

Functions can return other functions

def f(y):
    def nth_power(x):
        return x ** y
    return nth_power    # returns a function

squareOf = f(2)         # function that returns the square of a number           
cubeOf = f(3)           # function that returns the cube of a number
squareOf(3)             # Output: 9
cubeOf(2)               # Output: 8

Functions can be passed as parameters to other functions:

def a(x, y):
    print(x, y)
def b(fun, str):        # b has two arguments: a function and a string 
    fun('Hello', str)
b(a, 'Sophia')           # Output: Hello Sophia

Inner functions have access to the enclosing scope (https://stackoverflow.com/documentation/python/228/functions/3885/closure ):

def outer_fun(name):
    def inner_fun():     # the variable name is available to the inner function
        return "Hello "+ name + "!"
    return inner_fun
greet = outer_fun("Sophia")
print(greet())            # Output: Hello Sophia!

Additional resources

More on functions and decorators: https://www.thecodeship.com/patterns/guide-to-python-function-decorators/

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Functions:
* Functions

Table Of Contents
2 Filter
3 List
4 Functions
7 Loops
22 Reduce
27 Classes
31 Set
42 Tuple
45 Enum
62 Sockets
89 urllib
92 Idioms
104 Stack
105 Profiling
109 Logging
111 os module
118 Mixins
120 ArcPy
126 Arrays
132 2to3 tool
135 Unicode
138 Neo4j
140 Curses
141 Templates
145 heapq
146 tkinter
154 Audio
155 pyglet
157 ijson
160 Flask
161 Groupby
163 pygame
165 hashlib
166 Gzip
167 ctypes
185 pyaudio
186 shelve