www.programiz.com Open in urlscan Pro
165.22.44.186  Public Scan

URL: https://www.programiz.com/python-programming/function
Submission: On October 10 via manual from AU — Scanned from AU

Form analysis 4 forms found in the DOM

POST /python-programming/function

<form action="/python-programming/function" method="post" id="search-api-page-search-form-simplest-programming-tutorials-f" accept-charset="UTF-8">
  <div>
    <div class="search-input search-api-page-search-form-simplest-programming-tutorials-f"><button type="submit" class="search-input__form-submit" hidden=""></button><button type="\&quot;button\&quot;" class="search-input__clear btn"><svg
          class="programiz-icon">
          <use xlink:href="/sites/all/themes/programiz/assets/feather-sprite.svg#x"></use>
        </svg></button><button type="\&quot;button\&quot;" class="btn btn--clear c-default"><svg class="programiz-icon programiz-icon--small search-input__icon">
          <use xlink:href="/sites/all/themes/programiz/assets/feather-sprite.svg#search"></use>
        </svg></button><input type="text" value="" placeholder="Search tutorials &amp; examples" id="edit-keys-2" name="keys_2" class="search-input__control js-bound" autocomplete="off"><input type="hidden" name="id" value="2"><input type="hidden"
        name="form_build_id" value="form-M_h9GOEtteRq1b58cnLC8NTeKLwHx3jvz_zYc3dSzv0"><input type="hidden" name="form_id" value="search_api_page_search_form_simplest_programming_tutorials_f"></div>
  </div>
</form>

POST /python-programming/function

<form class="webform-client-form webform-client-form-1680" action="/python-programming/function" method="post" id="webform-client-form-1680" accept-charset="UTF-8">
  <div>
    <div class="form-item webform-component webform-component-markup webform-component--page-feedback-header">
      <p class="font-weight-600" style="font-size: 18px;">Sorry about that.</p>
      <label class="social-area__label" style="margin-top: 20px; font-size: 14px;">How can we improve it?</label>
    </div>
    <div class="rate-share-form">
      <div class="col-md-12">
        <div class="form">
          <div class="form-item webform-component webform-component-textarea webform-component--dislike-feedback">
            <label class="element-invisible" for="edit-submitted-dislike-feedback">Feedback <span class="form-required" title="This field is required.">*</span></label>
            <div class="form-textarea-wrapper resizable textarea-processed resizable-textarea"><textarea required="required" placeholder="Enter your message..." class="form__control form__control--textarea form-textarea required"
                id="edit-submitted-dislike-feedback" name="submitted[dislike_feedback]" cols="60" rows="5"></textarea>
              <div class="grippie"></div>
            </div>
          </div>
        </div>
      </div>
    </div><input type="hidden" name="details[sid]">
    <input type="hidden" name="details[page_num]" value="1">
    <input type="hidden" name="details[page_count]" value="1">
    <input type="hidden" name="details[finished]" value="0">
    <input type="hidden" name="form_build_id" value="form-aF8XUSidcVdGfmYX9_vgeJoTznesJ1YOXxT1doU9frg">
    <input type="hidden" name="form_id" value="webform_client_form_1680">
    <input type="hidden" name="honeypot_time" value="1696914676|VMJA5l2NmrqB2zd_W3hHd14b8IHQwUiIHy0hRrK4GHQ">
    <div class="phone-textfield">
      <div class="form-item form-type-textfield form-item-phone">
        <label for="edit-phone">Leave this field blank </label>
        <input autocomplete="off" type="text" id="edit-phone" name="phone" value="" size="20" maxlength="128" class="form-text js-bound">
      </div>
    </div>
    <div class="captcha"><input type="hidden" name="captcha_sid" value="176340151">
      <input type="hidden" name="captcha_token" value="2db16d0cae926d2ce3a033f255b32927">
      <input type="hidden" name="captcha_response" value="Google no captcha">
      <div class="g-recaptcha" data-sitekey="6LcpoEsUAAAAAP2oeouHeV70m85MUNlab8UrEqyL" data-theme="light" data-type="image">
        <div style="width: 304px; height: 78px;">
          <div><iframe title="reCAPTCHA" width="304" height="78" role="presentation" name="a-2b9s01d6r9bh" frameborder="0" scrolling="no"
              sandbox="allow-forms allow-popups allow-same-origin allow-scripts allow-top-navigation allow-modals allow-popups-to-escape-sandbox"
              src="https://www.google.com/recaptcha/api2/anchor?ar=1&amp;k=6LcpoEsUAAAAAP2oeouHeV70m85MUNlab8UrEqyL&amp;co=aHR0cHM6Ly93d3cucHJvZ3JhbWl6LmNvbTo0NDM.&amp;hl=en&amp;type=image&amp;v=lLirU0na9roYU3wDDisGJEVT&amp;theme=light&amp;size=normal&amp;cb=18vq08n7xttu"></iframe>
          </div><textarea id="g-recaptcha-response" name="g-recaptcha-response" class="g-recaptcha-response"
            style="width: 250px; height: 40px; border: 1px solid rgb(193, 193, 193); margin: 10px 25px; padding: 0px; resize: none; display: none;"></textarea>
        </div><iframe style="display: none;"></iframe>
      </div><noscript>
        <div style="width: 302px; height: 352px;">
          <div style="width: 302px; height: 352px; position: relative;">
            <div style="width: 302px; height: 352px; position: absolute;">
              <iframe src="https://www.google.com/recaptcha/api/fallback?k=6LcpoEsUAAAAAP2oeouHeV70m85MUNlab8UrEqyL&amp;hl=en" frameborder="0" scrolling="no" style="width: 302px; height:352px; border-style: none;"></iframe>
            </div>
            <div style="width: 250px; height: 80px; position: absolute; border-style: none; bottom: 21px; left: 25px; margin: 0px; padding: 0px; right: 25px;">
              <textarea id="g-recaptcha-response" name="g-recaptcha-response" class="g-recaptcha-response" style="width: 250px; height: 80px; border: 1px solid #c1c1c1; margin: 0px; padding: 0px; resize: none;" value=""></textarea>
            </div>
          </div>
        </div>
      </noscript>
    </div>
    <div class="form-actions">
      <div>
        <div class="d-flex justify-content-end"><input class="webform-submit button-primary btn btn-submit-feedback btn--medium btn--block-sp form-submit ajax-processed" type="submit" id="edit-submit" name="op" value="Submit Feedback"></div>
      </div>
    </div>
  </div>
</form>

POST https://email.programiz.com/form/submit?formId=9

<form autocomplete="false" role="form" method="post" action="https://email.programiz.com/form/submit?formId=9" id="mauticform_generalsubscribersformmobile" data-mautic-form="generalsubscribersformmobile" enctype="multipart/form-data"
  class="card card--even-spaced card--shadowed-up card--no-border card--even-spaced__container" target="mauticiframe_generalsubscribersformmobile">
  <div class="mauticform-error" id="mauticform_generalsubscribersformmobile_error"></div>
  <div class="mauticform-message" id="mauticform_generalsubscribersformmobile_message"></div>
  <div class="mauticform-innerform">
    <div class="footer__form__title">Join our newsletter for the latest updates.</div>
    <div class="mauticform-page-wrapper mauticform-page-1 input-group" data-mautic-form-page="1">
      <div id="mauticform_generalsubscribersformmobile_email1" class="mauticform-row mauticform-email mauticform-field-1 mauticform-required input-group" data-validate="email1" data-validation-type="email">
        <input id="mauticform_input_generalsubscribersformmobile_email1" name="mauticform[email1]" value="" placeholder="Enter Email Address" class="mauticform-input input-group__control js-bound" type="email">
        <span class="mauticform-errormsg" style="display: none;">This is required.</span>
      </div>
      <div id="mauticform_generalsubscribersformmobile_submit" class="mauticform-row mauticform-button-wrapper mauticform-field-2 input-group">
        <button type="submit" name="mauticform[submit]" id="mauticform_input_generalsubscribersformmobile_submit" value="" class="mauticform-button input-group__action input-group__action--btn btn btn--primary">Join</button>
      </div>
    </div>
  </div>
  <input type="hidden" name="mauticform[formId]" id="mauticform_generalsubscribersformmobile_id" value="9">
  <input type="hidden" name="mauticform[return]" id="mauticform_generalsubscribersformmobile_return" value="">
  <input type="hidden" name="mauticform[formName]" id="mauticform_generalsubscribersformmobile_name" value="generalsubscribersformmobile">
  <input type="hidden" name="mauticform[messenger]" id="mauticform_generalsubscribersformmobile_messenger" value="1">
</form>

POST https://email.programiz.com/form/submit?formId=6

<form action="https://email.programiz.com/form/submit?formId=6" autocomplete="false" class="footer__form" data-mautic-form="generalsubscribersform" enctype="multipart/form-data" id="mauticform_generalsubscribersform" method="post" role="form"
  target="mauticiframe_generalsubscribersform">
  <div class="mauticform-error" id="mauticform_generalsubscribersform_error"></div>
  <div class="mauticform-message" id="mauticform_generalsubscribersform_message"></div>
  <div class="mauticform-innerform">
    <div class="footer__form__title">Join our newsletter for the latest updates.</div>
    <div class="mauticform-page-wrapper mauticform-page-1 input-group" data-mautic-form-page="1">
      <div class="mauticform-row mauticform-email mauticform-field-1 mauticform-required input-group" data-validate="email1" data-validation-type="email" id="mauticform_generalsubscribersform_email1">
        <input class="mauticform-input input-group__control js-bound" id="mauticform_input_generalsubscribersform_email1" name="mauticform[email1]" placeholder="Enter Email Address" type="email" value="">
        <span class="mauticform-errormsg" style="display: none;">This is required.</span>
      </div>
      <div class="mauticform-row mauticform-button-wrapper mauticform-field-2 input-group" id="mauticform_generalsubscribersform_submit">
        <button class="mauticform-button input-group__action btn btn--primary" id="mauticform_input_generalsubscribersform_submit" name="mauticform[submit]" type="submit" value="">Join</button>
      </div>
    </div>
  </div>
  <input id="mauticform_generalsubscribersform_id" name="mauticform[formId]" type="hidden" value="6">
  <input id="mauticform_generalsubscribersform_return" name="mauticform[return]" type="hidden" value="">
  <input id="mauticform_generalsubscribersform_name" name="mauticform[formName]" type="hidden" value="generalsubscribersform">
  <input type="hidden" name="mauticform[messenger]" id="mauticform_generalsubscribersform_messenger" value="1">
</form>

Text Content

36% off
Try hands-on Python with Programiz PRO!
Claim Discount Now
36% off
Learn to code by doing. Try hands-on Python with Programiz PRO.
Claim Discount Now
Courses Tutorials Examples


Try Programiz PRO



Course Index Explore Programiz

Python JavaScript SQL HTML R C C++ Java RUST Golang Kotlin Swift C# DSA


 * LEARN PYTHON INTERACTIVELY


 * PYTHON INTRODUCTION
   
   * Getting Started
   * Keywords and Identifier
   * Python Comments
   * Python Variables
   * Python Data Types
   * Python Type Conversion
   * Python I/O and Import
   * Python Operators
   * Python Namespace


 * PYTHON FLOW CONTROL
   
   * Python if...else
   * Python for Loop
   * Python while Loop
   * Python break and continue
   * Python Pass


 * PYTHON FUNCTIONS
   
   * Python Function
   * Function Argument
   * Python Recursion
   * Anonymous Function
   * Global, Local and Nonlocal
   * Python Global Keyword
   * Python Modules
   * Python Package


 * PYTHON DATATYPES
   
   * Python Numbers
   * Python List
   * Python Tuple
   * Python String
   * Python Set
   * Python Dictionary


 * PYTHON FILES
   
   * Python File Operation
   * Python Directory
   * Python Exception
   * Exception Handling
   * User-defined Exception


 * PYTHON OBJECT & CLASS
   
   * Python OOP
   * Classes & Objects
   * Python Inheritance
   * Multiple Inheritance
   * Operator Overloading


 * PYTHON ADVANCED TOPICS
   
   * Python Iterator
   * Python Generator
   * Python Closure
   * Python Decorators
   * Python Property
   * Python RegEx
   * Python Examples


 * PYTHON DATE AND TIME
   
   * Python datetime Module
   * Python datetime.strftime()
   * Python datetime.strptime()
   * Current date & time
   * Get current time
   * Timestamp to datetime
   * Python time Module
   * Python time.sleep()

Learn Python practically
and Get Certified.

ENROLL

POPULAR TUTORIALS

Getting Started With Python
Python if Statement
while Loop in Python
Python Lists
Dictionaries in Python
Start Learning Python

POPULAR EXAMPLES

Add two numbers
Check prime number
Find the factorial of a number
Print the Fibonacci sequence
Check leap year
Explore Python Examples

REFERENCE MATERIALS

Built-in Functions
List Methods
Dictionary Methods
String Methods
View all
Learning Paths
Challenges

LEARN PYTHON INTERACTIVELY

Try for Free

COURSES

Interactive SQL Course
Interactive C Course
Interactive Java Course
View all Courses
Python
JavaScript
SQL
HTML
R
C
C++
Java
More languages


LEARN PYTHON PRACTICALLY
AND GET CERTIFIED.

ENROLL FOR FREE!

POPULAR TUTORIALS

Getting Started With Python
Python if Statement
while Loop in Python
Python Lists
Dictionaries in Python
Start Learning Python All Python Tutorials

REFERENCE MATERIALS

Built-in Functions
List Methods
Dictionary Methods
String Methods
View all
Python
JavaScript
R
C
C++
Java
Kotlin

Learn Python practically
and Get Certified.

ENROLL FOR FREE!

POPULAR EXAMPLES

Add two numbers
Check prime number
Find the factorial of a number
Print the Fibonacci sequence
Check leap year
All Python Examples


 * LEARN PYTHON INTERACTIVELY


 * PYTHON INTRODUCTION
   
   * Getting Started
   * Keywords and Identifier
   * Python Comments
   * Python Variables
   * Python Data Types
   * Python Type Conversion
   * Python I/O and Import
   * Python Operators
   * Python Namespace


 * PYTHON FLOW CONTROL
   
   * Python if...else
   * Python for Loop
   * Python while Loop
   * Python break and continue
   * Python Pass


 * PYTHON FUNCTIONS
   
   * Python Function
   * Function Argument
   * Python Recursion
   * Anonymous Function
   * Global, Local and Nonlocal
   * Python Global Keyword
   * Python Modules
   * Python Package


 * PYTHON DATATYPES
   
   * Python Numbers
   * Python List
   * Python Tuple
   * Python String
   * Python Set
   * Python Dictionary


 * PYTHON FILES
   
   * Python File Operation
   * Python Directory
   * Python Exception
   * Exception Handling
   * User-defined Exception


 * PYTHON OBJECT & CLASS
   
   * Python OOP
   * Classes & Objects
   * Python Inheritance
   * Multiple Inheritance
   * Operator Overloading


 * PYTHON ADVANCED TOPICS
   
   * Python Iterator
   * Python Generator
   * Python Closure
   * Python Decorators
   * Python Property
   * Python RegEx
   * Python Examples


 * PYTHON DATE AND TIME
   
   * Python datetime Module
   * Python datetime.strftime()
   * Python datetime.strptime()
   * Current date & time
   * Get current time
   * Timestamp to datetime
   * Python time Module
   * Python time.sleep()

Ad
Ad



PYTHON TUTORIALS

 * Python Function Arguments
 * Python User-defined Functions
 * Python Lambda/Anonymous Function
 * Python Mathematical Functions
 * Python map()
 * Python Decorators

Ad
Ad
Ad



PYTHON FUNCTIONS

A function is a block of code that performs a specific task.

Suppose, you need to create a program to create a circle and color it. You can
create two functions to solve this problem:

 * create a circle function
 * create a color function

Dividing a complex problem into smaller chunks makes our program easy to
understand and reuse.

--------------------------------------------------------------------------------


LEARN PYTHON WITH CHALLENGES

Solve challenges and become a Python expert.



--------------------------------------------------------------------------------


TYPES OF FUNCTION

There are two types of function in Python programming:

 * Standard library functions - These are built-in functions in Python that are
   available to use.
 * User-defined functions - We can create our own functions based on our
   requirements.

--------------------------------------------------------------------------------


PYTHON FUNCTION DECLARATION

The syntax to declare a function is:

def function_name(arguments):
    # function body 

    return

Here,

 * def - keyword used to declare a function
 * function_name - any name given to the function
 * arguments - any value passed to function
 * return (optional) - returns value from a function

Let's see an example,

def greet():
    print('Hello World!')



Ad



Here, we have created a function named greet(). It simply prints the text Hello
World!.

This function doesn't have any arguments and doesn't return any values. We will
learn about arguments and return statements later in this tutorial.

--------------------------------------------------------------------------------


CALLING A FUNCTION IN PYTHON

In the above example, we have declared a function named greet().

def greet():
    print('Hello World!')

Now, to use this function, we need to call it.

Here's how we can call the greet() function in Python.

# call the function
greet()

--------------------------------------------------------------------------------


EXAMPLE: PYTHON FUNCTION

def greet():
    print('Hello World!')

# call the function
greet()

print('Outside function')

Run Code

Output

Hello World!
Outside function

In the above example, we have created a function named greet(). Here's how the
program works:

Working of Python Function

Here,

 * When the function is called, the control of the program goes to the function
   definition.
 * All codes inside the function are executed.
 * The control of the program jumps to the next statement after the function
   call.

--------------------------------------------------------------------------------


PYTHON FUNCTION ARGUMENTS

As mentioned earlier, a function can also have arguments. An argument is a value
that is accepted by a function. For example,

# function with two arguments
def add_numbers(num1, num2):
    sum = num1 + num2
    print('Sum: ',sum)

# function with no argument
def add_numbers():
    # code

If we create a function with arguments, we need to pass the corresponding values
while calling them. For example,

# function call with two values
add_numbers(5, 4)

# function call with no value
add_numbers()

Here, add_numbers(5, 4) specifies that arguments num1 and num2 will get values 5
and 4 respectively.

--------------------------------------------------------------------------------


EXAMPLE 1: PYTHON FUNCTION ARGUMENTS

# function with two arguments
def add_numbers(num1, num2):
    sum = num1 + num2
    print("Sum: ",sum)

# function call with two values
add_numbers(5, 4)

# Output: Sum: 9

Run Code

In the above example, we have created a function named add_numbers() with
arguments: num1 and num2.

Python Function with Arguments

We can also call the function by mentioning the argument name as:

add_numbers(num1 = 5, num2 = 4)

In Python, we call it Keyword Argument (or named argument). The code above is
equivalent to

add_numbers(5, 4)

--------------------------------------------------------------------------------


THE RETURN STATEMENT IN PYTHON

A Python function may or may not return a value. If we want our function to
return some value to a function call, we use the return statement. For example,

def add_numbers():
    ...
    return sum

Here, we are returning the variable sum to the function call.

Note: The return statement also denotes that the function has ended. Any code
after return is not executed.

--------------------------------------------------------------------------------


EXAMPLE 2: FUNCTION RETURN TYPE

# function definition
def find_square(num):
    result = num * num
    return result

# function call
square = find_square(3)

print('Square:',square)

# Output: Square: 9

Run Code

In the above example, we have created a function named find_square(). The
function accepts a number and returns the square of the number.

Working of functions in Python

--------------------------------------------------------------------------------


EXAMPLE 3: ADD TWO NUMBERS

# function that adds two numbers
def add_numbers(num1, num2):
    sum = num1 + num2
    return sum

# calling function with two values
result = add_numbers(5, 4)

print('Sum: ', result)

# Output: Sum: 9

Run Code

--------------------------------------------------------------------------------


PYTHON LIBRARY FUNCTIONS

In Python, standard library functions are the built-in functions that can be
used directly in our program. For example,

 * print() - prints the string inside the quotation marks
 * sqrt() - returns the square root of a number
 * pow() - returns the power of a number

These library functions are defined inside the module. And, to use them we must
include the module inside our program.

For example, sqrt() is defined inside the math module.

--------------------------------------------------------------------------------


EXAMPLE 4: PYTHON LIBRARY FUNCTION

import math

# sqrt computes the square root
square_root = math.sqrt(4)

print("Square Root of 4 is",square_root)

# pow() comptes the power
power = pow(2, 3)

print("2 to the power 3 is",power)

Run Code

Output

Square Root of 4 is 2.0
2 to the power 3 is 8

In the above example, we have used

 * math.sqrt(4) - to compute the square root of 4
 * pow(2, 3) - computes the power of a number i.e. 23

Here, notice the statement,

import math

Since sqrt() is defined inside the math module, we need to include it in our
program.

--------------------------------------------------------------------------------


BENEFITS OF USING FUNCTIONS

1. Code Reusable - We can use the same function multiple times in our program
which makes our code reusable. For example,

# function definition
def get_square(num):
    return num * num

for i in [1,2,3]:
    # function call
    result = get_square(i)
    print('Square of',i, '=',result)

Run Code

Output

Square of 1 = 1
Square of 2 = 4
Square of 3 = 9

In the above example, we have created the function named get_square() to
calculate the square of a number. Here, the function is used to calculate the
square of numbers from 1 to 3.

Hence, the same method is used again and again.

2. Code Readability - Functions help us break our code into chunks to make our
program readable and easy to understand.


TABLE OF CONTENTS

 * Introduction
 * Types of function
 * Python Function Declaration
 * Calling a Function in Python
 * Example: Python Function
 * Python Function Arguments
 * Example 1: Python Function Arguments
 * The return Statement in Python
 * Example 2: Function return Type
 * Python Library Functions
 * Example 4: Python Library Function
 * Benefits of Using Functions


VIDEO: INTRODUCTION TO PYTHON FUNCTIONS


Previous Tutorial:
Python Pass
Next Tutorial:
Function Argument
Share on:

Did you find this article helpful?


Sorry about that.

How can we improve it?
Feedback *

Leave this field blank


Ad


--------------------------------------------------------------------------------


RELATED TUTORIALS

Python Tutorial

Python Function Arguments

Python Tutorial

Python User-defined Functions

Python Tutorial

Python Lambda/Anonymous Function

Python Library

Python map()

Join our newsletter for the latest updates.
This is required.
Join
Join our newsletter for the latest updates.
This is required.
Join


TUTORIALS

 * Python 3 Tutorial
 * JavaScript Tutorial
 * SQL Tutorial
 * HTML Tutorial
 * R Tutorial
 * C Tutorial
 * C++ Tutorial
 * Java Tutorial
 * Rust Tutorial
 * Go Tutorial
 * Kotlin Tutorial
 * Swift Tutorial
 * C# Tutorial
 * DSA Tutorial

EXAMPLES

 * Python Examples
 * JavaScript Examples
 * C Examples
 * Java Examples
 * Kotlin Examples
 * C++ Examples

COMPANY

 * Change Ad Consent
 * Do not sell my data
 * About
 * Advertising
 * Privacy Policy
 * Terms & Conditions
 * Contact
 * Blog
 * Careers
 * Youtube

APPS

 * Learn Python
 * Learn C Programming
 * Learn Java



© Parewa Labs Pvt. Ltd. All rights reserved.