Overview
Comments can be used to explain Python code, make the code more readable, or prevent execution when testing code since they are ignored when running.
Creating a Comment
Comments starts with a #.
#This is a comment
print('Hello World')
Comments can be placed at the end of a line, and Python will ignore the rest of the line.
print('Hello World') #This is a comment (more code here that will be ignored)
Comments can be placed at the beginning of a line, and Python will ignore the entire line of code, and simply move to run the next line.
#print('Hello World')
print('Hello Universe')
Multiline Comments
Python does have a syntax for multiline comments. To add a multiline comment you would insert a # for each line.
#This is a comment
#and it is written
#on three lines
print('Hello World')
Or, since Python will ignore string literals that are not assigned to a variable, you can add a multiline string (triple quotes) in your code, and place your comment inside it.
"""
This is a comment
and it is written
on three lines
"""
print('Hello World')
Note
The first method is preferred. The second method is kind of a hack.
Python Notes:
- The most recent major version of Python is Python 3; however, Python 2 is still in use and quite popular, although not being updated with anything other than security updates
- Python uses new lines to complete a command, as opposed to other programming languages which often use semicolons or parentheses
- Python relies on indentation, using whitespace to define scope, such as the scope of loops, functions, and classes; other programming languages often use curly-brackets for this purpose
- Python string methods return new values, and DO NOT change the original string
- Python tuples are unchangeable after created (their items CANNOT be changed or re-ordered at a later point)
- Python sets are unordered (may appear in random orders when called), unchangeable (the value of individual items cannot be changed after creation), unindexed (items cannot be referred to by index or key), and duplicates are NOT ALLOWED
- As of v3.7, Python dictionaries are ordered and duplicates ARE ALLOWED; in v3.6 and earlier, dictionaries were unordered (did not have a defined order and could not be referred to using an index)
We’d like to acknowledge that we learned a great deal of our coding from W3Schools and TutorialsPoint, borrowing heavily from their teaching process and excellent code examples. We highly recommend both sites to deepen your experience, and further your coding journey. We’re just hitting the basics here at 1SMARTchicken.