FUNCTION IN PYTHON

Functions are block of codes that are designed to perform specific task .In this chapter you will study everything about function. If you have to perform a task multiple times throughout, so instead of writing code again and again you can define a function for this task and can call that function whenever we want to perform that same task.

Defining a function

You can define functions according to your requirements. Simple rules to define a function in Python are.

  • Function blocks begin with the keyword deffollowed by the function name and parentheses ( ) every code inside def block is a part of function.
  • You can leave these parentheses empty or any input parameters or arguments should be placed within these parentheses. You can also define parameters inside these parentheses. Keep in mind that the input parameters or argument must be used in function block of codes.

1b

  • The first statement of a function must be the documentation string of the function or docstring. This is optional but you should write this is indication of a good program.
  • The code block within every function starts with a colon (:) and is indented to four spaces or a tab.
  • The statement return is used to get an output and exits a function, optionally passing back an expression to the caller. A return statement with no arguments is the same as return None.

NOTE: return can only be used within a function. The difference between return and print is that The value that is returned by a function can then be further used as an argument passed to another function, stored as a variable, or just printed for the benefit of the human user .Which is not possible by print.

Examples:

1:)

2b.png

2:)

3b

3:)

4b

4:)5b

Leave a comment