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
- def function_name(parameters):
-
- statement(s)
Example
- def my_function():
- print("Hello c# corner")
Calling function
To call a function, use the function keyword.
Example
- def my_function():
- print("Hello c# corner")
- 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
- def my_function(arg_name):
- print(arg_name + " c# corner")
- my_function("hello")
- my_function("welcome")
- 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
- def my_function(arg_name1, arg_name2):
- print(arg_name1 + " " +arg_name2)
- 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
- def my_function(color_name = "yellow"):
- print("I like " + color_name+" color")
- my_function("red")
- my_function("orange")
- my_function()
- 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
- def my_function(number):
- for x in number:
- print(x)
- number = ["one", "two", "three"]
- 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!