How do i use methods in python?



  • Methods allow you to reuse the code. Python has lots of built-in methods.

    Defining a method.

    def error_message(s1,s2):
        print("The error is: " + s1 + " at " + s2)
    

    To use the method:

    error_message("Fatal", "Mon Jan 22nd 2012 15:34:00")
    

    The error is: Fatal at Mon Jan 22nd, 2012 15:34:00

    Adding some documentation to the code. Inserting three double quotes when using something like Pycharm editor will automatically fill in the simple documentation template where you can add your own description of the method.

    def error_message(s1,s2):
        """
        Print error message level and date.
        :param s1: 
        :param s2: 
        :return: 
        """
        print("The error is: " + s1 + " at " + s2)
    

    Using return statement to assign values to a variable. Change our print statement to return, use our method in a variable called "values", and print the output, for demonstration purposes, it's just two joined words.

    def error_message(s1,s2):
        """
        Print error message level and date.
        :param s1: 
        :param s2: 
        :return: 
        """
        return s1 + s2
    
    values = error_message("Fatal", "Date")
    print(values)
    

    FatalDate

    You can use optional or positional parameters within methods. The s2 string has a default value. if only the first string is provided, the second string has a default, if not specifically specified.

    >>> def welcome_message(s1, s2="folks!"):
                 print(s1,s2)
    
    welcome_message("Hello")
    

    Hello folks!

    welcome_message("Goodbye")
    

    Goodbye folks!

    If the second string is specifically specified in the method:

    welcome_message("Hello", s2="World!")
    

    As you see it is flexible, they can be both default values or you can specify one or the other.
    Hello World!


Log in to reply
 

© Lightnetics 2024