Comments

Single-Line Comments

Discover how to use single-line comments in Python to enhance your code’s clarity. This lesson guides you through adding comments with the hash symbol and demonstrates how multiple comments help describe complex code functions, improving readability and maintainability.

Single-line comments

Single-line comments can be added by simply putting the hash symbol before the comment.

Let’s take a look at an example that displays a message on the screen. This code uses comments to describe the functionality.

message = "Let's learn Python Comments today" # Displaying the message to the user on the console print("Message for the user = " + message)

Single-line comments in Python

Multiple single-line comments

In Python, we can add as many comments as we want to describe the working of the code.

For instance, this piece of code calculates the amount of work to be done in a day work_per_day using information such as total_work, my_progress_so_far, days_spent, and all_days. It consists of multiple single-line comments, and the format for each comment remains the same.

# Given values for the problem total_work = 100 my_progress_so_far = 27 days_spent = 20 all_days = 60 # Calculating remaining work and days remaining_work = total_work - my_progress_so_far days_remaining = all_days - days_spent # Calculating work per day work_per_day = remaining_work / days_remaining # Printing the result print(f'You need to do approximately {work_per_day:.3f} units of work per day to complete the task.')

Multiple single-line comments in Python

Note: The .3f in the {work_per_day:.3f} statement allows us to specify the number of decimal places to print. In this case, work_per_day is printed up to three decimal places.

On this page

    In This Module