Comments and Readable Code
Write notes to yourself and keep your Python easy to read
- write a comment with the
#symbol, - choose clear variable names that explain themselves,
- keep code tidy with spaces and blank lines so it is easy to fix.
1. What is a comment?
A comment is a line (or part of a line) that Python does not run. It is a note for humans. In Python you start a comment with the hash symbol #. Everything after the # on that line is ignored by Python.
# This program greets the user by name
name = input("What is your name? ") # ask the user to type a name
print("Hello,", name) # show a friendly greeting
Expected output (after you type Sam):
What is your name? Sam
Hello, Sam
Notice the two kinds of comment: a whole line that starts with #, and a short note at the end of a line after the code. Python skips both.
2. Python ignores comments
Because Python ignores everything after #, comments never change what your program does. You can even "turn off" a line of code by putting a # in front of it.
# The next line is just a note for people. Python ignores it.
print("Python runs this line")
# print("Python never runs this line")
Expected output:
Python runs this line
The second print is now a comment, so it does nothing. This trick is handy when you want to test one line at a time.