Python Functions is a block of statements that return the specific task.
The idea is to put some commonly or repeatedly done tasks together and make a function so that instead of writing the same code again and again for different inputs, we can do the function calls to reuse code contained in it over and over again.
Syntax: Python Functions
Creating a Python Function
We can create a Python function using the def keyword.
Python3
def
fun[]:
print
[
"Welcome to GFG"
]
Calling a Python Function
After creating a function we can call it by using the name of the function followed by parenthesis containing parameters of that particular function.
Python3
def
fun[]:
print
[
"Welcome to GFG"
]
fun[]
Output:
Welcome to GFG
Defining and calling a function with parameters
If you have experience in C/C++ or Java then you must be thinking about the return type of the function and data type of arguments. That is possible in Python as well [specifically for Python 3.5 and above].
Syntax: Python Function with parameters
def function_name[parameter: data_type] -> return_type: """Doctring""" # body of the function return expression
The following example uses arguments that you will learn later in this article so you can come back on it again if not understood. It is defined here for people with prior experience in languages like C/C++ or Java.
Python3
def
add[num1:
int
, num2:
int
]
-
>
int
:
num3
=
num1
+
num2
return
num3
num1, num2
=
5
,
15
ans
=
add[num1, num2]
print
[f
"The addition of {num1} and {num2} results {ans}."
]
Output:
The addition of 5 and 15 results 20.
Some more examples are as follows:
Note: The following examples are defined using syntax 1, try to convert them in syntax 2 for practice.
Python3
def
is_prime[n]:
if
n
in
[
2
,
3
]:
return
True
if
[n
=
=
1
]
or
[n
%
2
=
=
0
]:
return
False
r
=
3
while
r
*
r