Python Classroom Series – 10/Sept/2020

Puzzle: Pig Latin Word

  • Solution:

def pig_latin(word):
    """
    This method will return the pig latin word
    :param word: word to be encrypted to pig_latin
    :return: word encrypted to pig_latin
    """
    if word[0] in 'aeiou':
        return f"{word}way"

    return f"{word[1:]}{word[0]}ay"


def pig_latin_sentence(sentence):
    """
    This method will return the pig latin word
    :param sentence: sentence to be encrypted to pig_latin
    :return: sentence encrypted to pig_latin

    """
    output = []
    for word in sentence.split():
        output.append(pig_latin(word))

    return ' '.join(output)

Python functions (contd..)

  • From python 3 it is possible to specify keyword only arguments
def print_colors(color, *,start=0, end=10)"
    ....
    ....
  • * in the function definition that the following parameters are named arguments
  • Sample Code
def print_colors(colors, *, start=0, end=100):
    """
    This method is used to demonstrate named argumets
    :param colors: colors
    :param start: named argument start
    :param end:  named argument end
    """
    for color in (colors[start:end]):
        print(color, end=",")
    print()

if __name__ == "__main__":
    colors = ['Red', 'Green', 'Blue', 'Yellow', 'Orange', 'Purple', 'Violet', 'Indigo', 'White', 'Black']
    print_colors(colors)
    print("start=2 end =6")
    print_colors(colors, start=2, end=6)
    print("start=3")
    print_colors(colors, start=3)
    print("end = 5")
    print_colors(colors, end=5)

Preview

Mutable & Immutable Arguments

  • It is a good practice to either document that argument may be changed or return the new value
  • Don’t write functions as shown below Preview

Functions are First Class Citizens

  • We can assign function to variables, use them as arguments to other functions & return them from functions.
def run_anything(func):
    """
    Pass any function to it
    :param func: function
    :return: 
    """
    func()


def pi():
    """
    This function prints pi
    :return: 
    """
    print('3.14')


if __name__ == "__main__":
    run_anything(pi)

Preview

Exercises

  1. Write a python function which prints the first and last elements in the sequence
    • Sample:
    tuple_sample = (1,2,3)
    print(first_last(tuple)) => 13
    
    list_sample = [1,2,4]
    print(first_last(tuple)) => 14
    

Leave a Comment

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

About learningthoughtsadmin