Python Classroom Series – 17/Sept/2020

Closures in Python

  • A closure is a dynamically generated by other function and can both change & remember the values of variables that were created outside the functions
def Prettify(message):
    """
    This method will capitalize the string
    :return:
    """

    def cap_message():
        return message.capitalize()

    return cap_message


if __name__ == "__main__":
    print(Prettify(input("Enter the message"))())

  • The same code is refactored as
def prettify(msg):
    """
    This method will capitalize the string
    :return:
    """

    def cap_message():
        return msg.capitalize()

    return cap_message


if __name__ == "__main__":
    message = input("Enter the message")
    prettify_func = prettify(message)
    print(prettify_func())

Anonymous functions: lambda

  • A python lambda function is an anonymous function that is expressed in a single statement
def decorate_word(word):
    """
    We decorate the word by capitalizing and adding ! at the end
    :param word: word to be decorated
    :return: <Word!>
    """
    return f"{word.capitalize()}!"


def rename_heros(superheros):
    """
    :param superheros:
    :return:
    """
    for superhero in superheros:
        my_func = lambda hero: f"{hero.capitalize()}!"
        print(my_func(superhero))


if __name__ == "__main__":
    rename_heros(['ironman', 'thor', 'hulk'])

  • Sample2
def square(x):
    return lambda: x * x


lamda_list = [square(number) for number in range(1, 10)]
for lambda_function in lamda_list:
    print(lambda_function())

Generators in Python

  • A function with a yield statement is referred as generator
def generate_traffic_signals():
    signal = 1
    print(f"returning red with signal value {signal}")
    yield signal

    signal += 1
    print(f"returning green with signal value {signal}")
    yield signal

    signal += 1
    print(f"returning orange with signal value {signal}")
    yield signal


if __name__ == "__main__":
    for signal in generate_traffic_signals():
        print(signal)

Ways of writing better python code (Contd..)

  1. Know which version of python you are using
python --version

# in some linux distributions
python --version

# python code
import sys
print(sys.version)
print(sys.version_info)
  1. Follow PEP-8 STYLE GUIDE: Since we are using pycharm try to fix all the issues shown by pycharm Preview
  2. Prefer interpolated f-strings over c-style format strings.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

About learningthoughtsadmin