Custom Def #4: Generalized Definitions

Published June 1, 2020, 12:04 a.m.

Last time we copied and modified our definition to make a new definition.  This works but can make for long and messy code.  Simple is often better. It would be better if we can generalize our definition .

We can expand our use of definitions and find a more elegant way of handling different parts of speech. If we could input the part of speech that we wanted into the definition, then we could have one definition that would work for any part of speech.  Turns out that we can do that:

def getNewWord(part_of_speech):
	query = "Give me an %s, and press 'Enter'." % part_of_speech
	engine.say(query, query)
	engine.runAndWait()
	newword = input()
	return newword

Here is what is happening:  We supply a string: "Noun", "Adjective", "Adverb" etc. and then the code asks for what is needed at run-time.  Our string is defined as the variable 'part_of_speech'  so the query will ask for what we supply in the definition.  If we revisit our code and use our updated definition:

lines = []
# lines.append( "\n Now for the story! \n")
# lines.append( "Once upon a time there was a %s with 2 weak arms." % getNoun())
# lines.append( "The dog was very small and frail.")
lines.append( "One day a %s %s spoke to the dog and said..." % (getNewWord("adjective"), getNewWord("noun")))
# lines.append( "'You are too weak.  You must eat protein %s!'" % getNoun())
# lines.append( "The dog was annoyed, but he started excercising daily.")
# lines.append( "Pretty soon, he became stronger and more muscular!")
# lines.append( "Now the dog shows off his %s on his own workout videos sponsored by P-89-X!"% getNoun() )
# lines.append( "The End!")

and run with:

C:\PythonProject>python madlib.py
Give me an adjective, and press 'Enter'.
ugly
Give me an noun, and press 'Enter'.
duckling
One day a ugly duckling spoke to the dog and said...

The code works the same as before but using a single definition that takes input. This is a more elegant and general definition for requesting a part of speech.

Next time we will look at using python dictionaries and  modify our definition again so that it can detect when and where to add the parts of speech that we want to add.  See you in the next tutorial!

skip_nextCustom Def #5: Dictionaries and Definitions
  • Custom Def #1: Import pyttsx3

  • Custom Def #2: Read a story from lines.

  • Custom Def #3: Using Multiple Definitions

  • Custom Def #4: Generalized Definitions
    (currently viewing)
  • Custom Def #5: Dictionaries and Definitions

  • Custom Def #6: Python Pickles

  • Custom Def #7: Search and Replace in Lines

  • Custom Def #8: Now for the Story...