Docy

Python Functions

Estimated reading: 3 minutes 1191 views

Function Overview

In Python, a function is a group of related statements that performs a specific task.

Functions help break our program into smaller and modular chunks. As our program grows larger and larger, functions make it more organized and manageable.

Furthermore, it avoids repetition and makes the code reusable.

 

Above shown is a function definition that consists of the following components.

  1. Keyword def that marks the start of the function header.
  2. A function name to uniquely identify the function. Function naming follows the same rules of writing identifiers in Python.
  3. Parameters (arguments) through which we pass values to a function. They are optional.
  4. A colon (:) to mark the end of the function header.
  5. Optional documentation string (docstring) to describe what the function does.
  6. One or more valid python statements that make up the function body. Statements must have the same indentation level (usually 4 spaces).
  7. An optional return statement to return a value from the function.
				
					def hello(name):
    """
    This function hello to
    the person passed in as
    a parameter
    """
    print("Hello, " + name + ". Good morning!")
greet('Paul')    
				
			

Function Without parameter and Without Return Type

The Below code shows the Snippts of for above example.

				
					def say_hello():
 print("Hello World")

say_hello() 
				
			

Function With parameter and Without Return Type

The Below code shows the Snippts of for above example.

				
					def get_add(a,b):
  res = a + b
  print(res)
get_add(10,20)  
				
			

Function Without parameter and With Return Type

The Below code shows the Snippts of for above example.

				
					def get_string_data():
  return "Hello"
res1 = get_string_data()
print(res1)
				
			

Function With parameter and With Return Type

The Below code shows the Snippts of for above example.

				
					def get_add_from_fun(a,b):
  res = a + b
  return res
res1 = get_add_from_fun(10,20)
print(res1)
				
			

Returning Tuple as return Type From Function

The below example Returning addition , multplication,division and substraction.

and accessing as index.

				
					def return_value(a,b):
  res = a + b
  res2 = a - b
  res3 = a/b
  res4 =  a*b
  return (res,res2,res3,res4)
  
tup_ans = return_value(10,20)
print(tup_ans[0])
print(tup_ans[1])
print(tup_ans[2])
print(tup_ans[3])
				
			

Leave a Comment

Share this Doc
CONTENTS