Comments are one of the most important features in Python programming. Although comments are ignored by the Python interpreter and do not affect program execution, they play a vital role in making code easier to understand, maintain, and debug. Whether you are writing a small script or developing a large Data Analytics or Machine Learning project, comments help explain the purpose of the code to yourself and other developers.
Professional developers spend a significant amount of time reading existing code rather than writing new code. Well-written comments make it easier to understand complex logic, explain assumptions, describe algorithms, and document important information. However, comments should complement the code rather than replace clear and meaningful code.
A comment is a line of text that is ignored by the Python interpreter. It is written to explain what a particular piece of code does, provide notes, describe algorithms, or temporarily disable code during testing.
Comments improve code readability and collaboration, especially in projects where multiple developers work together.
Python uses the # symbol to create a single-line comment. Everything written after the hash symbol on the same line is ignored by Python.
# This is a comment
print("Hello Python")
You can also write comments after a statement.
age = 25 # Store employee age
salary = 45000 # Monthly salary
# Calculate total marks
math = 80
science = 90
english = 85
total = math + science + english
print(total)
The comment explains the purpose of the code without affecting the program.
Python does not have a dedicated syntax for multi-line comments like some other programming languages. Instead, developers typically write multiple consecutive single-line comments using the # symbol.
# Read customer data
# Remove duplicate records
# Calculate yearly revenue
# Generate dashboard
This approach is the most commonly accepted way to write multi-line comments in Python.
# Step 1: Load dataset
# Step 2: Clean missing values
# Step 3: Remove duplicates
# Step 4: Perform analysis
print("Data Processing Started")
Docstrings (Documentation Strings) are special strings enclosed within triple quotes (""" """) or (''' '''). They are used to document modules, functions, classes, and methods.
Unlike ordinary comments, docstrings become part of the object’s documentation and can be accessed using the help() function or the __doc__ attribute.
def calculate_average(numbers):
"""
Calculates the average of a list of numbers.
Parameters:
numbers (list): List of numeric values.
Returns:
float: Average value.
"""
return sum(numbers) / len(numbers)
Now the documentation can be viewed using:
help(calculate_average)
class Student:
"""
Represents a student in the college database.
"""
def __init__(self, name):
self.name = name
"""
Sales Analysis Project
This module performs customer segmentation
using Python and Machine Learning.
"""
| Feature | Comments | Docstrings |
|---|---|---|
| Purpose | Explain code | Document modules, classes and functions |
| Interpreter | Ignored | Stored as documentation |
| Syntax | # | Triple Quotes |
| Accessible using help() | No | Yes |
| Professional Documentation | No | Yes |
Imagine returning to a project after six months. Without comments, understanding the purpose of every variable, function, and algorithm becomes difficult. Good comments save development time and reduce confusion.
In Data Analytics projects, comments often explain:
# Add numbers
total = price + tax
This comment is unnecessary because the code is already obvious.
# GST is added separately because product prices exclude tax.
total = price + tax
The second comment explains why the calculation is performed.
An identifier is the name given to variables, functions, classes, modules, or objects. Choosing meaningful identifiers makes programs easier to understand and maintain.
student_name
employee1
total_marks
_price
average_salary
1student
employee-name
student name
class
salary$
Each invalid identifier violates one or more naming rules.
Python allows developers to choose almost any valid identifier as a variable name, but meaningful names are strongly recommended.
student_age
total_sales
average_income
customer_count
employee_salary
a
x
abc
temp1
data2
Meaningful variable names make the program self-explanatory.
In this section, you learned how Python comments improve code readability, the difference between comments and docstrings, how documentation works in professional projects, and the rules for creating valid Python identifiers and meaningful variable names. In the next chunk, you will learn about naming conventions, Python reserved keywords, the PEP 8 style guide, writing readable code, and common syntax errors that every Python developer should avoid.
Although Python allows developers to choose almost any valid identifier, professional programmers follow standard naming conventions. These conventions make code easier to read, understand, and maintain. The official Python style guide, known as PEP 8, recommends consistent naming styles for variables, functions, classes, modules, packages, and constants.
Following naming conventions becomes even more important in large Data Analytics and Machine Learning projects where hundreds of Python files are maintained by multiple developers.
Variable names should be written in lowercase letters. If a variable contains multiple words, separate them using an underscore (_). This naming style is called snake_case.
student_name = "Rahul"
employee_salary = 55000
total_sales = 250000
average_marks = 88
customer_count = 1450
StudentName
Student_Name
studentName
TOTALSALES
X
Meaningful variable names make code self-explanatory and reduce the need for unnecessary comments.
Function names should also follow the snake_case naming style. A function name should clearly describe the action it performs.
def calculate_salary():
pass
def load_dataset():
pass
def remove_duplicates():
pass
def train_model():
pass
Avoid vague function names such as:
def test():
pass
def temp():
pass
def data():
pass
A descriptive function name makes programs much easier to understand.
Python recommends using PascalCase for class names. In PascalCase, every word begins with a capital letter without spaces or underscores.
class Student:
class EmployeeDatabase:
class SalesPrediction:
class MachineLearningModel:
class student
class employee_database
class machine_learning_model
Constants are variables whose values should not change during program execution. Although Python does not enforce constants, developers use uppercase letters with underscores.
PI = 3.14159
MAX_USERS = 100
DATABASE_NAME = "sales"
DEFAULT_LANGUAGE = "English"
This convention immediately tells other developers that these values should remain unchanged.
A module is simply a Python file containing Python code. Module names should be short, meaningful, and written in lowercase.
student.py
database.py
data_cleaning.py
sales_analysis.py
Packages are folders containing multiple Python modules. Package names should also be written in lowercase without spaces.
analytics
utilities
machinelearning
dashboard
Python contains predefined words called keywords. These words have special meanings in the language and cannot be used as identifiers.
For example, the word if represents a conditional statement, while class is used to define a class. Since Python already understands their meaning, they cannot be used as variable or function names.
| Keyword | Purpose |
|---|---|
| if | Conditional statement |
| else | Alternative condition |
| elif | Multiple conditions |
| for | Loop |
| while | Loop |
| break | Exit loop |
| continue | Skip iteration |
| pass | Placeholder statement |
| class | Create class |
| def | Create function |
| return | Return value |
| try | Exception handling |
| except | Handle exception |
| finally | Always execute block |
| import | Import module |
| from | Import specific object |
| True | Boolean value |
| False | Boolean value |
| None | Represents no value |
class = "Python"
This produces a syntax error because class is a reserved keyword.
class_name = "Python"
PEP 8 stands for Python Enhancement Proposal 8. It is the official style guide for writing Python code. Rather than defining how Python works, PEP 8 provides recommendations for formatting code consistently so that it is easier to read and maintain.
Professional software companies, open-source projects, and data science teams generally follow PEP 8 to ensure that everyone writes code in a consistent style.
if marks > 40:
print("Pass")
Good:
total = price + tax
Bad:
total=price+tax
Good:
monthly_sales = 25000
Bad:
x = 25000
PEP 8 recommends keeping most lines within 79 characters to improve readability, especially when reviewing code or using split-screen editors.
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
Imports should generally appear at the top of the file before executable code.
a=100
b=50
c=a+b
print(c)
product_price = 100
tax_amount = 50
total_price = product_price + tax_amount
print(total_price)
The second example is easier to understand because the variables have meaningful names and proper spacing is used.
In this section, you learned the standard Python naming conventions for variables, functions, classes, modules, packages, and constants. You also explored Python reserved keywords and discovered why they cannot be used as identifiers. Finally, you were introduced to the PEP 8 style guide, which provides the best practices followed by professional Python developers to write clean, readable, and maintainable code. In the next and final chunk of this lesson, you will learn about writing readable code, common syntax errors, best practices, lesson summary, FAQs, MCQs, coding exercises, interview questions, and a mini project before completing the Python Syntax lesson.
Writing code that works is only one part of becoming a good Python programmer. Professional developers also focus on writing readable code. Readable code is easy to understand, modify, debug, and maintain. In real-world software development, data analytics, and machine learning projects, code is often read many more times than it is written.
Readable code follows consistent formatting, meaningful naming conventions, proper indentation, and the recommendations of the Python Style Guide (PEP 8). Clean code helps reduce bugs and improves collaboration among team members.
Whitespace refers to blank spaces, indentation, and blank lines used in a program. Although whitespace does not usually affect program execution, it greatly improves readability.
price = 100
tax = 18
total = price + tax
print(total)
price=100
tax=18
total=price+tax
print(total)
The first example is much easier to read because proper spacing is used around operators.
Blank lines separate different sections of code and improve readability. PEP 8 recommends using blank lines between functions, classes, and logical blocks of code.
name = "Rahul"
age = 22
print(name)
salary = 50000
print(salary)
Import statements should appear at the beginning of the Python file. Keeping imports organized makes it easy to identify the libraries required by the program.
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
data = pd.read_csv("sales.csv")
from math import sqrt
number = 25
print(sqrt(number))
from math import sqrt, factorial
import pandas as pd
import numpy as np
Aliases such as pd and np are widely accepted standards in the Python community.
A well-organized Python program usually follows this order:
"""
Student Management System
"""
import pandas as pd
MAX_STUDENTS = 100
def display_student():
print("Student Information")
display_student()
A syntax error occurs when Python cannot understand the structure of your code. These errors prevent the program from running until they are corrected.
Incorrect:
if marks > 40
print("Pass")
Correct:
if marks > 40:
print("Pass")
Incorrect:
if marks > 40:
print("Pass")
Correct:
if marks > 40:
print("Pass")
Incorrect:
print("Hello"
Correct:
print("Hello")
Incorrect:
name = Rahul
Correct:
name = "Rahul"
Incorrect:
class = "Python"
Correct:
class_name = "Python"
Incorrect:
if marks = 50:
print("Pass")
Correct:
if marks == 50:
print("Pass")
| Error | Description |
|---|---|
| SyntaxError | Python cannot understand the program structure. |
| IndentationError | Indentation is missing or inconsistent. |
| NameError | A variable or function name is not defined. |
| TypeError | An operation is performed on incompatible data types. |
| ValueError | A function receives a value of the correct type but an inappropriate value. |
| IndexError | A list index is outside its valid range. |
| KeyError | A dictionary key does not exist. |
| ModuleNotFoundError | The requested module is not installed or cannot be located. |
In this lesson, you learned the fundamental rules of Python syntax that every programmer must understand before writing Python programs. You explored Python statements, indentation, code blocks, comments, docstrings, identifiers, naming conventions, reserved keywords, and the PEP 8 style guide. You also learned how to write clean, readable code, organize Python files, and identify common syntax errors such as missing colons, incorrect indentation, unmatched parentheses, and misuse of reserved keywords. These concepts form the foundation of writing professional Python programs for Data Analytics, Machine Learning, Automation, and Software Development.
# symbol.Create a Python program named student_report.py that follows all the syntax rules learned in this lesson. The program should:
Congratulations! You have completed the Python Syntax lesson. In the next lesson, you will learn Python Variables and Data Types, where you’ll explore how Python stores information in memory, create variables, work with different data types such as integers, floats, strings, booleans, and understand type conversion. These concepts are essential for building Python programs used in Data Analytics and Machine Learning.