• Home
  • HTML
    • HTML Introduction
    • HTML Basic
    • HTML Elements
    • HTML Attributes
    • HTML Headings
    • HTML Paragraphs
    • HTML Text Formatting
    • HTML Styles
    • HTML Comments
    • HTML Styles - CSS
    • HTML Links
    • HTML Images
    • HTML Tables
    • HTML Lists
    • HTML Block and Inline Elements
    • HTML class Attribute
    • HTML Forms
    • HTML Media
  • CSS
    • Introduction of CSS
    • CSS Syntax
    • CSS Selectors
    • How To Add CSS
    • CSS Comments
    • CSS Colors
    • CSS Backgrounds
    • CSS Borders
    • CSS Margins
    • CSS Text
    • CSS Lists
    • CSS Tables
    • CSS Box Model
    • CSS Dimension
    • CSS Padding
    • CSS Border
    • CSS Margin
    • CSS Outline
    • CSS Cursors
    • CSS Overflow
    • CSS Units
    • CSS Visual Formatting
    • CSS Display
    • CSS Visibility
    • CSS Position
    • CSS Layers
    • CSS Float
    • CSS Alignment
    • CSS Pseudo-classes
    • CSS Pseudo-elements
    • CSS Media Types
    • CSS Sprites
    • CSS Opacity
    • CSS Attribute Selectors
    • CSS Validation
    • CSS3 Border
    • CSS3 Gradients
    • CSS3 Text Overflow
  • JavaScript
    • JS Introduction
    • JS Getting Started
    • JS Syntax
    • JS Variables
    • JS Generating Output
    • JS Data Types
    • JS Operators
    • JS Events
    • JS Strings
    • JS Numbers
    • JS If Else
    • JS Switch Case
    • JS Arrays
    • JS Sorting Arrays
    • JS Loops
    • JS Functions
    • JS Objects
    • JS DOM Nodes
    • JS DOM Selectors
    • JS DOM Styling
    • JS DOM Get Set Attributes
    • JS DOM Manipulation
    • JS DOM Navigation
    • JS Window
    • JS Screen
    • JS Location
    • JS History
    • JS Navigator
    • JS Dialog Boxes
    • JS Timers
    • JS Date and Time
    • JS Math Operations
    • JS Type Conversions
    • JS Event Listeners
    • JS Event Propagation
    • JS Borrowing Methods
    • JS Hoisting Behavior
    • JS Closures
    • JS Strict Mode
    • JS JSON Parsing
    • JS Error Handling
    • JS Regular Expressions
    • JS Form Validation
    • JS Cookies
    • JS AJAX Requests
    • JS ES6 Features
  • jQuery
    • jQuery Introduction
    • jQuery Syntax
    • jQuery Selectors
    • jQuery Events
    • jQuery Show/Hide
    • jQuery Fade
    • jQuery Slide
    • jQuery Animation
    • jQuery Stop
    • jQuery Chaining
    • jQuery Callback
    • jQuery Get/Set
    • jQuery Insert
    • jQuery Remove
    • jQuery CSS Classes
    • jQuery Style Properties
    • jQuery Dimensions
    • jQuery Traversing
    • jQuery Ancestors
    • jQuery Descendants
    • jQuery Siblings
    • jQuery Filtering
    • jQuery Ajax
    • jQuery Load
    • jQuery Get/Post
    • jQuery No-Conflict
  • PHP
    • PHP Introduction
    • PHP Install
    • PHP Syntax
    • PHP Comments
    • PHP Variables
    • PHP Echo / Print
    • PHP Data Types
    • PHP Strings
    • PHP Constants
    • PHP Operators
    • PHP If...Else...Elseif
    • PHP Switch
    • PHP Loops
    • PHP Functions
    • PHP Arrays
    • PHP Superglobals
    • PHP Date and Time
    • PHP Include
    • PHP File Handling
    • PHP File Upload
    • PHP Cookies
    • PHP Sessions
    • PHP Filters
    • PHP Callback Functions
    • PHP JSON
    • PHP Exceptions
    • PHP What is OOP
    • PHP Classes/Objects
    • PHP Constructor
    • PHP Destructor
    • PHP Access Modifiers
    • PHP Inheritance
    • PHP Abstract Classes
    • PHP Interfaces
    • PHP Traits
    • PHP Static Methods
    • PHP Namespaces
  • SQL
    • Introduction to SQL
    • SQL Create Command
    • SQL ALTER Command
    • SQL Truncate Drop Rename
    • INSERT SQL command
    • UPDATE SQL command
    • DELETE SQL command
    • SQL COMMIT command
    • SQL ROLLBACK command
    • SQL GRANT and REVOKE Command
    • SQL WHERE clause
    • SQL LIKE clause
    • SQL ORDER BY Clause
    • SQL Group By Clause
    • SQL HAVING Clause
    • SQL DISTINCT keyword
    • SQL AND OR operator
    • SQL Constraints
    • SQL Functions
    • SQL JOIN
  • Python
    • Getting started with Python
    • Introduction to IDLE
    • Python 2.x vs. Python 3.x
    • Syntax Rules and First Program
    • Numbers and Math Functions
    • Python Operators
    • Python Variables
    • Python Modules and Functions
    • Python Input and Output
    • Data Types in Python
    • String in Python
    • String Functions in python
    • Lists in Python
    • Utilizing List Elements by Iterating
    • Deleting List Elements & other Functions
    • Dictionaries in Python
    • Functions for Dictionary
    • Tuples in Python
    • Relational and Logical Operators
    • Conditional Statements in Python
    • Looping in Python
    • Define Functions in Python
    • Python-Introduction to OOP
    • Object Oriented Programming in Python
    • Classes in Python
    • The concept of Constructor
    • Destructors - Destroying the Object in Python
    • Inheritance in Python
    • Access Modifers in Python
    • Types of Inheritance
    • Method Overriding in Python
    • Polymorphism
    • static Keyword
    • Operator Overloading Python
    • Introduction to Error Handling
    • Exception Handling: try and except
    • Exeption Handling: finally
    • Exception Handling: raise
    • File Handling
    • Reading and Writing File
    • Introduction to Multithreading
    • Threading Module in Python
    • Thread Object
    • Lock Object
    • RLock Object
    • Event Object
    • Timer Object
    • Condition Object
    • Barrier Object
    • __name__ Variable in Python
    • Iterable and Iterator
    • yield Keyword
    • Python Generators
    • Python Closures
    • Python Decorators
    • @property Decorator in Python
    • Assert Statement
    • Garbage Collection
    • Shallow and Deep Copy
    • Introduction to Logging
    • Configure Log LEVEL, Format etc
    • Python Logging in a file
    • Python Logging Variable Data
    • Python Logging Classes and Functions
    • Python MySQL Introduction
    • Create Database - Python MySQL
    • Create Table - Python MySQL
    • Insert Data in Table
    • Select Data from Table
    • Update data in Table
    • Delete data from Table
    • Drop Table from Database
    • WHERE clause - Python MySQL
    • Order By clause - Python MySQL
    • Limit clause - Python MySQL
    • Table Joins - Python MySQL
  • MongoDB
    • MongoDB Introduction
    • Overview of MongoDB
    • MongoDB vs SQL Databases
    • Advantages of MongoDB
    • When to go for MongoDB
    • Data Modelling in MongoDB
    • Is MongoDB really Schemaless?
    • Installing MongoDB on Windows and Linux
    • Datatypes in MongoDB
    • Create and Drop Database in MongoDB
    • MongoDB: Creating a Collection
    • CRUD Operations in MongoDB
    • Data Relationships in MongoDB
    • Indexing in MongoDB
    • Sorting in MongoDB
    • Aggregation in MongoDB
    • Data Backup and Restoration in MongoDB
    • Sharding in MongoDB
    • Java Integration with MongoDB
  • Elixir
    • Elixir Overview
    • Elixir Environment
    • Elixir Basic Syntax
    • Elixir Data Types
    • Elixir Variables
    • Elixir Operators
    • Elixir Pattern Matching
    • Elixir Decision Making
    • Elixir Strings
    • Elixir Char Lists
    • Elixir Lists and Tuples
    • Elixir Keyword Lists
    • Elixir Maps
    • Elixir Modules
    • Elixir Aliases
    • Elixir Functions
    • Elixir Recursion
    • Elixir Loops
    • Elixir Enumerables
    • Elixir Streams
    • Elixir Structs
    • Elixir Protocols
    • Elixir File I/O
    • Elixir Processes
    • Elixir Sigils
    • Elixir Comprehensions
    • Elixir Typespecs
    • Elixir Behaviours
    • Elixir Errors Handling
    • Elixir Macros
    • Elixir Libraries
  • TypeScript
    • TypeScript Overview
    • Install TypeScript
    • First TypeScript Program
    • Type Annotation
    • TypeScript Variable
    • TypeScript Data Type Number
    • TypeScript Data Type String
    • TypeScript Data Type Boolean
    • TypeScript Arrays
    • TypeScript Tuples
    • TypeScript Enum
    • TypeScript Union
    • TypeScript Any Data Type
    • TypeScript Void Data Type
    • TypeScript Never Data Type
  • Home
  • Getting started with Python
  • Introduction to IDLE
  • Python 2.x vs. Python 3.x
  • Syntax Rules and First Program
  • Numbers and Math Functions
  • Python Operators
  • Python Variables
  • Python Modules and Functions
  • Python Input and Output
  • Data Types in Python
  • String in Python
  • String Functions in python
  • Lists in Python
  • Utilizing List Elements by Iterating
  • Deleting List Elements & other Functions
  • Dictionaries in Python
  • Functions for Dictionary
  • Tuples in Python
  • Relational and Logical Operators
  • Conditional Statements in Python
  • Looping in Python
  • Define Functions in Python
  • Python-Introduction to OOP
  • Object Oriented Programming in Python
  • Classes in Python
  • The concept of Constructor
  • Destructors - Destroying the Object in Python
  • Inheritance in Python
  • Access Modifers in Python
  • Types of Inheritance
  • Method Overriding in Python
  • Polymorphism
  • static Keyword
  • Operator Overloading Python
  • Introduction to Error Handling
  • Exception Handling: try and except
  • Exeption Handling: finally
  • Exception Handling: raise
  • File Handling
  • Reading and Writing File
  • Introduction to Multithreading
  • Threading Module in Python
  • Thread Object
  • Lock Object
  • RLock Object
  • Event Object
  • Timer Object
  • Condition Object
  • Barrier Object
  • __name__ Variable in Python
  • Iterable and Iterator
  • yield Keyword
  • Python Generators
  • Python Closures
  • Python Decorators
  • @property Decorator in Python
  • Assert Statement
  • Garbage Collection
  • Shallow and Deep Copy
  • Introduction to Logging
  • Configure Log LEVEL, Format etc
  • Python Logging in a file
  • Python Logging Variable Data
  • Python Logging Classes and Functions
  • Python MySQL Introduction
  • Create Database - Python MySQL
  • Create Table - Python MySQL
  • Insert Data in Table
  • Select Data from Table
  • Update data in Table
  • Delete data from Table
  • Drop Table from Database
  • WHERE clause - Python MySQL
  • Order By clause - Python MySQL
  • Limit clause - Python MySQL
  • Table Joins - Python MySQL
Home >> python >> Define Functions in Python

Define Functions in Python

Welcome to a tutorial on Writing User-defined Functions in Python. 

In the previous tutorial, you were introduced to functions, how functions are used, and the several inbuilt functions. 

Hence, since functions are built, if we want to use them, all we need to was simply call them and provide the necessary arguments. 

Functions defined explicitly (or by a user) in a program, help to divide the whole program into sub-parts, thus making it more readable, easy to revise the code, and to fix any errors (or bugs).

Let's learn about user-defined functions (creating our functions) in Python. Just as learned in previous tutorials, in other to use a built-in function, there is a need to import the module by which the function is defined in our program. Check out the example below, where we imported the math module to use the floor() in-built function.

import math

a = 2.3
print ("The floor of 2.3 is : "+ math.floor(a))

When we open the module file ( a file in Python), we can see the definitions of various functions. You will get to do this on your own before the end of this tutorial, by defining your user-defined functions.

 

Structure of function definition

Below is the general syntax to create a function.

def functionName(parameter1, parameter2, ...):
    logic/algorithm statements
    ...
    return someData

The important part here is the indentation, the definition of the function should be indented by a tabspace after the def functionName(parameter1, parameter2) in the syntax.

In the syntax above, the first line is called function header and starts with the keyword def which means defines, because it is the starting point when defining a function. The next step is the function’s name, where a function is given a name such as multiply, add, or anything that identifies the task of the function.

Afterward, the parameter comes inside the circular braces. These parameters are the required values the user inputs and are used inside the function during the operation. 

In one of our previous tutorials, we put several numbers while calling math's function such as sin(3.14), where the 3.14 is the parameter value, and we know that without the value, the sin() function will not have a value to perform the sine operation. Back to base, you can specify your user-defined function to expect some parameters for successful execution, while defining the function in your program. 

Now, in the second line, there are the logic/algorithm statements, where we will be utilizing all the parameters (if any) to obtain the purpose of the function. There are also, various operations loops, conditional statements, and so on, to perform it. Let’s use the add() function as an example, if we perform a simple addition of –a +b and the result is stored in a variable, like c, thus inside the add() function, there is an expression: c=a+b, and a and be are the input values. 

Then lastly, the return statement comes. The first thing to know is the return statement as it is not compulsory to have it a function. However, if your function is required to return a value after any operation, then you must use the return statement to output that value, otherwise, your function does not need it. Therefore, we must know when to use the return statement. As such the returned data can be anything like a string, a Boolean value, a number, or anything you can think of.

Now, if we want to return any value, all that is needed is to mention the value which we want to return, next to the return keyword. Check out the example below.

def add(a, b):
    c = (a+b)
    return c

Alternatively, (a+b) can be returned directly, without storing it to some other variable.

def add(a, b):
    return (a+b)

Once a function is defined, it can be used to simply call it just as it is for the built-in function. Check out the example below.

>>> print add(5, 9)

Output:

14

In addition, we can as well pass a function as a parameter.

>>> print add(5, add(7, 6))

Output:

18

You might be confused, let me clarify what happened above, firstly the add(7,6) is evaluated and returns 13; this result (13) is passed inside the second add() function as a parameter that will be added with 5. Thus, our final result will be the output of add(5,13) which is 18.

 

Return Type of a function

In Python, every function has a return type, which is the type of values it returns, and it is easy to ascertain the return type of a function. For instance, in add() function, if a and b are integer, then the add() function will return an integer value and will be its return return-type. Also, if the function is returning a list, its return type will be a list. where for a built-in function, you can as well find the return type of every function that is specified in the official documentation.

Recall that we stated above, that it is optional for functions to have a return type. Now, what will be the return type of a function that does not return anything? The answer to this is void, this is quite similar to empty or nothing, meaning that there is no return statement. As such the return type is void.

Now, we will learn how to use the functions with a return-type void.

Note: since this return type does not return anything, it can be used to break our program into smaller units or bits.

Check out the example below of a simple program, in which a positive number was taken as input from the user and printed all the even numbers, and doubled all the odd numbers that start from 1 to the number. 

n = input()
for i in xrange(1, n+1):
	if i%2 == 0:
		print i
	else:
		print 2*i

Let's attempt to obtain the above with a function, as we will start by defining the function on the top. However, it doesn't matter where you define the function, since it does not affect the flow of execution of the function. Although, it's a good practice to define all the functions at the start of your program since that is where all the programmers look for all the user-defined functions when they are reviewing any code in a program.

def check(k):
	if (k%2==0):
		print k
	else:
		print 2*k

n = input()
for i in xrange(1, i+1):
	check(i)

From the above example, we picked up the logic of checking whether the number is even or not and defined it inside the check() function. As such we can call it in the for loop, and then pass a new value to it in every iteration. Interestingly, it cleaned up the for a loop a bit and made it look tidier or cleaner.

The example above is a simple program, but some programs might have 100s of lines of code, so dividing such a program into functions is the best thing to do.

In addition, one advantage of using a function is that you can re-use that function at any time, just by calling it. From the above example, if we want to print a number if it's even or prints the double of it if it is odd, so all we need to do is simply call the function, and then pass that number as the argument, and it is done, just like the check(9).

 

Default Arguments

In Python, the Default arguments are used when you need to pre-set the value for the parameters. That is, if in the future we don't pass any variable as an argument while calling the function, the function will assume the default value and execute its statements.

Check out the example below on how to define the default arguments.

>>> print add()

 

Python will throw an error if a function has no default parameter. Now, we will set the default arguments for the add() function, for it to work without argument values. So will take the default value to be 0, so the returned value will be 0+0=0, which is reasonable, as we have passed any parameter/argument value.

So the updated add() function will be:

def add(a=0, b=0):
    return (a+b)
>>> print add(10, 6)
>>> print add()

Output:

16
0

 

Aliasing function names

Python program has a special feature in which we can create an alias of any function, that is, if a function name is too long and not worth typing every time, a new name can be assigned to it, without altering the original function. Let’s consider the add() function example, if we want a shorter or different name for this function, but without editing the original function, the function aliasing feature can be used. Check out the below where we can rename ad() to a():

>>> a = add

That is it! So after that line, the ad() and a() would call the same function, hence, the parameters will have to be the same as well. Check out the example below to see how this will work.

>>> print a(9, 8)

Output:

17

 

  • Prev
  • Next


-Advertisement-


DeveloperTutorial
[email protected] © 2022-2023 Developers Tutorial All rights reserved.

Follow Us

Facebook Twitter LinkedIn Printerest Reddit

Announcement

Its a big achivement for us, We make a partnership with TutorialWithExample.com for the better content of our users.

Still Need Help ?

Let us now about your issue and a Professional will reach you out.