Accumulate output in a variable

Tags
Summary

Rather than have a bunch of print()s, assemble what you want to output into a variable, and print() that.

Situation

You have more than a handful of print() statements in a program.

Action

Make a new variable, and add output that. Instead of this:

  • if animal == 'dog':
  •     print('The best animal!')
  • elif animal == 'goat':
  •     print('Goats are cool!')
  • elif animal == 'cat':
  •     print('Cats are OK, I guess.')

Do this:

  • if animal == 'dog':
  •     message = 'The best animal!'
  • elif animal == 'goat':
  •     message = 'Goats are cool!'
  • elif animal == 'cat':
  •     message = 'Cats are OK, I guess.'
Where referenced