Friday, June 28, 2019

Comments in Python

Single Line Comment


Python uses the symbol # to represent a comment. Unlike many languages like C++ and C# there is no begin and end comment.

#This is a comment
print("Hello World")
#This is a comment too

You can also put a comment after a line of code but not before a line of code.


print("Hello World") #This is a comment too!

Python comments are stripped before the code is compiled to byte code for execution so unlike some interpreted languages it does not cause a penalty during runtime. If there are a bunch of comments then it could cause extra compile time.

A Multiline Comment Hack

I was quickly corrected by one of my fellow python developers when I referred to multiline strings as comments. They are in fact just strings that are not assigned a variable.

"""
This is a multiline string.
It is often used for long comments...
but it is really just a string that is not assigned to a variable
"""
def print_hello():
  print("Hello World")

No comments:

Post a Comment

nonlocal keyword

The nonlocal keyword is used to allow an inner function to access variables defined in an outer function. Without using the nonlocal keywo...