Your ultimate guide

Functions in Python - part 1

 Functions:
    If a group of statements is repeatedly required, then it is not recommended to write them separately every time. We have to define these statements as a single unit and we can call that unit any number of times based on our requirement without rewriting.

There are two types of functions:
    1. Built-in Function
            Python software includes a collection of pre-loaded functions that come as part of its standard package.
        Example: type(), id(), input(), print(), range(), bin(), etc.,
    2. User Defined Functions
            We can create our own function based on our requirements.
        Syntax:
        def function_name(parameters) :
                Statements
                - - -
                - - -
        return value

        Note: while creating functions, we can use 2 keywords
                1) def (mandatory)
                2) return (optional)
                

    Important functions of List:
    1) append() - To add the object to the end of the list.
        Eg:
            1) l = ["apple", "boy"]
            2) l.append("cat")
            3) print(l)
            >>> ["apple", "boy", "cat"]
    2) clear() - Remove all items from the list.
        Eg:
            1) l = [1,2,3]
            2) l.clear()
            3) print(l)
            >>> []
    3) copy() - Return a shallow copy of the list.
        Eg:
            1) list1 = [1, 2, 3, 4, 5]
            2) list2 = list1
            3) print(list1, list2)
            >>>[1, 2, 3, 4, 5]    [1, 2, 3, 4, 5]
            5) list2[1] = 55
            6) print(list1, list 2)
            >>>[1, 55, 3, 4, 5]    [1, 55, 3, 4, 5]
        The problem here is by using one reference variable if we are changing content, then those changes will be reflected to the other reference variable.
        To overcome this problem we should use either copy() function or slice operator.
    Eg: By using the slice operator
        1) list1 = [1, 2, 3, 4, 5]
        2) list2 = list1[:]
        3) print(list1, list2)
            >>>[1, 2, 3, 4, 5]    [1, 2, 3, 4, 5]
            5) list2[1] = 55
            6) print(list1, list 2)
            >>> [1, 2, 3, 4, 5]    [1, 55, 3, 4, 5]
        Eg: By using copy() function
            1) list1 = [1, 2, 3, 4, 5]
            2) list2 = list1.copy()
            3) print(list1, list2)
            >>>[1, 2, 3, 4, 5]    [1, 2, 3, 4, 5]
            5) list2[1] = 55
            6) print(list1, list 2)
            >>> [1, 2, 3, 4, 5]    [1, 55, 3, 4, 5]

    4) count() - Return the number of occurrences of value.
        Eg:
            1) l = [1, 2, 2, 2, 3, 3, 3, 3, 3, 3, 4, 4]
            2) print(l.count(1))
            >>>1
            3) print(l.count(2))
            >>> 3
            4) print(l.count(3))
            >>> 6
            5) print(l.count(4))
            >>> 2

    5) extend() - Adds all items of one list to the end of another list.
        Eg:
            1) list1 = [1, 2, 3, 4]
            2) list2 = ["A", "B", "C"]
            3) list1.extend(list2)
            4) print(list1)
            >>> [1, 2, 3, 4, "A", "B", "C"]

    6) index() - Return the index of the first element with a specified value.
        Eg:
            1) l = ["apple", "bat", "bat", "cat"]
            2) print(l.index("apple"))    #0
            3) print(l.index("bat"))    #1
            4) print(l.index("cat"))    #3

    7) insert() - Adds element at any specified position.
        Syntax:
            list.insert(index, value)
        Eg:
            1) l = ["apple", "cat", "dog"]
            2) l.insert(1 , "bat")
            3) print(l)
            >>> ['apple', 'bat', 'cat', 'dog']

        Difference between append() and insert()?
            append(): In List when we add any element it will come in last.
            insert(): In List, we can insert an element in the particular index position. 

    8) pop() - Remove the element at the specified position (default last).
        Syntax:
            list.pop(index)    # to remove the particular index value
            list.pop()    # to remove the last value in a list
        Eg:
            1) l = ["apple", "boy", "cat"]
            2) l.pop(1)
            3) print(l)    #['apple', 'cat']
        Eg:
            1) l = ["apple", "boy", "cat"]
            2) l.pop()
            3) print(l)    #['apple', 'boy']

    9) remove() - Remove the first item with specific values
                            (Remove the first occurrence of the value)
            Eg:
                1) l = ["apple", 1, 2, 3, 2]
                2) l.remove("apple")
                3) print(l)
                >>> [1, 2, 3, 2]
                4) l.remove(2)
                >>> [1, 3, 2]
    10) reverse() - reverse the order of the list.
        Eg:
            1) l = [1, 2, 3, 4]
            2) l.reverse()
            3) print(l)
            >>> [4, 3, 2, 1]

    11) sort() - Sort the list in ascending order.
        Eg:
            1) num = [3, 2, 4, 1]
            2) num.sort()
            3) print(num)    #[1, 2, 3, 4]

            4) alp = ['boy', 'apple', 'dog']
            5) alp.sort()
            6) print(alp)    #['apple', 'boy', 'dog']

            7) mul = [3, 2, 1, 'apple', 'boy']
            8) mul.sort()
            >>> TypeError: not supported between instances of 'str' and 'int'

    Important functions of Tuple:
    1) count() - Return the number of occurrences of value.
        Eg:
            1) t = (1, 2, 3, 2, 4, 2)
            2)print(t.count(2))
            >>> 3

    2) index() - Return the index of the first element with a specified value.
        Eg:
            1) t = (1, 2, 3, 2, 4, 2)
            2) print(t.index(2))
            >>> 1


    Important functions of set:
    1) add() - To add an element to a set.
        Eg:
            1) s = {1, 2, 3}
            2) s.add(0)
            3) print(s)    #{0, 1, 2, 3}

    2) clear() - To remove all elements from this set.
        Eg:
            1) s = {1, 2, 3}
            2) print(s)    #{1, 2, 3}
            3) s.clear()
            4) print(s)    #set{}
 
    3) copy() - Return a shallow copy of a set
        Eg:
            1) s = {1, 2, 3}
            2) s1 = s.copy()
            3) print(s1)    #{1, 2, 3}

    4) difference() - Return the difference of two or more sets as a new set.
        Eg:
            1) x = {1, 2, 3}
            2) y = {3, 4, 5}
            3) z = x.difference(y)
            3) print(z)    #{1, 2}
            4) print(y.difference(x))    #{4, 5}

        difference_update() - Remove all elements that exist in both sets.
        Eg: 
            1) x = {1, 2, 3}
            2) y = {3, 4, 5}
            3) x.diffrence_update(y)
            4) print(x)    #{1, 2}

    5) discard() - To remove the specified item.
        Eg:
            1) s = {1, 2, 3, 4}
            2) s.discard(2)
            3) print(s)    #{1, 3, 4}
            4) s.discard(5)
            5) print(s)    #{1, 3, 4}

    6) intersection() - Return intersection of two or more sets as a new set.
        Eg:
            1) s1 = {1, 2, 3, 4}
            2) s2 = {3, 4, 5, 6}
            3) print(s1.intersection(s2))    #{3, 4}
            4) print(s1 & s2)    #{3, 4}

        intersection_update() - Update a set with the intersection of itself and another.
        Eg:
            1) s1 = {1, 2, 3, 4}
            2) s2 = {3, 4, 5, 6}
            3) s1.intersection_update(s2)
            4) print(s1)

    7) isdisjoint() -Returns True if two sets have a null intersection.
        Eg:
            1) x = {"apple", "boy",  "cat"}
            2) y = {"one", "two", "cat"}
            3) z = {"testing", "colleges", "blogger"}
            4) print(x.isdisjoint(z))    #True
            5) print(x.isdisjoint(y))    #False

    8) issubset() - Reports True if all items in the set exist in the specified set. 
        Eg:
            1) x = {"apple", "boy", "cat"}
            2) y = {"one", "two", "cat", "boy", "apple"}
            3) z = {"one", "two", "three", "boy", "apple"}
            4) print(x.issubset(y))    #True
            5) print(x.issubset(z))    #False

    9) issuperset()Report True if all items in the specified set exist in the original set.
        Eg:
            1) x = {"one", "two", "cat", "boy", "apple"}
            2) y = {"apple", "boy", "cat"}
            3) z = {"apple", "boy", "dog"}
            4) print(x.issuperset(y))    #True
            5) print(x.issuperset(z))    #False

    10) pop() - To remove an element from the set
        Eg:
            1) s = {1, 2, 3}
            2) s.pop()
            3) print(s)    #{2, 3}

    11) remove() - To remove the specified element
        Eg:
            1) s = {1, 2, 3}
            2) s.remove(2)
            3) print(s)    #{1, 3}

    12) union() - Returns the union of sets as a new set.
        Eg:
            1) s1 = {1, 2, 3}
            2) s2 = {2, 3, 4, 5}
            3) print(s1.union(s2))    #{1, 2, 3, 4, 5}
            4) print(s1 | s2)    #{1, 2, 3, 4, 5}

    13) update(x, y, z) - To add another set or iterable(list, tuple, etc.,)
        Eg:
            1) x = {1, 2, 3}
            2) y = {3, 6, 5, 4}
            3) x.update(y)
            4) print(x)    #{1, 2, 3, 4, 5, 6}
        (Note: If an item is present in both sets, only one appearance of this item will be present in the updated set)
        Eg:
            1) x = {"apple", "boy", "cat"}
            2) y = {"cat", "dog"}
            3) x.update(y, range(3))
            4) print(x)    #{0, 1, 2, 'cat', 'apple', 'dog', 'boy'}

    Important function of Dictionary
    1) clear() - Remove all elements from the dictionary.
        Eg:
            1) bike = {"brand" : "Harley Davidson" , "model" : "x440", "price" : "229K"}
            2) bike.clear()
            3) print(bike)    #{}

    2) copy() - Return a shallow copy of a dictionary.
        Eg:
            1) bike = {"brand" : "Harley Davidson" , "model" : "x440", "price" : "229K"}
            2) mybike = bike.copy()
            3) print(mybike)
            >>> {'brand' : 'Harley Davidson' , 'model' : 'x440', 'price' : '229K'}

    3) fromkeys() - Return dictionary with specified keys and values.
        Eg:
            1) x = ('a', 'b', 'c')
            2) y = None
            3) z = dict.fromkeys(x, y)
            4) print(z)
            >>> {'a': None, 'b': None, 'c': None}

    4) get() - Return value using keys.
        Eg:
            1) bike = {'brand' : 'Harley Davidson' , 'model' : 'x440', 'price' : '229K'}
            2) print(bike.get('model'))    #x440

    5) items() - Return a list containing a tuple for each key-value pair.
        Eg:
            1) bike = {'brand' : 'Harley Davidson' , 'model' : 'x440', 'price' : '229K'}
            2) tbike = bike.items()
            3) print(tbike)
            >>> dict_items([('brand' : 'Harley Davidson'), ('model' : 'x440'), ('price' : '229K')])

    6) keys() - Returns the list containing key values.
        Eg:
            1) bike = {'brand' : 'Harley Davidson' , 'model' : 'x440', 'price' : '229K'}
            2) tbike = bike.keys()
            3) print(tbike)
            >>> dict_keys(['brand', 'model', 'price'])

    7) pop() - Remove the specified key-value pair.
        Eg:
            1) bike = {'brand' : 'Harley Davidson' , 'model' : 'x440', 'price' : '229K'}
            2) bike.pop('brand')
            3)print(bike)
            >>> {'model' : 'x440', 'price' : '229K'}

    8) popitem() - Remove the last inserted key-value pair.
        Eg:
            1) bike = {'brand' : 'Harley Davidson' , 'model' : 'x440', 'price' : '229K'}
            2) bike.popitem()
            3) print(bike)
            >>>{'brand' : 'Harley Davidson' , 'model' : 'x440'}

    9) update() - add specified key-value pair to the dictionary.
        Eg:
            1) bike = {'brand' : 'Harley Davidson' , 'model' : 'x440'}
            2) bike.update({'price' : '229K'})
            3) print(bike)
            >>> {'brand' : 'Harley Davidson' , 'model' : 'x440', 'price' : '229K'}

    10) values() - Return the list containing all values.
        Eg:
            1) bike = {'brand' : 'Harley Davidson' , 'model' : 'x440', 'price' : '229K'}
            2) x = bike.values()
            3) print(x)
            >>> dict_values(['Harley Davidson', 'x440', '229K'])

    Important function of String
    1) capitalize() - converts the first character to upper case in a string and the remaining all characters to lower case.
        Eg:
            1) word = "learning Python is EASY"
            2) x = word.capitalize()
            3) print(x)
            >>> Learning python is easy

    2) casefold() - convert the string into lowercase.
        Eg:
            1) word = "Python is Object Oriented Programming LANGUAGE"
            2) print(word.casefold())
            >>> python is object oriented programming language

    3) count() - Return the number of times a specified value occurs in the string.
        Eg:
            1) word = "testing colleges blogger"
            2) word.count('e')    #4
            3) word.count('testing')    #1

    4) endswith() - Return True if the string ends with the specified value.
        Eg:
            1) word = "testing colleges blogger"
            2) print(word.endswith("r"))
            >>> True
            3) print(word.endswith("blogger"))
            >>> True
    5) startswith() - Return True if the string starts with the specified value.
        Eg:
            1) word = "testing colleges blogger"
            2) print(word.startswith("testing"))
            >>> True

    6) find() - Return the position of the specified value.
        Eg:
            1) word = "testing colleges blogger"
            2) print(word.find("colleges"))    #8
            3) print(word.find("o"))    #9

    7) format() - Return specified values in a string.
        Eg:
            1) a,b = 10,20
            2) c = a + b
            3) result = "Addition of {f} and {l} is {sum}"
            4) result.format(f=a, l=b, sum=c)
            >>> 'Addition of 10 and 20 is 30'
            
            1) word = "My name is {name}"
            2) word.format(name = "Testing")
            3) 'My name is Testing'
            
    8) index() - Return the position of the specified value. It is exactly the same as the find() method except that if the specified substring is not available then we will get ValueError.
        Eg:
            1) word = "testing colleges blogger"
            2) print(word.index("colleges"))    #8
            3) print(word.index("o"))    #9
            4) print(word.index("a"))
            >>> ValueError: substring not found

    9) isalnum() - Return True if all characters in the string are alphabets/numeric values. (False, if the string contains: (space)!@#$%^&()* etc.,)
        Eg:
            1) word1 = "Testing12"
            2) word2 = "Testing 12"
            3) word3= "Testing$12"
            4) print(word1.isalnum())    #True
            5) print(word2.isalnum())    #False
            6) print(word3.isalnum())    #False

    10) isalpha() - Return True if all characters in the string are only alphabets. (False, if the string contains: 0-9, (space)!@#$%^&()* etc.,)
        Eg:
            1) word1 = "Testing"
            2) word2 = "Testing12"
            3) print(word1.isalpha())    #True
            4) print(word2.isalpha())    #False

    11) isdecimal() - Return True if all characters in the string are only decimals. (False, if the string contains: a-z, A-Z, (space)!@#$%^&()* etc.,)
        Eg:
            1) word = "1234"
            2) print(word.isdecimal())    #True

    12) islower() - Return True if all characters in the string are in lowercase.
        Eg:
            1) word1 = "testing colleges"
            2) word2 = "Testing"
            3) word3 = "testing $ colleges"
            4) print(word1.islower())    #True
            5) print(word2.islower())    #False
            6) print(word3.islower())    #True
    13) isspace() -  Returns True if all characters are blank spaces.
        Eg:
            1) a = "  "
            2) print(a.isspace())    #True

    14) istitle() - Returns True if all words should be title case.
        Eg:
            1) a = "Testing Colleges"
            2) print(a.istitle())    #True

    15) isupper() - Returns True if all the characters are in Uppercase.
        Eg:
            1) a = "TESTING COLLEGES"
            2) b = "TESTING 123"
            3) c = "Testing Colleges"
            4) print(a.isupper())    #True
            4) print(b.isupper())    #True
            4) print(c.isupper())    #False

    16) join() - It returns a string by joining all the elements of iterable (list, string, tuple, dictionary, set), separated by the given separator.
        Eg:
            1) m = {"bike": "Triumph", "model": "400 x", "type": "Cruiser"}
            2) n = ['1', '2', '3', '4']
            3) o = ('a', 'b', 'c', 'd')
            4) x = "@".join(m)
            5) y = "".join(n)
            6) z = "TC".join(o)
            7) print(x)
            8) print(y)
            9) print(z)
            output:
                bike@model@type
                1234
                aTCbTCcTCd

    17) lower() - Converts all characters in a String into a lowercase.
        Eg:
            1) a = "Testing COLLeges"
            2) print(a.lower())    #testing colleges

    18) replace() - Replace the specified value with another specified value.
        Syntax: str.replace(oldvalue, newvalue, count)
            ∴ count - Optional, A number specifying how many occurrences of the old value you want to replace. Default is all occurrences.
        Eg:
            1) word = "Testing colleges website"
            2) x = word.replace("website", "blogger")
            3) print(x)    #Testing colleges blogger

            1) word = "aaaaaa"
            2) x = word.repalce("a", "b", 2)
            3) print(x)    #bbaaaa

    19) partition() - It splits the string into a tuple containing three elements.
        Eg:
            1) word = "Testing colleges blogger"
            2) x = word.partition("colleges")
            3) y = word.partition("Testing")
            4) z = word.partition("XYZ")
            5) print(x)    #('Testing', 'colleges', "blogger")
            6) print(y)    #(' ', 'Testing', "colleges blogger")
            7) print(z)    #('Testing colleges blogger', ' ', ' ' )

    20) rfind() - Returns the position of the specified value from the right.
        Eg:
            1) word = "Testing colleges"
            2) print(word.rfind("g"))    #13
        (Here it finds the index of the first "g" from the right side, the index will be calculated from the left.)

    21) rindex() - It is almost the same as the rfind(). Returns the position of the specified value from the right. 
        Eg:
            1) word = "Testing colleges"
            2) print(word.rindex("g"))    #13

    Note: Difference between rfind() and rindex():- Both are almost the same but the only difference between them is that the rindex() method throws a ValueError if the substring cannot be found. Whereas the rfind() method returns value -1.

    22) split() - It converts a String into a list.
                split supports two parameters:
                    - separator (optional): Specifies the separator to use when splitting the string.
                    - maxsplit (optional): Maximum number of splits.
                    Syntax: str.split(separator, maxsplit)

        Eg: By default, the split is separated by whitespace
            1) word = "Testing colleges blogger"
            2) print(word.split())    #['Testing', 'colleges', 'blogger']

        Eg: We can separate the string with the specified separator.
            1) word = "Testing#colleges#blogger"
            2) x = word.split("#")
            3) print(x)    #['Testing', 'colleges', 'blogger']

        Eg: Split the string into specified times.
            1) word = "Testing#colleges#blogger"
            2) x = word.split("#", 1)
            3) print(x)    #['Testing', 'colleges#blogger']

    23) swapcase() - It converts all uppercase characters to lowercase and lowercase characters to uppercase.
        Eg:
            1) word = "Testing Colleges"
            2) print(word.swapcase())    #tESTING cOLLEGES

    24) title() - It converts the first character in every word to uppercase
        Eg:
            1) word = "Testing colleges blogger"
            2) Tword = word.title()
            3) print(Tword)    #Testing Colleges Blogger
            
            (If the word contains a number or symbol, the first letter after that will be converted to upper case.)
            1) word = "Testing $hello"
            2) Tword = word.title()
            3) print(Tword)    #Testing $Hello

    25) upper() - It converts String into Uppercase (Symbols and Numbers are ignored)
        Eg:
            1) word = "Testing Colleges blogger"
            2) ucword = word.upper()
            3) print(ucword)    #TESTING COLLEGES BLOGGER
 
    26) zfill() - It fills with zero (0) at the beginning of the string, until it reaches the specified length.
        Eg:
            1) word = "TC"
            2) print(word.zfill(6))    #0000TC

No comments:

Post a Comment