Can we write comments without using # in python?

can we write comments without using # in python?

Hi there, and welcome to the forums.

In Python the main, and really only way of adding an official comment is by using the # signifier. However there is an unofficial way of doing it based on how the python interpreter works. You can create multi-line strings using triple quotes like so.

"""
Hello there I am a multiline string.
I have multiple lines in this string.
Hello World!
"""

These multi-line strings are a good way of recording paragraphs in Python code and saving them to a variable. However the quirk of them is that multi-line strings are ignored by the Python interpreter unless they are explicitly being assigned to a variable. What this means is that you can actually use them as a form of multi-line, formatted comment in your code, as unless they’re assigned to a variable they won’t be included when running. See below for example:

""" This is a function that takes a number n and prints all the numbers from n to 1. It uses recursion instead of a loop to do this. Once it reaches the end of the sequence, it prints the word 'FIN' instead of 0. """ def count_backwards(n): if n == 0: print("FIN") else: print(n) count_backwards(n-1) return 0 count_backwards(10) count_backwards(15)

We can see here that the multi-line string stands out as far as comments go and can look nice, plus the code doesn’t break despite there just being a string there. As far as I am aware this is the only other way to do commenting in Python, if you find something else do let us know!

2 Likes