Writing Python: Rules and Syntax

Python has gained popularity largely due to its readability and intuitive syntax. Unlike many other programming languages, Python code closely resembles plain English, which makes it accessible even to beginners. However, it still follows strict syntax rules that developers must understand. This article outlines essential Python syntax rules and conventions clearly and comprehensively.

1. Basic Python Syntax

Statements and Expressions

A statement is an instruction executed, like assigning a variable or performing an action.

x = 5
print("Hello, World!")

An expression evaluates to a value:

y = 5 + 3  # 5 + 3 is an expression

2. Indendation and Blocks

We use indentation (spaces or tabs) to structure code. Unlike languages that use curly braces ({}).

if 10 > 5:
    print("Ten is greater than five.")  # Indented code forms a block
  • Mixing tabs and spaces is discouraged.
  • Standard indentation is four spaces per level.
if 10 > 5:
print("Ten is greater than five.")  # No indentation – error!

3. Variables and Assignment

  • Variables do not need explicit declaration.
  • Python is dynamically-typed, meaning the same variable can hold different data types at different times.
name = "Alice"
age = 30
height = 1.65

name = 100  # Now 'name' is an integer

Rules for naming variables:

  • Must begin with a letter (a-z, A-Z) or underscore (_).
  • Can contain letters, numbers, and underscores.
  • Cannot start with a number.
  • Names are case-sensitive (age and Age are two different variables).

4. Comments

Comments are ignored by the Python interpreter and used for code readability.

  • Single-line comments start with #:
# This is a single-line comment

  • Multi-line comments can be created using triple quotes:
'''
This is a multi-line comment or docstring
that spans multiple lines.
'''

5. Data Types and Literals

Python supports various built-in data types:

  • Numeric types (int, float, complex)
  • Text type (str)
  • Boolean type (bool)
  • Sequence types (list, tuple, range)
  • Mapping type (dict)
  • Set types (set, frozenset)
integer_var = 10
float_var = 10.5
string_var = "Hello, Python!"
boolean_var = True
list_var = [1, 2, 3]
dict_var = {"name": "Alice", "age": 25}

6. Operators and Expressions

Python supports various operators:

  • Arithmetic operators: +, -, *, /, %, **, //
  • Assignment operators: =, +=, -=, etc.
  • Comparison operators: ==, !=, >, <, >=, <=
  • Logical operators: and, or, not
a = 10
b = 3

print(a + b)    # 13
print(a / b)    # 3.333...
print(a // b)   # 3 (integer division)
print(a % b)    # 1 (remainder)

7. String Formatting and Concatenation

Python strings can be formatted in various ways:

Concatenation:

name = "Alice"
greeting = "Hello, " + name + "!"

f-strings (Python 3.6+ recommended):

name = "Bob"
age = 30
print(f"{name} is {age} years old.")

8. Conditional Statements

Python uses if, elif, and else for conditional logic.

age = 20

if age < 18:
    print("Minor")
elif age == 18:
    print("Just became an adult!")
else:
    print("Adult")

9. Loops

Python provides two types of loops: for and while.

For loops iterate over sequences:

for fruit in ["apple", "banana", "cherry"]:
    print(fruit)

While loops run as long as the condition is true:

count = 1
while count <= 5:
    print(count)
    count += 1

10. Functions

Functions are defined using the def keyword:

def greet(name):
    print(f"Hello, {name}!")

greet("Alice")  # Calls the function
  • Python allows default parameters:
def greet(name="User"):
    print(f"Hello, {name}!")

greet()         # Hello, User!
greet("Bob")    # Hello, Bob!

11. Classes and Objects

Python supports object-oriented programming through classes:

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def introduce(self):
        print(f"My name is {self.name} and I am {self.age} years old.")

alice = Person("Alice", 30)
alice.introduce()

12. Importing Modules

Python imports external modules using the import statement:

import math

print(math.sqrt(16))  # 4.0

Importing specific functions:

from math import sqrt

print(sqrt(25))  # 5.0

13. Exception Handling

Python provides structured error handling:

try:
    result = 10 / 0
except ZeroDivisionError:
    print("Cannot divide by zero!")
finally:
    print("Completed error checking.")

14. Python Naming Conventions

These guidelines help maintain readable code:

  • Variables and functions: lowercase words separated by underscores (snake_case)
student_name = "John"
  • Classes: capitalized words (PascalCase)
class StudentDetails:
    pass
  • Constants: uppercase words separated by underscores
MAX_SIZE = 10

Common Mistakes to Avoid

Incorrect indentation: Always maintain consistent indentation.

Case sensitivity: Be careful about variable names (Age vs. age).

Missing colons: Conditional statements and loops require colons (:) after their declarations.

Mixing tabs and spaces: Stick to spaces or tabs consistently.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top