Tuesday, November 15, 2022

Functions - Python Programming for Beginners Practice Exercise 7

Exercise 7:

Create a fill in the blank word game. Prompt the user to enter a noun, verb, and an adjective. Use those responses to fill in the blanks and display the story.

Write a short story. Remove a noun, verb, and an adjective.

Create a function to get the input from the user.

Create a function that fills in the blanks in the story you created.

Ensure each function contains a docstring.

After the noun, verb, and adjective have been collected from the user, display the story using their input.

Solution:

  1. #!/usr/bin/env python3
  2.  
  3. def get_word(word_type):
  4. """Get a word from a user and return that word."""
  5.  
  6. # The lower() function converts the string to lowercase before testing it
  7. if word_type.lower() == 'adjective':
  8. # Use 'an' in front of 'adjective'
  9. a_or_an = 'an'
  10. else:
  11. # Otherwise, use 'a' in front of 'noun' or 'verb'
  12. a_or_an = 'a'
  13. return input('Enter a word that is {0} {1}: '.format(a_or_an, word_type))
  14.  
  15.  
  16. def fill_in_the_blanks(noun, verb, adjective):
  17. """Fills in the blanks and returns a completed story."""
  18.  
  19. # The \ lets the string continue on the next line to make the code easier to read
  20. story = "In this course you will learn how to {1}. " \
  21. "It's so easy even a {0} can do it. " \
  22. "Trust me, it will be very {2}.".format(noun, verb, adjective)
  23. return story
  24.  
  25.  
  26. def display_story(story):
  27. """Displays a story."""
  28. print()
  29. print('Here is the story you created. Enjoy!')
  30. print()
  31. print(story)
  32.  
  33.  
  34. def create_story():
  35. """Creates a story by capturing the input and displaying a finished story."""
  36. noun = get_word('noun')
  37. verb = get_word('verb')
  38. adjective = get_word('adjective')
  39.  
  40. the_story = fill_in_the_blanks(noun, verb, adjective)
  41. display_story(the_story)
  42.  
  43. create_story()

No comments:

Post a Comment