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:

  1. #!/usr/bin/env python3
  2.  
  3. def cat_say(text):
  4. """Generate a picture of a cat saying something"""
  5. text_length = len(text)
  6. print(' {}'.format('_' * text_length))
  7. print(' < {} >'.format(text))
  8. print(' {}'.format('-' * text_length))
  9. print(' /')
  10. print(' /\_/\ /')
  11. print('( o.o )')
  12. print(' > ^ <')
  13.  
  14. def main():
  15. text = input('What would you like the cat to say? ')
  16. cat_say(text)
  17.  
  18. if __name__ == '__main__':
  19. main()

Solution 2:

  1. #!/usr/bin/env python3
  2.  
  3. import cat_say
  4.  
  5. def main():
  6. cat_say.cat_say('Feed me.')
  7. cat_say.cat_say('Pet me.')
  8. cat_say.cat_say('Purr. Purr.')
  9.  
  10. if __name__ == '__main__':
  11. main()

No comments:

Post a Comment