A function is block of code that are designed to do specific job, in other words functions are nothing but a group of related statements that perform a specific. If we want to perform a particular task that is defined in a function, we want to call the name of that function. There are many built-in functions that comes with python.
The main advantage of using python function is, it avoids repetition and makes high degree of code reusing.
A Function bock must begin with the keyword ” def ” followed by function name and parenthesis(). The code block always comes after a colon(:) and it is indented.
def function_name ([parameter1, parameter2,...]): "block of statements" return [expression]
def sample(): print("Hello")
To call a function we need to specify the function name followed by parenthesis.
def sample(): print("Hello World") sample()
Passing Arguments in Function
Arguments are passed inside the function parentheses, an argument is a type of information. Comma is used to separate more than one arguments.
def sample(name): print("My name is:", name) sample("Neural Beast")
My name is: Neural Beast
Passing multiple arguments
def add(a, b): print("The sum of the value is:", a + b) add(10, 20)
The sum of the value is: 30
return statement is used at the end end of a function and it will return the value to the caller function.
def add(): x = 10 y = 20 z = x + y return(z) print("The sum of the value is", add())
The sum of the value is 30
Keyword arguments will invoke the function after the parameters are recognized by their parameter names. We can also send keyword arguments by syntax “key = value”. The keyword argument value must match with the parameter name.
def my_fun(fname, lname): print("My first name is:", fname, ", and my last name is:", lname) my_fun(fname = "Regu", lname = "Ram")
My first name is: Regu , and my last name is: Ram
These arguments passed to a function at correct positional order.
def my_fun(name): pq = "Hello " + name + "," + " " + "Welcome to Python Tutorial" return pq name = input("Enter your name: ") print(my_fun(name))
Enter your name: regu Hello regu, Welcome to Python Tutorial
When we call a function without any argument, that assumes a default value for that argument.
def info(name , salary = "35,000"): print("Name:", name) print("Salary:", salary) info("Mani", "25,000") info("Ram")
Name: Mani Salary: 25,000 Name: Ram Salary: 35,000
In some instances we may not know number of arguments passed in function, in such case we use variable-length argument.
def prgm(*name): print("Some popular programming languages are:") for i in name: print(i) prgm("Python", "Java", "C#", "HTML", "PHP")
Some popular programming languages are: Python Java C# HTML PHP
If a function is defined it cannot be empty, but you want to create a empty function for some reason, when you run the program it will show error message. To avoid error message we use pass statement.
def my_fun(): pass