Computer >> Computer tutorials >  >> Programming >> Python

How to define a function in Python?


A function is a piece of code that is called by name. It can be passed data to operate on (i.e. the parameters) and can optionally return data (the return value). All data that is passed to a function is explicitly passed.

Syntax of defining a function

def function_name():
     #do something

A function is defined using the keyword def following a space and the function_name with parentheses and a colon. The next line contain a indented code block to do something

Method is a function that is associated with an object. In Python, method is not unique to class instances. Any object type can have methods.

It is said that everything in Python is an object. In python, functions too are objects. So they have attributes like other objects. We can also assign new attributes to them, as well as retrieve the values of those attributes. Functions can have even functions written inside them.