06. Python Functions

A function is a block of code which only runs when it is called. You can pass data, known as parameters, into a function. A function can return data as a result.

To create a function in python we use def keyword.

For Example :

def my_function():
     print(“This is my first function“)
    
my_function() # this is used to call the above function

Output
This is my Function

Functions Parameters

Parameters are specified after the function name, inside the parentheses. You can add as many parameters as you want, just separate them with a comma. Information can be passed to functions as parameters.

For Example :
def my_function(fname):
    print(fname + " Gupta")

my_function("Ram")
my_function("Shyam")
my_function("Raju")

Output
Ram Gupta
Shyam Gupta
Raju Gupta

Set value as a Parameter :

If we call the function without parameters, it uses the default value.

For Example:
country_name = input("Enter country Name : ")
def my_function(country = country_name ):
    print("I am from " + country)

my_function()
my_function("Sweden")

Output
Enter country Name : India
I am from India
I am from Sweden

Passing a list as a Parameter :

You can send any data types of parameter to a function (string, number, list, dictionary etc.), and it will be treated as the same data type inside the function.

For Example :
def my_function(fruit):
    for x in fruit:
        print(x)

fruits = ["apple", "banana", "cherry"]
my_function(fruits)

Output:
apple
banana
cherry

Return value as a Parameter :

To let a function return a value, use the return statement:

For Example:
def my_function(x):
    return 5 * x

print(my_function(3))
print(my_function(5))
print(my_function(9))

Output
15
25
45