Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

How to define a function in Python?

I have two lines of code

class f(): pass
def f(): pass

Which of the two is a function and how do we define a function?


1 Answer
Rajendra Dharmkar

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.

Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.