Wednesday, November 16, 2022

Modules - Python Programming for Beginners Practice Exercise 11

Exercise 11:

Update the "What Did the Cat Say" program from an earlier section so that it can be run directly or imported as a module. When it runs as a program is should prompt for input and display a cat "saying" what was provided by the user. Place the input provided by the user inside a speech bubble. Make the speech bubble expand or contract to fit around the input provided by the user.

Sample output when run interactively


Next, create a new program called cat_talk.py that imports the cat_say module. Use a function from the cat_say() module to display various messages to the screen.

Sample output when used as a module:


Solution 1:

#!/usr/bin/env python3

def cat_say(text):
    """Generate a picture of a cat saying something"""
    text_length = len(text)
    print('            {}'.format('_' * text_length))
    print('          < {} >'.format(text))
    print('            {}'.format('-' * text_length))
    print('          /')
    print(' /\_/\   /')
    print('( o.o )')
    print(' > ^ <')

def main():
    text = input('What would you like the cat to say? ')
    cat_say(text)

if __name__ == '__main__':
    main()

Solution 2:

#!/usr/bin/env python3

import cat_say

def main():
    cat_say.cat_say('Feed me.')
    cat_say.cat_say('Pet me.')
    cat_say.cat_say('Purr.  Purr.')

if __name__ == '__main__':
    main()

No comments:

Post a Comment