Skip to main content

Syntax and Coding Standards

What is a Programming Language?

A programming language is a formal set of instructions that can be used to communicate with a computer. It acts as a medium through which humans can write programs to solve problems, automate tasks, or build applications. Programming languages can be broadly classified into two types: low-level languages (closer to machine code) and high-level languages (closer to human languages, making them easier to learn and use).

Python is a high-level, interpreted language that emphasizes readability and simplicity, making it one of the most beginner-friendly programming languages.

Understanding the Interpreter

Python uses an interpreter to execute code. An interpreter is a program that reads and executes code line by line, translating it into machine instructions. This differs from a compiler, which translates the entire program into machine code before execution.

Python's interpreter offers several advantages:

Immediate feedback via an interactive mode (REPL). No need for compilation, which makes it faster to test code. Portability, as Python code can run on different platforms without modification, provided the Python interpreter is available. To run Python code, you can:

  1. Use the interactive shell (type python in your terminal or command prompt).
  2. Save your code in a .py file and run it using python <filename>.py

Python's popularity stems from several factors:

  1. Simple Syntax: Python reads almost like English, making it accessible to beginners.
  2. Versatility: It is used in diverse fields, including web development, data science, machine learning, automation, and more.
  3. Rich Ecosystem: Python has an extensive library ecosystem, offering pre-built solutions for almost any programming need.
  4. Community Support: A large, active community ensures ample resources, tutorials, and problem-solving forums.

Strengths of Python

  1. Ease of Learning: Simple syntax and readability.
  2. Flexibility: Python supports multiple programming paradigms, such as procedural, object-oriented, and functional programming.
  3. Extensive Libraries: Libraries like NumPy, Pandas, Flask, and TensorFlow make development faster.
  4. Cross-Platform Compatibility: Python runs seamlessly on Windows, macOS, and Linux.
  5. Rapid Development: Ideal for prototyping and iterative development.

Syntax of a programming language?

The syntax of a programming language refers to the set of rules that define how programs are written in that language. These rules specify the structure, format, and order of symbols, keywords, operators, and other elements that the programming language recognizes.

Understanding a programming language's syntax is the foundation for writing functional and error-free programs.

Python (Simple Syntax):

x=0
if x > 0:
print("Positive")
else:
print("Negative or Zero")

Java (More Structured Syntax):

if (x > 0) {
System.out.println("Positive");
} else {
System.out.println("Negative or Zero");
}

Basic Python Syntax

Let’s start with Python’s core syntax. The key to mastering Python is understanding its simplicity and emphasis on readability.

1. Printing Output

Hello = "hello"
Anupama = "Anupama"
print("Hello" + "Anupama")

2. Variables

Variables in Python do not require explicit type declaration. Types are inferred dynamically.

name = "anu"  # String
age = 2 # Integer
height = 5.6 # Float
is_student = True # Boolean

3. Indentation

Python uses indentation to define blocks of code, unlike other languages that use braces () or keywords.

age = 5
if age > 18:
print("You are an adult.")
#print("You can vote.")
else:
print("You are not an adult.")
#print("You can't vote")

4. Comments Comments start with a # and are ignored by the interpreter.

# This is a single-line comment

If comments are ignore by an interpretor, then why does Python has comments as part of a syntax?

Python Coding Standards

Python’s coding standards, as defined in PEP 8 (Python Enhancement Proposal 8), are designed to promote code readability and consistency across Python projects. Adhering to these standards ensures that your code is clean, understandable, and maintainable by others.

1. Indentation

Indentation is a critical part of Python syntax. Unlike many other languages that use braces () or keywords (begin, end) to define blocks of code, Python relies solely on whitespace indentation. This makes the code visually cleaner but also enforces strict formatting rules.

PEP 8 Rules for Indentation: Use 4 spaces per indentation level. Avoid using tabs. Ensure consistency: Mixing tabs and spaces in the same file will raise an IndentationError. Examples of Correct Indentation:

# Correct indentation using 4 spaces
def greet_user(username):
if username:
print(f"Hello, {username}!")
else:
print("Hello, Guest!")

# Incorrect: Using tabs or inconsistent spaces
def greet_user(username):
if username: # Using a tab instead of 4 spaces
print(f"Hello, {username}!")
greet_user("vela")
greet_user("tharinie")

Why is the above code inorrect in its indentation?

2. Naming Conventions

Naming conventions define how you should name variables, functions, classes, constants, and other identifiers in Python. Consistent naming makes code easier to read and understand, even for someone new to the project.

3. Variable and Function Names Use lowercase letters and separate words with underscores (snake_case). Avoid overly long or cryptic names; names should be descriptive but concise.

Examples:

# Good practice
student_name = "Alice"
calculate_total_marks()

# Bad practice
StudentName = "Alice" # CamelCase is not recommended for variables
CalculateTotalMarks() # CamelCase is not recommended for functions
x = 42 # Avoid single-letter variable names unless used in loops

4. Class Names

  • Use PascalCase (also called UpperCamelCase) for class names.
  • The name should be a noun or noun phrase that reflects what the class represents.
# Good practice
class Student:
pass

class MathOperations:
pass

# Bad practice
class student: # Class names should use PascalCase
pass

5. Constant Names

  • Use ALL_CAPS with words separated by underscores.
  • Place constants at the top of your module (file).
# Good practice
PI = 3.14159
MAX_CONNECTIONS = 100

# Bad practice
Pi = 3.14159 # Use uppercase for constants
maxConnections = 100 # Use ALL_CAPS

6. Method Names

  • Follow the same rules as functions: snake_case.
  • In classes, methods that modify the object’s state or perform actions should have action-oriented names.
class Car:
def start_engine(self):
pass

def get_mileage(self):
return 15

7. Private Names

  • Use a single leading underscore to indicate a private variable or method (e.g., _internal_variable).

  • For stronger name-mangling protection, use double leading underscores (e.g., __private_method).

##3. Other Coding Standard Highlights

8. Line Length

  • Limit all lines to a maximum of 79 characters.
  • For longer lines, use Python’s implicit line continuation inside parentheses, brackets, or braces. For explicit line continuation, use a backslash (), though implicit is preferred.
# Implicit continuation
data = [
"item1", "item2", "item3",
"item4", "item5", "item6"
]

# Explicit continuation
long_string = "This is a very long string that we need to split " \
"across multiple lines for better readability."

9. Blank Lines

  • Use blank lines to separate logical sections of code.
  • Two blank lines between top-level functions and classes.
  • One blank line between methods within a class.
# Blank lines between functions
def function_one():
pass


def function_two():
pass

9. Imports

  • Place all imports at the top of the file.
  • Follow the order:
    1. Standard library imports.
    2. Third-party library imports.
    3. Local application/library-specific imports. Separate each group with a blank line.
# Good practice for imports
import os
import sys

import numpy as np
import pandas as pd

from mymodule import my_function

###String Quotes -Use single quotes (') or double quotes (") consistently. -For multi-line strings, use triple quotes (''' or """).

# Consistent string usage
greeting = "Hello, World!"
error_message = 'An error occurred.'

# Multi-line string
description = """This is a multi-line string.
It spans several lines."""