Notification texts go here Contact Us Buy Now!

4. Python Programming - Essentials | 4.4 Functions

 

Functions

In programming, a function is a self-contained block of code that encapsulates a specific task or related group of tasks. They run only when specifically called within the program. The prime advantage of functions is the code re-usability and manageability.

 

  Built in Functions in Python

In previous lessons of this course, you have been introduced to some of the built-in functions provided by Python.  print() for example, takes five arguments, only the first is frequently used, and displays the passed string/object on the screen, unless specified to be written into a file. Function input() lets you insert values to the program.

In these builtin functions, the code that accomplishes the task is abstracted out from you and you only need to know the function arguments and the values it's returning, whenever you are going to call it.

 

  User Defined Functions

You can define your own functions to manage and reuse the lines of code you may need within the program.

 

Function Calls and Definition

The usual syntax for defining a Python function is as,

def <function_name>([<parameters>]):
    <statement(s)>

 

def is the keyword that we use to inform Python of the new function we re creating. Function name is the identifier, and this should also follow the naming conventions that we learnt in variables tutorial. The component named <parameter/s> is optional. It is there we provide the parameters to be passed to the function, if any are needed. The indented <statement/s> compose the function body defining the functionality. We include the statements we need executed when the function is called , there.

The syntax for calling a Python function is as,

<function_name>([<arguments>]):

<arguments> are the values that are passed into the function when it is called. They correspond to the <parameters> in the particular function definition.

Here is a sample function definition.

def my_fucntion():
    print(“Hello from a function!”)

Calling this function as my_function() would execute the function body statements and print a line on screen as Hello from a function!

>>> def my_function():
    print("Hello from a function")

>>> my_function()
Hello from a function

Even if you define a function that does not need taking any arguments, the parentheses are a must.

 

 

  Empty Functions

Sometimes you may need to define a function with an empty body, one that does nothing. This is usually to act as a placeholder until the function is implemented at a later level. Anyhow, when you define empty functions you must use the pass statement.

def empty_func():
   pass
empty_func()

Passing Arguments

Most of the functions you will be defining needs data being passed into it, in the form of parameters. In Python there are varied ways of function invocation.

  Positional Arguments

Positional Arguments is the most common and straightforward method of passing arguments to function. During the definition of the function you also specify the list of parameters that the function accepts, within parenthesis as below.

#Function definition
def calc(qty, item, price):
    print("The"+ item + " cost/s" , (qty*price), "rupees")

#Function Call
calc(2,'Apples', 20)        

The Apples cost/s 40 rupees

This method calc() is here called with 2, Apples,20 as arguments, in correspondence to the defined parameters, qty,item,price. What you should keep in mind is that with positional arguments, the arguments you pass in the function call and the parameters defined in the function should match in order and number.

Although positional arguments are the most straightforward way to pass data to a function,. You are not allowed to leave any out, or specify extra ones when calling the function, as shown in the following.

def calc(qty, item, price):
      print("The "+ item + " cost/s" . (qty*price), "rupees")

calc(2,'Apples', 20,50)

TypeError: calc() takes 3 positional arguments but 4 were given

  Keyword Arguments

Another way to call the functions is with Keyword arguments where you can specify the passed arguments in <keyword>=<value> format.The <keyword> is what you have provided as the parameter and the value is the actual parameter value you want to pass to the function.

The previous function calc() can also be called with keyword arguments as shown below.

def calc(qty, item, price):
      print("The "+ item + " cost/s", (qty*price), "rupees")

calc(qty=5, item="Oranges",price=10)

 

The speciality with Keyword arguments use is that you don’t need to worry about the argument order like you did previously. As each argument you pass is specified with the parameter/Keyword name Python can identify the values even though the order is messed up.

However, here too, the number of arguments should be equal to what is defined in the function.

  Default Parameters

In Functions defined with default parameters, if no argument is passed during the function call, a predefined default parameter is passed as the value for the function. Such parameters are specified in Python function definition in the <name>=<value>, format. This <value> becomes a default value for that parameter.

def greet(name, msg="How are you?"):
   print(name + ", " msg)

greet("John")
greet("John", "Good Evening")
greet("Good Evening")

John, How are you?
John, Good Evening
Good Evening, How are you?
>>>

You can see in the above examples, when any arguments are left out, the function assumes its default value.

New text

  Arbitrary Arguments

In some function definitions, you will not know the exact number of arguments that need to be passed to the function during its call. In such situations you can use the *args syntax with the function definition.

def add(*args):
    #sum() is an inbuilt function to sum up a list
    total=(sum(args))
    print("The sum : " ,total)

def greet(msg, *names):
    for name in names:
        print(msg + ", " + name)

#Calling add() function
add(1,4,5)

#Calling greet() function
greet("Hello","John","Maggie","Lucy")

The sum:10
Hello, John
Hello, Maggie
Hello, Lucy

>>>

  The return Statement

A return statement in a Python function can serve either terminate the function immediately and pass the control of execution back to the caller OR pass any required data back to the function caller.

In the first situation we just include the return statement but whenever we are returning a specific value/s from the function we need to mention that together with the return statement. And these returned values can be captured by another function or a variable as the program prefers.

A Python function can return any type of object. And Python allows returning multiple values, separated by commas. There they are actually returned as a tuple.

def calc(quantity, price):
    return quantity*price

print("The Price is " , calc(10,750))

The Price is 7500
>>>

  Docstrings

The Docstrings are supposed to provide detailed documentation for a function. It can be composed of the function’s purpose, its list of arguments, its return values and any other information that the programmer thinks important to mention.

A docstring is added as the first statement in the body of a Python function. These need to be within quotation marks and the recommended convention to use the triple-quotes (in double quotes) as “”” docstring “”” . These can be on a single line or be multi lined as well. If the docstring fits on a single line both the opening and closing quotes should be on the same line.

We can also view the docstrings of built-in and user defined functions using the __doc___ attribute.

def calc(quantity, price):
    """Returns the product of quantity and price"""
    return quantity*price

print (calc.__doc__)

Returns the prodcut of quantity and price
>>>

 

Docstrings seem to be similar to the commenting. But the difference is that comments are not accessible for viewing during the program execution. And the purpose docstrings serve is different, they are in fact a more useful way of commenting.

>>> print(print.__doc__)
print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)

Prints the values to a stream, or to sys.stdout by default.
Optional keyword arguments:
file:  a file-like object (stream); defaults to the current sys.stdout.
sep:   string inserted between values, default a space.
end:   string appended after the last value, default a newline.
flush: whether to forcibly flush the stream.
>>>

About the Author

Coding | Riding | Music, Embracing the beauty of code, the thrill of the ride, and the rhythm of life. Let's explore the journey together!

إرسال تعليق

Cookie Consent
We serve cookies on this site to analyze traffic, remember your preferences, and optimize your experience.
Oops!
It seems there is something wrong with your internet connection. Please connect to the internet and start browsing again.
AdBlock Detected!
We have detected that you are using adblocking plugin in your browser.
The revenue we earn by the advertisements is used to manage this website, we request you to whitelist our website in your adblocking plugin.
Site is Blocked
Sorry! This site is not available in your country.
Code Copied!