Python Functions

What are Python Functions?

Python Functions is a block of related statements designed to perform a computational, logical, or evaluative 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. Python Functions

Creating a function

  • The def keyword is used to declare a function.
  • A function name that identifies the function uniquely.
  • We can pass parameters (arguments). It’s optional.
  • An optional return declaration to return a function value.
# create a function 
def fun(): 
    print("Welcome to fullstackadda.com") 
		 
# call a function 
fun() 
Welcome to fullstackadda.com

Function With Arguments:

We can pass values to a function using an Argument.

def fname(lname):
    fullname = "Surya " + lname
    print(fullname)

lname = 'Singam'
fname(lname)
Surya Singam

Returning a Value:

return keyword is used to return a value from the function.

def add(num):
	return num + 2

print(add(2))
print(add(10))
4
12

Function Arguments:

A function can have number of arguments. Arguments are the values passed inside the parenthesis of the function.

def fullname(arg_1, arg_2):
  print(arg_1 + " " + arg_2)

fname = 'Surya'
lname = 'Singam'
fullname(arg_1 = fname, arg_2 = lname)
Surya Singam

In the above example values are passed without using argument names.

  • These values get assigned according to their position.
  • Order of the arguments matters here.
def fullname(arg_1, arg_2):
  print(arg_1 + " " + arg_2)

fname = 'Surya'
lname = 'Singam'
fullname(fname, lname)
Surya Singam

We can pass the Default values also

Example:

def fullname(arg_1 = 'Surya', arg_2 = 'Singam'):
  print(arg_1 + " " + arg_2)


fullname()
Surya Singam

Example 2:

def fullname(arg_1 = 'Vikram', arg_2 = 'Kamal'):
  print(arg_1 + " " + arg_2)

fname = 'Surya'
lname = 'Singam'
fullname(fname)
Surya Kamal

python functions
  1. Python Functions is a block of related statements designed to perform a computational, logical, or evaluative task.
  2. def keyword is used to declare a function.
  3. A function name that identifies the function uniquely.
  4. An optional return declaration to return a function value.