fbpx

In this article, we will learn the fundamentals of creating Python Function by our own. Let’s take an example. Here is the problem statement:

Problem statement:

Given a list of strings, return the count of the number of strings where the string length is 3 or more and the first and last chars of the string are the same.
Input : [‘gang’, ‘baby’, ‘ok’, ‘no’, ‘Area’,’Bulb’,’bush’,’ERASE’]
Output: [‘gang’, ‘Area’, ‘Bulb’, ‘ERASE’]

Actual Code :

# create a function by name listcrowl which will take one python list input as argument 
def listcrowl(a):
#let's initiate a list l as blank 
    l=[]
#As we get a list as input to the function, we need to run a loop and pull each element of the list one by one in i
    for i in a: 
#in the first loop i will be a python string that is first element of the list , you should pull first char by i[0] 
#and last char by i[0] of the string . Convert them in upper case so as small case u and  capital U both can 
# be converted into Capital U and compare will not be case sensitive. After than do another check of string length
# using function len() . 
        if (i[0].upper()==i[-1].upper() and len(i)>2):
#If both condition satisfied then we append the list l ,which we created at the start of the code.
            l.append(i)
        else :
# else we continue in the loop until we get last element of the list .
            continue 
# once the loop is complete , return the list l 
    return l

we are done with creating a function. Now create a list a using the input list given in the problem statement and call the function and see if the output is correct or now.

a=['gang', 'baby', 'ok', 'no', 'Area','Bulb','bush','ERASE']
listcrowl(a)

If you have any doubt please comment below or Contact us and we will be happy to help .

To learn Python check out this .

By tecksed

Leave a Reply

Your email address will not be published. Required fields are marked *

×