CodingNic

Python Foundations

Comments and Clean Code

Python Foundations 16 min read

Comments and Clean Code

Comments and Clean Code

Writing code is not only about making programs work. Good code should also be easy to read, understand, and maintain. Comments and clean coding habits help you write professional Python programs.

What Is a Comment?

A comment is text inside your code that Python ignores when the program runs.

Use the # symbol to create a comment.

python
# This is a comment
print("Hello")

Why Comments Matter

Comments help explain:

  • What the code does
  • Why a decision was made
  • Important reminders
  • Complex logic

Single-Line Comments

Use # for short notes.

python
# Store the user's name
name = "Alex"

# Print a greeting
print("Hello", name)

Inline Comments

Comments can appear after code, but use them carefully.

python
age = 25  # User age

Clean Code Principles

Clean code is readable and organized.

Use Clear Names

python
student_name = "Maya"
total_price = 49.99

Instead of:

python
x = "Maya"
y = 49.99

Keep Code Simple

python
score = 90
passed = score >= 50

Use Consistent Formatting

python
name = "Sam"
age = 20
country = "Kenya"

Avoid Too Many Comments

Do not comment obvious code.

Bad example:

python
# Print hello
print("Hello")

Better code needs fewer comments because it is already clear.

Code Along

python
# Student information
student_name = "Amina"
grade = 88

# Display result
print(student_name)
print(grade)

Mini Challenge

Improve this code by renaming variables and adding useful comments.

python
a = "John"
b = 95
print(a)
print(b)

Real World Use Case

Teams working on large software projects rely on clean code so other developers can understand, debug, and improve the program quickly.

Quiz

  1. What symbol starts a comment in Python?
  2. Does Python run comment lines?
  3. Which is better: x or user_name?
  4. Why is clean code important?

Assignment

Write a small program about yourself using at least three variables and add helpful comments explaining the code.

Summary

You learned how comments work, when to use them, and how clean code practices make Python programs easier to read and maintain.