Python Function

There are some cases where a  certain piece of code needs to perform an action several times. But writing the code at all times where the action is necessary increased the code complexity. So we need an alternative to these problems. Python function provide good solutions to this. So let first have a look over

What is a python function?

The function is a block of code which provides the re-usability. These functions allow the proper modularity for the application in a single action. Python offers built-in functions like Print(). Besides, it allows the users to create the function of our own. These functions are knows as the  User-defined functions.

So my readers till now we have what is a function in learn to code python, So now let us have a look over how to define a function.

Rules for defining a function:
  • The function name should start with a def keyword followed by a function name and parenthesis.
  • All the arguments and input parameters should be placed within the parenthesis
  • The functional code within the function should start with the colon :
  • To exit the function, we use the return (this is also used to send object return to the caller)

 Syntax :

def func_name():

statements()

retrun

Ex:

I would like to explain this with an  addition example

def sum(x,y):

z=x+y

return z

Sum (20, 30)

 Output :

50

So in learn python for beginners, we will discuss how to call (or) how to invoke a function.

Function calling (or) function invoking :

The definition of the function would offer the name and specify the values/ parameter that should be included in a function. Once the function has given the basic structures,  it can be executed by calling from the other functions. Besides this can also be called from the python prompt.As discussed above in Function calling, we can pass value by reference (or) pass by value.

 Syn :

Def function_name():

Print()

Function_name()

Example:

Def first():

Print(‘this is the first function’)

First()

Arguments :

These are the values passed in a function. The arguments are of 5 types.

Default arguments:

 These arguments provide a default value if nothing is provided in the function call. These have to be defined in the function definition.

Keyword arguments :

These arguments are related to the calls. With the help of parameter name caller identify the arguments

This allows skipping arguments.

Required arguments :

These are those arguments that are passed to the function in the correct order according to their positions.

Variable- length arguments :

In some cases, we need to write functions, that accept more parameter than they defined. These arguments are otherwise called as These arguments as a variable – length arguments.

also check  How can you check the quality of the python code

scope of the variable :

The variables declare this have different scopes. let us discuss the usage in detailed.

Local variable :

The variables that can be accessed in a function, where it is declared. It cannot be accessed outside the body. Let us discuss the code with an example.

Ex:

def first():

a = ‘im the lcoal variable’

print(a)

first()

Output :

Im the local variable

EX :2:

def first():

a  = ‘im the lcoal variable’

print(a)

first()

print (a)

Output :

im the local variable

name ‘a’ is not defined

Reason :

 Since variable ‘a’  is defined in a function ,it cannot accessed outside the function.So we have experienced an error.

So to overcome this feature, we use Global variables

 Global Variable :

This is unlike the local variable. This can be accessed globally. The variables that are declared ones can be accessed many functions.

 Ex:

def f():

s= ‘im the local function. I overrided the global function’

print (s)

a= ‘im the local function, i cannot  access the outside the function f’

print (a)

# Global scope

b= “Since, I am the global function, print S is called before the function, and first  exected”

print(s)

f()

a= ‘i love python’

print (a)

Output :

Since, I am the global function, print S is called before the function,and first  exected

im the local function. I overrided the global function

im the local function, I cannot  access the outside the function f

i love python

Ex:2

def f():

s= ‘im the local function. I overrided the global function’

print (s)

# Global scope

b = “Since, I am the global function, print S is called before the function,and first  exected”

print(s)

f()

print (b)

Output :

Since, am the global function, print S is called before the function,and first  exected

im the local function. I overrided the global function

am the global function, print S is called before the function,and first  exected

 Note :

If you have observed the code, when the control comes outside the function, the value of the global variable will be stored.

Q: How do we access the local variable value outside the function?

So far, we have discussed the local variables as well as the global variables. But as shown above, if the control is a function outside, the memory/cache stores only the global variable

So to store the local variable value outside the memory we need to make use of Global function. let us consider the working of the global function with an example.

Ex:

def f():

global b

s= ‘im the local function. I overrided the global function’

print (b)

# Global scope

b = “Since, I am the global function, print S is called before the function, and first  exected”

print(s)

f()

print (b)

Output :

Iam the global function, since print S is called before the function, I was exected

im the local function. I override the global function

im the local function. I overrided the global function

So now let’s move to the next topic recursion.

Recursion:

So till now, we have seen how to call the function and also how to pass the variables to it. But we cannot say exactly the function may call the other functions. In some cases, function calls the same functions too. This phenomenon is nothing but recursion.

In simeple words factorial is a good example of recursion.

Ex:

def calc_factorial(x):

“””This is a recursive function

to find the factorial of an integer”””

if x == 1:

return 1

else:

return (x * calc_factorial(x-1))

num = 10

print(“The factorial of”, num, “is”, calc_factorial(num))

So far, we have discussed what is a function, how to define the function and the types of functions? Now its time to discuss some functions in python.

_Init_:

After the class creation __init__ called . It also known as constructor

Self :

Self represents the instance of the class. In python, using the self keyword, we can access the python class attributes and methods.

In the best way to learn to learn python, these keywords play a prominent role. So now let us have a look over the syntax and example

Syntax:

class SomeClass:

variable_1 = “ This is a class variable”

variable_2 = 50    #this is some other variable

def __init__(self, param1, param2):

self.instance_var1 = param1

#instance_var1 is a instance variable

self.instance_var2 = param2

#instance_var2 is a instance variable

Ex:

class Rectangle:

def __init__(self, length, breadth, unit_cost=0):

self.length = length

self.breadth = breadth

self.unit_cost = unit_cost

def get_perimeter(self):

return 2 * (self.length + self.breadth)

def get_area(self):

return self.length * self.breadth

def calculate_cost(self):

area = self.get_area()

return area * self.unit_cost

# breadth = 50 cm, length = 70 cm, 1 cm^2 = Rs 1500

r = Rectangle(50, 70, 1500)

print(“Area of Rectangle: %s cm^2” % (r.get_area()))

print(“Cost of rectangular field: Rs. %s ” % (r.calculate_cost()))

Here in the above example, all the values that were the length, breadth, and unit_cost were assigned to self.length, self.breadth, and self.unit_cost  respectively. And all the operations were done using the self.variable_name (variable _name may be length,breadth and unit_cost).

Hope you got a better idea regarding _init_ and self. 

Doc strings :

It provides a convenient way of associating documentation, with python modules, classes, functions, and methods. doc_ strings can be accessed by  __doc__ attribute. 

How to define a doc string?

Usually, the doc string line should start with a capital letter.

The first line should be a short description

And we should not write the object name.

Ex:

def my_function():

“””Demonstrate docstrings and does nothing really.”””

return None

print (“Using __doc__:”)

print (my_function.__doc__)

Out Put :

Using __doc__:

Demonstrate docstrings and does nothing really.

I Suggest you to practice the one line Doc string, multi-line doc strings and Doc string in classes. If you fin difficulty clarify your doubts at best online python course.

Date and Time :

The other function that we need to discuss is Date and time. Let us discuss briefly it.

A date in python is a data type of its own. But we can import a module, named date time to work with dates as well as date objects.

Ex:

import datetime

x = datetime.datetime.now()

print(x)

Output :

2019-02-13 13:12:25.389359

It means it displays the result in a year, month, day, hour, minute, second and microsecond.

How to get the calendar?

Python allows you to print the calendar of the month. The following code allows you to print the calendar of the month.

Ex :

from datetime import datetime

import calendar

cal = calendar.month(2019, 2)

print (‘Here is the calendar:’)

print (cal)

Output :

How to display the year and weekday of the week

import datetime

x = datetime.datetime.now()

print(x.year)

print(x.strftime(“%A”))

Output :

2019

Wednesday

How to display the name of the month?

import datetime

x = datetime.datetime(2018, 6, 1)

print(x.strftime(“%B”))

Output :

June

Now let us have a look over some Date and time legal formats.

Directive Description Example
%a Weekday, short version Wed
%A Weekday, full version Wednesday
%w Weekday as a number(0-6). Weekday starts from Sunday 3

 

%d Day of the month (1-31) 13
%b Month name(short version) Feb
%B Month name(full version) February
%m Month as a number(1-12) 2
%y Year, short version 19
%Y Year, Full version 2019
%H Hour (00-23) 15
%I Hour(00-12) 3
%p AM/PM PM
%M Minute(00-59) 27
%S Second(0-59) 27
%f Microsecond(000000-999999) 270893
%z UTC offset +0100
%Z Timezone CST
%j Day number of the year 44
%U Week number of the year. Sunday as the first day of the week 22
%W Week number of the year. Monday as the first day of the year 52
%c The local version of date and time Wed Feb 13 15:10:54 2019
%x The local version of date 02/03/2019
%X The Local version of time 15:14:17

 In the previous topics, we have discussed the python list, python tuples, and python dictionaries. And these perform the Slicing operation. Basically, these tuples/dictionaries contain a group of elements. But in all the cases, we do not require to display the complete list of elements. (It is enough to display only some elements). In those cases, we use a concept of slicing.

Slicing:

A slice object specifies how to slice the sequence. Here, you can specify where to start and where to end the sequence. The slice function returns a slice object.

Syntax:

Slice (start , end ,step)

Parameter Description
start An integer specifying the position to start slicing. Its default value is zero. It is optional
End An integer specifying the end of the slicing
Step An integer specifying  the step of slicing. Its default value is one

 Ex:

temp= (“Online”, “IT”, “Guru”, “Training”, “Education”, “and”, “placement”, “centre”)

x = slice(3, 5)

print(temp[x])

Out put :

(‘D’, ‘E’)

Subscribe
to our newsletter

Drop Us A Query

Trending Courses
  • Pega testing training
    PEGA Testing Training
  • Today application testing is the deciding factor to launch the application into the market. And people do not launch the application unless it goes true.

  • blockchain course
    Blockchain Online Course
  • Today many people were enthusiastic, to know the exact details of things happening around him. This can get the proper knowledge on Blockchain.

  • ethical hacking course
    Ethical Hacking Certification Course
  • Zeal to learn ethical hacking is common among college students and IT professionals. Because everybody wants to secure their system from cyber attacks.

  • python training
    Python Online Training
  • Python is a dynamic interrupted language which is used in wide varieties of applications. It is very interactive object oriented and high-level programming language.

  • Tableau Training
    Tableau Training
  • Tableau is a Software company that caters interactive data visualization products that provide Business Intelligence services. The company’s Head Quarters is in Seattle, USA.

  • what is pega
    PEGA Online Training
  • Pega Systems Inc. is a Cambridge, Massachusetts based Software Company. It is known for developing software for Customer Relationship Management (CRM) and Business process Management (BPM).


100% Secure Payments. All major credit & debit cards accepted.