Functions

  • A function is a block of organized, reusable code that is used to perform a single, related action.
  • A function is a block of code which only runs when it is called.
def function_name(parameters):

   """docstring"""

  statement(s)

  return [expression]

Keyword def that marks the start of the function header.

A colon (:) to mark the end of the function header.

Creating a Function

In Python a function is defined using the def keyword:

def my_func ():
  print(“  I am in Function")

Calling a Function

To call a function, use the function name followed by parenthesis:

my_func()

Parameters

  • Parameters are specified after the function name, inside the parentheses.
  • Add as many parameters as you want, just separate them with a comma
def my_func(country):

  print("I am from " + country)

my_func("India")

my_func("Brazil")

Arbitrary Arguments, *args

  • If you don’t know how many arguments that will be passed into your function –
  • add a * before the parameter name in the function definition.
def my_func(*classes):

  print(classes)

my_func("first", "second", "third")

Keyword Arguments

Arguments with the keyvaluesyntax is said to be keyword arguments.

def my_func(a,b):

  print(a,b)

my_func(a=7,b=8)

Arbitrary Keyword Arguments, **kwargs

  • If you don’t know how many keyword arguments that will be passed into your function –
  • Add two asterisk: ** before the parameter name in the function definition.
def my_func(**classes):

  print(classes['a'])

my_func(a="first", b="second", c="third")

Default Parameter Value

The function call without argument, it uses the default value.

def my_func(lang = "Python"):

  print("I am learning " + lang)

my_func("c++")

my_func("java")

my_func()

Return Values

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

def sqrt(x):
  return x *x

print(sqrt(3))

print(sqrt(5))


You can return the mutiple values in the form of tuple:

def sqrt_cube(x):
  return x *x ,x*x*x

print(sqrt_cube(3))

print(sqrt_cube(5))

Docstrings

  • It is briefly used to explain what a function does.
  • The first string after the function header is called the docstring.
  • This string is available to us as the __doc__ attribute of the function.

0 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *