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.
# 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.
# Store the user's name
name = "Alex"
# Print a greeting
print("Hello", name)
Inline Comments
Comments can appear after code, but use them carefully.
age = 25 # User age
Clean Code Principles
Clean code is readable and organized.
Use Clear Names
student_name = "Maya"
total_price = 49.99
Instead of:
x = "Maya"
y = 49.99
Keep Code Simple
score = 90
passed = score >= 50
Use Consistent Formatting
name = "Sam"
age = 20
country = "Kenya"
Avoid Too Many Comments
Do not comment obvious code.
Bad example:
# Print hello
print("Hello")
Better code needs fewer comments because it is already clear.
Code Along
# 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.
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
- What symbol starts a comment in Python?
- Does Python run comment lines?
- Which is better:
xoruser_name? - 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.