livepython.net
CHAPTER 06Comments
6.4  PRACTICE

Python Comments Practice Questions for Beginners

Chapter 6 Recap and Practice

You can now explain your code to people, and switch lines on and off while you work. Here is the chapter in one table:

You writeIt does
# a notea comment: Python skips everything after # on that line
price = 50 # in rupeesan inline comment: two spaces, #, one space
# on each linea note over several lines
"""…""" at the topa docstring: a description of a file (or, later, a function)
print("#Python")# inside quotes is just text
# print("debug")commenting out: the line is switched off
# TODO: …a reminder of unfinished work

And the habits that make comments useful:

  • Explain why, not what the code already shows.
  • Skip the obvious; comment the tricky parts.
  • Update comments when you change the code.
  • Prefer clear names; they never go out of date.
  • Delete commented-out code and debug prints when you're done.

Practice questions

Most of these programs print the same output with or without comments, so the tests can't check your comments. Write them anyway: that's the skill.

Python comments

  1. 44.Python Program to Print a Hashtag Inside a StringEasySolve
  2. 45.Fix a Python Program with a Comment Missing Its #EasySolve

Good comments

  1. 46.Python Program to Calculate a Bill with Clear CommentsEasySolve
  2. 47.Python Program to Explain a Calculation with CommentsMediumSolve

Commenting out code

  1. 48.Fix a Python Program by Commenting Out Debug PrintsEasySolve
  2. 49.Fix a Python Program by Commenting Out an Unfinished LineMediumSolve
  3. 50.Fix and Tidy a Messy Python ProgramHardSolve

Good comments explain why; good names explain what. Next, your programs will start talking to the user.