Function In Python

Introduction

 
In this article, I will explain the function in Python. A function is a block of code which only runs when it is called. Function blocks begin with the keyword “def” followed by the characteristic name and parentheses (()). The code block within every feature starts off evolved with a colon (): and is indented. Any enter parameters or arguments have to be positioned inside those parentheses. You also can define parameters inside these parentheses.
 

Creating a function

 
“def” keyword is used to create new functions.
 
Syntax 
  1. def function_name(parameters):  
  2.     """some code"""  
  3.     statement(s)   
Example
  1. def my_function():  
  2.   print("Hello c# corner")  

Calling function

 
To call a function, use the function keyword.
 
Example
  1. def my_function():#function  
  2.   print("Hello c# corner")  
  3. my_function() 
Output
 
 

Arguments

 
Information can be exceeded into functions as arguments. Arguments are unique after the function name, in the parentheses. You can add as many arguments as you want, simply separate them with a comma.
 
Example
  1. def my_function(arg_name):#Arguments name is arg_name.  
  2.   print(arg_name + " c# corner")  
  3. my_function("hello")  
  4. my_function("welcome")  
  5. my_function("hi"
Output
 
 

Number of arguments

 
By default, a function must be known as with the right variety of arguments. This means that if your function expects 2 arguments, you must call the function with 2 arguments.
 
Example
  1. def my_function(arg_name1, arg_name2):#2 arguments  
  2.   print(arg_name1 + " " +arg_name2)  
  3. my_function("hello""c# corner")#2 must call arguments 
Output
 
 

Default parameter value

 
The following example shows a way to use a default parameter value. If we call the function without argument, it makes use of the default value:
 
Example
  1. def my_function(color_name = "yellow"):# Default color_name is yellow.  
  2.   print("I like " + color_name+" color")  
  3. my_function("red")  
  4. my_function("orange")  
  5. my_function()#yellow is displayed on the output screen.  
  6. my_function("pink")  
Output
 
 

Passing a list as an Argument

 
You pass any data type of argument to a function (string, number, list etc.) and it'll be handled because of the same data type in the function.
 
Example
  1. def my_function(number):  
  2.   for x in number: #list  
  3.     print(x)  
  4. number = ["one""two""three"]  
  5. my_function(number)  
Output
 
 

Conclusion

 
In this article, we have seen functions in Python. I hope this article was useful to you. Thanks for reading!


Recommended Free Ebook
Similar Articles