Comments in Python#
(Click here for the German version of this page)
Comments in Python are relatively simple. There is just one way to create comments.
When a pound symbol (#
) appears outside of a string, then everything to the right of the symbol in the given line is treated as a comment.
x = 5 # Assign the value 5 to x
# ^^^^^^^^^^^^^^^^^^^^^^^^
# Code comment
Normally, there is no way to create a comment spanning over multiple lines, such as in C/C++/Java with
/*
This is a comment
This is also a comment
And this is also a comment
*/
Therefore one would have to comment out the lines individually in Python.
# This is a comment
# This is also a comment
# And this is also a comment
To make it a little bit simpler, it is possible to treat the content to be commented out, as a string without any assignment. Since the string is not assigned, it will just be ignored. A string spanning over multiple lines can be created using so-called “triple quotes”, which refers to three sequential double quotes.
Exercise#
Now it is your turn!
Please modify the below program WITHOUT removing code or moving it to a different spot, so that the program outputs “Hello World!”.
You are allowed to use triple quotes (”””
).
my_output = "Hello World!"
my_output = 0
for i in range(1, 100+1):
my_output += i
print(my_output)
5050
Solution
my_output = "Hello World!"
"""
my_output = 0
for i in range(1, 100+1):
my_output += i
"""
print(my_output)
# --> "Hello World!"