21 captures
01 May 2019 - 03 Aug 2025
Aug SEP Oct
19
2019 2020 2021
success
fail

About this capture

COLLECTED BY

Collection: Common Crawl

Web crawl data from Common Crawl.
TIMESTAMPS

The Wayback Machine - http://web.archive.org/web/20200919025300/https://data-flair.training/blogs/python-function/
 

DataFlair

Blogs
Big Data Tutorials
Hadoop Tutorials
Spark Tutorials
Data Science Tutorials
Python Tutorials
R Tutorials
Machine Learning Tutorials

        
Blog Home
Data Science
Data Science Tutorials
Machine Learning Tutorials
Big Data
Big Data Tutorials
Hadoop Ecosystem Tutorials
Apache Spark Tutorials
Apache Flink Tutorials
Apache Kafka Tutorials
Python Tutorials
Python Tutorials
TensorFlow Tutorials
Pandas Tutorials
Django Tutorials
BI Tutorials
Tableau Tutorials
Power BI Tutorials
QlikView Tutorials
Qlik Sense Tutorials
SAP HANA Tutorials
SQL & NoSQL
SQL Tutorials
Cassandra Tutorials
MongoDB Tutorials
IoT Tutorials
R Tutorials
SAS Tutorials
AI Tutorials
Categories
Programming
C Tutorials
Scala Tutorials
Java Tutorials
Spring Tutorials
Cloud
Cloud Computing Tutorials
AWS Tutorials
Android Tutorials
Blockchain Tutorials
Linux Tutorials
JavaScript Tutorials
AngularJS Tutorials
Courses
Big Data Hadoop & Spark Scala
Python Course
Big Data & Hadoop
Apache Kafka
Apache Spark & Scala


DataFlair
Learn Today. Lead Tomorrow.


Python Tutorials
6
PREVIOUS
NEXT  

Python Function Tutorial  Type of Functions in Python(With Example)

by  · Updated · 7, 2019
Keeping you updated with latest technology trends, Join DataFlair on Telegram

1. Python Function  Objective

In our tutorial, we discussed dictionaries in python. Now, we forward to deeper parts of the language, lets read about Python Function. Moreover, we will study the different types of functions in Python: Python built-in functions, Python recursion function, Python lambda function, and Python user-defined functions with their syntax and examples.
So, lets start the Python Function Tutorial.
Python Function Tutorial - Type of Functions in Python(With Example)
Python Function Tutorial  Type of Functions in Python(With Example)
Learn: Range Function in Python  Range() in Python

2. An Introduction to Function in Python

Python function in any programming language is a sequence of statements in a certain order, given a name. When called, those statements are executed. So we dont have to write the code again and again for each [type of] data that we want to apply it to. This is called code re-usability.

3. User-Defined Functions in Python

For simplicity purposes, we will divide this lesson into two parts. First, we will talk about user-defined functions in Python. Python lets us group a sequence of statements into a single entity, called a function. A Python function may or may not have a name. Well look at functions without a name later in this tutorial.

a. Advantages of User-defined Functions in Python

(一)This Python Function help divide a program into modules. This makes the code easier to manage, debug, and scale.
(二)It implements code reuse. Every time you need to execute a sequence of statements, all you need to do is to call the function.
(三)This Python Function allow us to change functionality easily, and different programmers can work on different functions.

b. Defining a Function in Python

To define your own Python function, you use the def keyword before its name. And its name is to be followed by parentheses, before a colon(:).
>>> def hello():
          print("Hello")

The contents inside the body of the function must be equally indented.
As we had discussed in our article on Python syntax, you may use a docstring right under the first line of a function declaration. This is a documentation string, and it explains what the function does.
>>> def hello():
             """
             This Python function simply prints hello to the screen
             """
             print("Hello")

You can access this docstring using the __doc__ attribute of the function.
>>> def func1():
           """
           This is the docstring
           """
           print("Hello")
>>> func1.__doc__
'\n\tThis is the docstring\n\t'

However, if you apply the attribute to a function without a docstring, this happens.
>>> sum.__doc__
>>> type(sum.__doc__)
<class 'NoneType'>
>>> bool(sum.__doc__)

False
If you dont yet know what to put in the function, then you should put the pass statement in its body. If you leave its body empty, you get an error Expected an indented block.
>>> def hello1():
       pass
>>> hello1()

You can even reassign a function by defining it again.
Learn Methods in Python  Classes, Objects and Functions in Python

c. Rules for naming python function (identifier)

We follow the same rules when naming a function as we do when naming a variable.
(一)It can begin with either of the following: A-Z, a-z, and underscore(_).
(二)The rest of it can contain either of the following: A-Z, a-z, digits(0-9), and underscore(_).
(三)A reserved keyword may not be chosen as an identifier.
It is good practice to name a Python function according to what it does.
Learn Python Dictionaries with Methods, Functions and Dictionary Operations

d. Python Function Parameters

Sometimes, you may want a function to operate on some variables, and produce a result. Such a function may take any number of parameters. Lets take a function to add two numbers.
>>> def sum(a,b):
            print(f"{a}+{b}={a+b}")
>>> sum(2,3)

2+3=5
Here, the function sum() takes two parameters- a and b. When we call the function, we pass numbers 2 and 3. These are the arguments that fit a and b respectively. We will describe calling a function in point f. A function in Python may contain any number of parameters, or none.
In the next example, we try adding an int and a float.
>>> def sum2(a,b):
         print(f"{a}+{b}={a+b}")
>>> sum2(3.0,2)

3.0+2=5.0
However, you cant add incompatible types.
>>> sum2('Hello',2)

Traceback (most recent call last):
File <pyshell#39>, line 1, in <module>
sum2(Hello,2)
File <pyshell#38>, line 2, in sum2
print(f{a}+{b}={a+b})
TypeError: must be str, not int
Learn Python Strings with String Functions and String Operations

e. Python return statement

A Python function may optionally return a value. This value can be a result that it produced on its execution. Or it can be something you specify- an expression or a value.
>>> def func1(a):
         if a%2==0:
               return 0
          else:
                return 1
>>> func1(7)

1
As soon as a return statement is reached in a function, the function stops executing. Then, the next statement after the function call is executed. Lets try returning an expression.
>>> def sum(a,b):
         return a+b
>>> sum(2,3)

5
>>> c=sum(2,3)

This was the Python Return Function

f. Calling a Python function

To call a Python function at a place in your code, you simply need to name it, and pass arguments, if any. Lets call the function hello() that we defined in section b.
>>> hello()

Hello
We already saw how to call python function with arguments in section e.
Learn: Python Operators with Syntax and Examples

g. Scope and Lifetime of Variables in Python

A variable isnt visible everywhere and alive every time. We study this in functions because the scope and lifetime for a variable depend on whether it is inside a function.
1. Scope
A variables scope tells us where in the program it is visible. A variable may have local or global scope.
Local Scope- A variable thats declared inside a function has a local scope. In other words, it is local to that function.
>>> def func3():
        x=7
        print(x)
>>> func3()

7
If you then try to access the variable x outside the function, you cannot.
>>>x

Traceback (most recent call last):
File <pyshell#96>, line 1, in <module>
x
NameError: name x is not defined
Global Scope- When you declare a variable outside python function, or anything else, it has global scope. It means that it is visible everywhere within the program.
>>> y=7
>>> def func4():
          print(y)
>>> func4()

7
However, you cant change its value from inside a local scope(here, inside a function). To do so, you must declare it global inside the function, using the global keyword.
>>> def func4():
      global y
      y+=1
      print(y)
>>> func4()

8
>>>y

8
As you can see, y has been changed to 8.
Learn: Python Variables and Data Types with Syntax and Examples
2. Lifetime
A variables lifetime is the period of time for which it resides in the memory.
A variable thats declared inside python function is destroyed after the function stops executing. So the next time the function is called, it does not remember the previous value of that variable.
>>> def func1():
         counter=0
         counter+=1
         print(counter)
>>> func1()

1
>>> func1()

1
As you can see here, the function func1() doesnt print 2 the second time.

h. Deleting Python function

Till now, we have seen how to delete a variable. Similarly, you can delete a function with the del keyword.
>>> def func7():
        print("7")
>>> func7()

7
>>> del func7
>>> func7()

Traceback (most recent call last):
File <pyshell#137>, line 1, in <module>
func7()
NameError: name func7 is not defined
When deleting a function, you dont need to put parentheses after its name.
Different Python Function Explained Below.
Learn: Python Installation Tutorial  Steps to Install Python on Windows

4. Python Built-in Functions

In various previous lessons, we have seen a range of built-in functions by Python. This Python function apply on constructs like int, float, bin, hex, string, list, tuple, set, dictionary, and so. Refer to those lessons to revise them all.

5. Python Lambda Expressions

As we said earlier, a function doesnt need to have a name. A lambda expression in Python allows us to create anonymous python function, and we use the lambda keyword for it. The following is the syntax for a lambda expression.
lambda arguments:expression
Its worth noting that it can have any number of arguments, but only one expression. It evaluates the value of that expression, and returns the result. Lets take an example.
>>> myvar=lambda a,b:(a*b)+2
>>> myvar(3,5)

17
This code takes the numbers 3 and 5 as arguments a and b respectively, and puts them in the expression (a*b)+2. This makes it (3*5)+2, which is 17. Finally, it returns 17.
Actually, the function object is assigned to the identifier myvar.
Learn: Python Arguments with Types, Syntax and Examples
Any Doubt yet in Python Function? Please Comment.

6. Python Recursion Function

A very interesting concept in any field, recursion is using something to define itself. In other words, it is something calling itself. In Python function, recursion is when a function calls itself. To see how this could be useful, lets try calculating the factorial of a number. Mathematically, a numbers factorial is:
n!=n*n-1*n-2**2*1
To code this, we type the following.
>>> def facto(n):
 if n==1:
  return 1
 return n*facto(n-1)
>>> facto(5)

120
>>> facto(1)

1
>>> facto(2)

2
>>> facto(3)

6
This was all about recursion function in Python
Isnt this handy? Tell us where else would you use recursion. However, remember that if you dont mention the base case (the case which converges the condition), it can result in an infinite execution.
Learn: Learn Python Closure  Nested Functions and Nonlocal Variables
This was all about the Python Function

7. Conclusion: Python Function

It is important to revise in order to retain information. In this lesson, we learned about the Python function. First, we saw the advantages of a user-defined function in Python. Now we can create, update, and delete a function. And we know that a function may take arguments and may return a value. We also looked at the scope and lifetime of a variable. Hope you like the Python Function Tutorial.
Dont forget to revise the various built-in functions supported by Python. Refer to our tutorials for the same.
Reference

  PREVIOUS
NEXT  
Tags: 
 

6 Responses

Comments6
Pingbacks0
Venkatesh says:
August 23, 2018 at 9:59 am 
hi can i get full pdf of your python notes.
Reply
Sree says:
May 30, 2019 at 4:46 pm 
please check for the output: (you publised under e
>>> def func1(a):
if a%2==0:
return 0
else:
return 1
>>> func1(7)
function calling should be like:
print(func1(7))
please correct me if i am wrong
Reply
Tushar Tonde says:
August 9, 2019 at 1:29 pm 
youre right
Reply
promsky says:
August 23, 2019 at 3:17 pm 
i think it depends whether you are in the python shell or whether you are using a notepadwhen in python shell, you dont need the print function that much .but when you are using a notepad, you can use the print function so as to be executed immediately on the script
Reply
grigorie_p says:
January 2, 2020 at 10:50 pm 
In the presentation you say:
>>> def func1():
counter=0
counter+=1
print(counter)
>>> func1()
1
>>> func1()
1
As you can see here, the function func1() doesnt print 2 the second time.
I didnt expect to display 2 because every time it comes into function, the counter variable becomes 0. I think the example is unhappy. The chapter functions I find quite difficult in Python, and the presentation is slightly slightly simplifying.
Reply
meghana says:
March 21, 2020 at 4:55 pm 
but may I know what is the difference in the output between func1(7) and print(func1(7))
Reply

Leave a Reply 

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

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.



Python Tutorials
Python  Introduction
Python  Features
Python  Pros and Cons
Python  Master Guide
Python  Best Practices
Python  Reasons to Learn
Python  Tools
Python 3.8 Features
Python  Install on Windows
Python  Advantages over Java
Python  Syntax
Python  Comments, Indentations and Statements
Python  Random Number
Python  Variables and Data Types
Python  Variable Scope
Python  Identifiers
Python  Number Types
Python  Strings
Python  Interpreter
Python  Operators
Python  Bitwise Operators
Python  Comparison Operators
Python  Operator Overloading
Python  Ternary Operator
Python  Operator Precedence
Python  Namespaces
Python  Decision Making
Python  Implement Switch Case
Python  Data Structures
Python  Lists
Python  Tuples
Python  Sets & Booleans
Python  List Comprehension
Python  Loops in Python
Python  Functions
Python  Function Arguments
Python  Built-in Functions
Python  Range() Function
Python  Zip Function
Python  Eval Function
Python  exec Function
Python  repr Function
Python  Collections Module
Python  Counters
Python  Namedtuples
Python  Dictionaries
Python  DefaultDict
Python  OrderedDict
Python  DateTime
Python  Modules
Python  Serialization
Python  Packages
Python  Python OS Module
Python  Python pprint Module
Python  Virtual Environment
Python  Date and Time
Python  Calendar Module
Python  Recursion
Python  Lambda Expression
Python  Decorators
Python  Generators
Python  Iterators
Python  Closures
Python  Classes
Python  Methods
Python  Constructors
Python  Object
Python  Inheritance
Python  Multiple Inheritance
Python  Compilers & Interpreters
Python  ZipFile
Python  File I/O
Python  File Handling
Python  Copy A File
Python  Shallow & Deep Copy
Python  Rename A File
Python  Errors and Exceptions
Python  Exception Handling
Python  Assert Statements
Python  Directories
Python  Iterables
Python  Itertool
Python  Property
Python  Sequences and Collections
Python  Multithreading
Python  Regular Expressions
Python  Debugger
Python  Multi Processing
Python  XML Processing
Python  CGI Programming
Python  Library
Python  Math Libraries
Python  SciPy
Python  NumPy
Python  Pandas
Python  PyQT
Python  Array Module
Python  Database Access
Python  Programming with C
Python  Frameworks
Python  Flask
Python  Django
Python  Forensics
Python  Network Programming
Python  Image Processing 
Python  Sending Email
Python  GUI Programming
Python  Unittest
Python  Logging
Python  Slice
Python  Subprocess Module
Python  sys Module
Python  Terminologies Part 1
Python  Terminologies Part 2
Python  OpenCV & Computer Vision
Python  OpenCV Features
Python  OpenCV Environment Setup
Python  Read, Display & Save Image in OpenCV
Python  Computer Vision Techniques
Python  Reasons Why Learn Python
Python  Best Python Books
Python  Applications
Python  Healthcare
Python  Stock Market
Python  Case Studies
Case Study  Python at Netflix
Python  Tuples vs Lists
Python  Modules vs Packages
Python  Generators vs Iterators
Python  Methods vs Functions
Python vs Scala
Python vs Java
Python vs R
Python For Beginners  Infographic
Python Features  Infographic
Python for Data Science
Learn Python for Data Science
Python  Data Science Tutorial
Mastering Python for Data Science
Python  Data Science Installation
Python  Data Cleansing & Operations
Python  Data File Formats
Python  Relational Database
Python  NoSQL Database
Python  Stemming & Lemmatization
Python  Aggregation & Data Wrangling
Python  Statistics
Python  Descriptive Statistics
Python  Probability Distributions
Python Anaconda Tutorial
Python  Matplotlib
Python  Scatter & Box Plots
Python  Bubble & 3D Charts
Python  Heatmap & Word Cloud
Python  Histogram & Bar Plot
Python  Geographical Map & Graph
Python  Time Series
Python  Linear Regression
Python  Importance for ML
Python ML  Tutorial
Python ML  Environment Setup
Python ML  Data Pre-Processing
Python ML  Train and Test Set
Python ML  Techniques
Python ML  Application
Python ML  Algorithms
Python Deep Learning Tutorial
Python DL  Environment Setup
Python DL  Application
Python DL  Python Libraries
Python DL  Deep Neural Networks
Python DL  Computational Graphs
Python AI Tutorial
Python AI  NLTK
Python AI  Speech Recognition
Python AI  NLP Tutorial
Python AI  Heuristic Search
Python AI  Genetic Algorithms
Python AI  Computer Vision
Python AI  Logic Programming
Python Career Guides
Python  Interesting Facts
Python  Demand
Python  Future
Python  Career Opportunities
Python  How Fresher Gets Job
Python  Create Resume
Python  Career Path
Python  Become Developer
Python Career  Infographic
Python Projects
Top Python Projects with source code
Python Interview Questions
Python  Beginners Interview Questions
Python  Intermediates Interview Questions
Python  Experts Interview Questions 
Python Quiz
Python Quiz- Part 1
Python Quiz- Part 2
Python Quiz- Part 3


Home About us Contact us Terms and Conditions Privacy Policy Disclaimer Write For Us Success Stories

Popular Courses
Hadoop Tutorials logoHadoop + Spark Course
Hadoop Tutorials logoBig Data Hadoop Course
Spark Tutorials logoSpark Scala Course
Python Course logoPython Course
Popular Tutorials
Hadoop Tutorials logoHadoop Tutorials
Spark Tutorials logoSpark Tutorials
Flink Tutorials logoFlink Tutorials
Tableau Tutorials logoTableau Tutorials
Power BI Tutorials logoPower BI Tutorials
Popular Tutorials
Data Science Tutorials logoData Science Tutorials
Machine Learning Tutorials logoMachine Learning Tutorials
Python Tutorials logoPython Tutorials
R Tutorials logoR Tutorials
SAS Tutorials logoSAS Tutorials


DataFlair © 2020. All Rights Reserved.