Practice: Python Comments
Q1. Comment a print
Write a program that has a comment line # Greeting followed by a line that prints Hello.
Goal: Write a single-line comment.
Q2. Inline comment
Write x = 5 with an inline comment saying # five, then print x.
Goal: Write an inline comment.
Q3. Function docstring
Write a function square(n) with a docstring that returns n * n, and print square(6).
Goal: Write a docstring.
Q4. Read a docstring
Define a function hi() with the docstring Say hi. and print its docstring using __doc__.
Goal: Read __doc__.
Q5. Disable a line
Write three prints for A, B and C, but disable the print for B using a comment.
Goal: Comment out code.
Q6. Hash inside text
Print the text Tag #python so that the hash symbol appears in the output.
Goal: Know # in strings.
Q7. Multi-line note
Write two comment lines above a line print(1 + 1). Only the result should be printed.
Goal: Write multi-line comments.
Q8. Comment with calculation
Calculate the area of a rectangle 4 by 5 with an explaining comment and print it.
Goal: Add helpful comments.
Q9. Ignored comment
What is printed?
print('one') # print('two')
print('three')Goal: Predict output with comments.
Q10. Hash in a string
What is printed?
print('Room #7 # floor 2')Goal: Hash in strings.
Q11. Commented-out line
What is printed?
a = 2
# a = 10
print(a)Goal: Commented code.
Q12. Docstring output
What is printed?
def f():
"""Does nothing."""
pass
print(f.__doc__)Goal: Read a docstring.
Q13. Missing docstring
What is printed?
def g():
return 1
print(g.__doc__)Goal: No docstring gives None.
Q14. Comment after calculation
What is printed?
print(3 + 4) # + 100Goal: Inline comment effect.
Q15. Triple quotes as string
What is printed?
note = '''line one
line two'''
print(note)Goal: Triple quotes make strings.
Q16. Length of a docstring
What is printed?
def f():
"""Hi"""
print(len(f.__doc__))Goal: Docstring is a string.
Q17. Fix the comment symbol
This code uses // for a comment and fails. Fix it so it prints 8.
x = 8 // value
print(x)Goal: Fix a comment symbol.
Q18. Fix the broken comment lines
The second note line is not a comment and causes an error. Fix it so the program prints Done.
# first note
second note
print('Done')Goal: Fix multi-line comments.
Q19. Why not what
A line says x = x + 1 # add one to x. Explain why this comment is poor and give a better one.
Goal: Write useful comments.
Q20. Comment or docstring
You want to describe what a function does so help(function) can show it. Do you use a # comment or a docstring?
Goal: Choose docstring vs comment.