Monday, June 27, 2022

How to write comments in Python?

When writing a script in Python programming language it is suggested that you write comments. Comments are very important since they give you additional information about what a specific line of code or chunk of code does. During the program development, it is good practice to sometimes comment on the parts of code to provide additional information. Example 1 Create a script and write the following code.
#This is the first comment that I'm going to create.
#After typing first # everything is ignored by Python
print("This is the first line of code that Python can execute.")
# You can put a comment right after the code and it will be ignored by Python
# The comments can be used to disable lines of code.
#To disable the line of code simply put # before the line of code.
#print("This will not be executed in Python")
print("This # will be executed.")

Solution: After creating a script and running it the following output will be produced.
This is the first line of code that Python can execute.
This # will be executed.
When the script and the output are compared it can be noticed that all the lines that started with # were skipped by Python.
As you can see Python has executed two print commands and as output shows only the strings inside the parenthesis of print functions. In Spyder the hashtag sign (#) can be created by pressing Ctrl and 1 simultaneously, or by pressing SHIFT + 1

How to create comments in multiple lines?

To create a comment in multiple lines each line has to begin with #. In Example 1 first two lines of code are comments and each line begins with #. So to create comments in multiple lines each line has to begin wtih the character #.

Why is the # -*- coding: utf-8 -*- skipped?

Every time you create a new Python script in Python the script will contain the following lines of code.
# -*- coding: utf-8 -*-
"""
Created on Thu Jun 23 12:38:08 2022

@author: user
"""
This code contains the line # -*- coding: utf-8 -*- which starts with sign for comments (#). Apparently the Python ignores that as the code however, a "hack" (workaround) for problems is developed for problems with setting and detecting the format of a file.
The UTF-8 is commonly used encoding, and Python defaults to using it. The UTF stands for Unicode Transformation Format and number 8 represents the 8-bit values are used for encoding.

How come the string "This # will be executed" is shown as output?

This line was a string inside the parenthesis of print function which means that is treated as a string so the sign here does not have influece, i.e. does not create a comment. # sign is treated as a string since it is inside the string.

No comments:

Post a Comment