Facebook Twitter Instagram
    TecAdmin
    • Home
    • FeedBack
    • Submit Article
    • About Us
    Facebook Twitter Instagram
    TecAdmin
    You are at:Home»General Articles»Python Functions – Definition with Examples

    Python Functions – Definition with Examples

    By RahulAugust 17, 20214 Mins Read

    Functions are subprograms in the main program that contain a bundle of related statements of code that only run when they are called. They are written in order to perform particular tasks. Functions help us break our code into smaller chunks and avoid repetitiveness in code. They make the code more organized and increase its readability.

    Advertisement

    Most programming languages have the following two types of functions:

    • Pre-Built/Built-in Functions
    • User defined Functions

    Python also has another small anonymous function called lambda function which will also be discussed in the following sections.

    What is Built-in Functions

    All major programming languages have built-in functions which are defined in the framework of the language. These functions can be called to perform tedious tasks by using just one line of code. For example, sum(), len(), slice() and print() are some of the examples of built-in functions in Python.

    What is User-defined Functions

    User-defined functions are custom functions created by the programmer to perform certain tasks in the code.

    If a programmer needs to perform a task repetitively in the code e.g. outputting a welcome text whenever someone logs in or performing any arithmetic operation on numbers, then he/she can write a function and call it whenever there is a need to perform that task.

    How to declare a function in Python

    A function in Python needs to be defined before it can be called. It does not have hoisting, unlike JavaScript where declarations are moved to the top of the code and a function can be called even before it has been declared.

    In Python, the def keyword is used to declare a function. It is followed by the name of the function along with the arguments/parameters in parenthesis. Then we use a colon (:) which marks the end of the header.

    The body of the function is indented and all the statements inside the body have the same level of indentation. The return statement marks the end of a function in Python; It is however optional.

    def function_name(parameters/arguments):
        statement(s)
    

    Now let’s declare a function that prints a welcome message whenever it is called:

    1
    2
    def welcome():
        print("Welcome!")

    How to call a function in Python

    In a program, a function needs to be called in order to execute the code present inside it. A function can be called by just using its name:

    1
    2
    3
    4
    def welcome():
        print("Welcome!")
     
    welcome()

    Output:
    Welcome!

    Using Return statement in Python Function’s

    The return is an optional statement which can be used to return a value to the main program from the function. It returns a value to where the function was called:

    1
    2
    3
    4
    5
    def welcome():
        greet = "Welcome here!"
        return greet
        
    print(welcome())

    Output:
    Welcome here!

    How to pass arguments to a function in Python

    Information can be passed from the main program to a function through variables as arguments. Any number of arguments can be passed to a function; they are specified in parenthesis and are separated by commas:

    1
    2
    3
    4
    5
    6
    def welcome(n):
        print("Welcome " + n + "!")
        
        
    name = "John"
    welcome(name)

    Output:
    Welcome John!

    The number of arguments should be the same when defining and calling a function, otherwise, the program will give an error:

    1
    2
    3
    4
    5
    6
    def welcome(n, second_name):
        print("Welcome " + n + "!")
        
        
    name = "John"
    welcome(name)

    Output:
    Traceback (most recent call last): File "", line 6, in TypeError: welcome() missing 1 required positional argument: 'second_name' >

    Once you provided the correct number of arguments, the function will work properly as below:

    1
    2
    3
    4
    5
    6
    def welcome(n, second_name):
        print("Welcome " + n + " " + second_name + "!")
        
    name = "John"
    second_name = "Snow"
    welcome(name, second_name)

    Output:
    Welcome John Snow!

    We can also pass a default parameter value. If the function is called without any arguments then it will use the default value:

    1
    2
    3
    4
    5
    def welcome(n = "John", second_name = "Doe"):
        print("Welcome " + n + " " + second_name + "!")
        
    name = "Jane"
    welcome(name)

    Output:
    Welcome John Doe!

    What is a lambda function in Python?

    Lambda are anonymous functions (they have no name) that are declared and defined on a single line. They are great for simple single-line operations like mathematical operators. They follow a simple syntax:

    lambda arguments: expression
    

    They are declared by using the keyword lambda followed by the arguments which are separated from the expression using a colon (:). Now we will make a simple lambda function that takes two numbers and adds them together:

    1
    2
    3
    sum = lambda a, b: a+b
     
    print(sum(6, 7))

    Output:
    13

    Conclusion

    Functions are a collection of statements of code that are called whenever there is a need to perform a specific task. Functions allow programmers to divide programs into subprograms and enable them to just reuse code rather than rewriting it.

    Python has three different types of functions i.e Built in, Custom and Lambda. The built in functions are already defined in the framework/libraries of the language. They enable us to easily perform complex tasks in a single step. The custom functions are written by the programmers themselves according to their needs. Lambda is small anonymous function in python.

    In this post we have learned about Python functions. We learned to declare functions and call them from our main program.

    functions Python
    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email WhatsApp

    Related Posts

    How to List Manually Installed Packages in Ubuntu & Debian

    10 Bash Tricks Every Developer Should Know

    How to Validate Email Address in JavaScript

    Add A Comment

    Leave A Reply Cancel Reply

    Advertisement
    Recent Posts
    • How to List Manually Installed Packages in Ubuntu & Debian
    • 10 Bash Tricks Every Developer Should Know
    • How to Validate Email Address in JavaScript
    • Firewalld: Common Firewall Rules and Commands
    • 12 Apk Commands in Alpine Linux Package Management
    Facebook Twitter Instagram Pinterest
    © 2023 Tecadmin.net. All Rights Reserved | Terms  | Privacy Policy

    Type above and press Enter to search. Press Esc to cancel.