Python Tutorial chapters (19)
  1. 01Python Introduction
  2. 02Python Syntax, Keywords & Operators
  3. 03Python Variables & Data Types
  4. 04Python Strings
  5. 05Python Control Statements
  6. 06Python Lists
  7. 07Python Tuples
  8. 08Python Sets
  9. 09Python Dictionaries
  10. 10Python Functions
  11. 11Python Modules
  12. 12Python OOPs
  13. 13Python Exception Handling
  14. 14Python File Handling
  15. 15Python Searching & Sorting
  16. 16Python Advanced Topics
  17. 17Python MySQL
  18. 18Python MongoDB & SQLite
  19. 19Python MCQ

Chapter 02

Python Syntax, Keywords & Operators

5 topics · 1 sections · beginner-friendly study notes · Updated

Share with friends:WhatsAppTelegram

Embed on your site

Free for teachers, schools and blogs. Please keep the attribution link.

Preview

Syntax is the set of rules for writing valid Python code.

This chapter covers indentation and statements, reserved keywords, literals, all operator groups with precedence, and comments.

Most beginner errors are SyntaxError or IndentationError.

Knowing the rules removes them.

Every Python program uses syntax, operators and comments from the first line.

1

Python Syntax

Python syntax is the set of rules that defines how a valid Python program is written and structured. Blocks are marked by indentation, statements end at the line end, and the language is case-sensitive.

In short: Syntax is the grammar of Python. If you break the grammar, Python shows an error.

Indentation = code blocks

Think about it

Python uses indentation instead of braces, so spacing is part of the grammar. A single misplaced space inside an if block can change what the program does.

Indentation: after a line ending with a colon (if, for, while, def, class) the next lines must be indented the same amount, usually 4 spaces.

Mixing tabs and spaces causes TabError.

Statements: one statement per line; use a backslash \ or open brackets ( ) [ ] { } to continue a statement on the next line.

A semicolon can put two statements on one line, but this is discouraged.

Case sensitivity: Total and total are two names.

Identifier rules: letters, digits and underscore; cannot start with a digit; cannot be a keyword.

Naming style (PEP 8): snake_case for variables and functions, PascalCase for classes, UPPER_CASE for constants.

Blank lines and extra spaces inside a line are ignored.

Common errors: SyntaxError (bad grammar), IndentationError (bad indent), NameError (name not defined).

Key points

  • Indentation: Leading spaces that show a block of code.
  • Identifier: Name of a variable, function, class or module.
  • Statement: One complete instruction that Python executes.
  • Block: Group of statements under a header that ends with a colon.
  • Use 4 spaces for each indentation level.
  • Headers (if, for, def, class) end with a colon.
  • Python is case-sensitive.
  • An identifier cannot start with a digit or use a keyword.

Example

Code
indentation, continuation and names:
# valid blocks
age = 19
if age >= 18:
    print("adult")       # 4 spaces
    print("can vote")
else:
    print("minor")

# long statement continued with brackets
total = (10 + 20 +
         30 + 40)
print(total)             # 100

# case-sensitive names
count = 1
Count = 2
print(count, Count)      # 1 2

# valid and invalid identifiers
user_name = "ravi"       # valid
_temp = 5                # valid
# 2cool = 3              # SyntaxError: starts with digit
2

Python Keywords

Keywords are reserved words that have a fixed meaning in Python. They form part of the syntax and cannot be used as variable, function or class names.

In short: Keywords are special words like if, for and class. Python already owns them, so you cannot use them as your own names.

Think about it

Using a keyword as a name gives SyntaxError. Knowing the list prevents silly mistakes. Writing class = "A" fails, so people use class_name or klass instead.

Python 3 has about 35 keywords: False, None, True, and, as, assert, async, await, break, class, continue, def, del, elif, else, except, finally, for, from, global, if, import, in, is, lambda, nonlocal, not, or, pass, raise, return, try, while, with, yield.

Only True, False and None start with a capital letter.

The exact list depends on the version, so print it with the keyword module.

Python 3.10+ also has "soft keywords" such as match and case that act as keywords only in a match statement and can still be used as normal names elsewhere.

Built-in names like print, len, list and str are NOT keywords; they can be overwritten (which is a bad idea).

Key points

  • Reserved word: Word with special meaning that cannot be an identifier.
  • Soft keyword: Word that is special only in some contexts, like match.
  • keyword module: Standard module that lists keywords.
  • Built-in name: Name such as print or len that is not a keyword.
  • True, False, None are keywords and are capitalised.
  • All other keywords are lowercase.
  • print and input are functions, not keywords, in Python 3.

Example

Code
list and test keywords:
import keyword

print(len(keyword.kwlist))        # 35 in recent 3.x versions
print(keyword.kwlist[:6])         # ['False', 'None', 'True', 'and', 'as', 'assert']
print(keyword.iskeyword("for"))   # True
print(keyword.iskeyword("print")) # False
print(keyword.softkwlist)         # e.g. ['_', 'case', 'match', 'type']

# class = 5   # SyntaxError
class_name = 5   # fine

# built-in names can be overwritten (avoid!)
list = [1, 2]
# list("abc")  -> TypeError now because list is a variable
del list         # restore the built-in
3

Python Literals

A literal is a fixed value written directly in the source code. Python has numeric, string, boolean, special (None) and collection literals.

In short: A literal is a value you type as it is, like 10, 3.5, "hello", True or [1, 2, 3].

Think about it

Understanding literals helps you predict types and avoid mistakes like mixing "5" and 5. Writing 1_000_000 makes big numbers easier to read in financial code.

Numeric literals: int (10, 0b1010 binary, 0o17 octal, 0xFF hex, 1_000_000 with underscores), float (3.14, 2e3 = 2000.0) and complex (3+4j).

String literals: single, double or triple quotes; prefixes r (raw), b (bytes), f (formatted), u (unicode).

Boolean literals: True and False.

Special literal: None means "no value".

Collection literals: list [1, 2], tuple (1, 2), dict {"a": 1}, set {1, 2}.

A literal is different from a variable: a variable is a name, a literal is a value.

Literals are objects too; their type is decided by how you write them: 5 is int, 5.0 is float, "5" is str.

Key points

  • Literal: Value written directly in code.
  • Raw string: String with r prefix where backslashes are kept as typed.
  • None: Special literal that represents no value.
  • Triple quotes: Quotes that allow strings across many lines.
  • 0b, 0o and 0x write binary, octal and hex literals.
  • None is not 0, not "" and not False; it is its own type NoneType.
  • 1e3 is a float (1000.0), not an int.

Example

Code
all kinds of literals:
print(0b1010, 0o17, 0xFF)      # 10 15 255
print(1_000_000)                # 1000000
print(2e3, type(2e3))           # 2000.0 <class 'float'>
print(3 + 4j, type(3 + 4j))     # (3+4j) <class 'complex'>

print(r"C:\new\table")          # C:\new\table  (raw string)
poem = """Roses are red,
Violets are blue"""
print(poem)

print(True, False, None)
print(type(None))               # <class 'NoneType'>

data = [1, 2], (3, 4), {"k": 5}, {6, 7}
for item in data:
    print(type(item).__name__)  # list tuple dict set
4

Python Operators

Operators are symbols that perform an operation on values called operands. Python has arithmetic, comparison, assignment, logical, bitwise, identity and membership operators.

In short: Operators do the work: add, compare, join conditions, check membership and more.

Operator types at a glance

Think about it

Operators appear in every expression and are the most common source of output-prediction questions. A billing script uses % to find leftover cents, // to count full packs and and/or for discount rules.

Arithmetic: + - * / // % ** (/ always gives float, // is floor division, % remainder, ** power).

Comparison

== !

= > < >= <= return True/False and can be chained: 1 < x < 10.

Assignment: = += -= *= /= //= %= **= and the walrus operator := (assign inside an expression).

Logical: and, or, not use short-circuit evaluation and return one of the operands, not always a bool.

Bitwise: & | ^ ~ << >> work on binary digits.

Identity: is, is not check whether two names refer to the SAME object (use == for equal value).

Membership: in, not in test presence in a sequence.

Precedence (high to low): ** → unary + - ~ → * / // % → + - → << >> → & → ^ → | → comparisons, is, in → not → and → or.

Use brackets to make order clear.

Division by zero raises ZeroDivisionError.

Key points

  • Operand: Value on which an operator works.
  • Floor division: // divides and rounds down to the nearest integer.
  • Short-circuit: Stop evaluating as soon as the result is known.
  • Walrus operator: := assigns a value inside an expression.
  • Precedence: Order in which operators are applied.
  • 7 / 2 is 3.5 but 7 // 2 is 3.
  • -7 // 2 is -4 (rounds toward minus infinity).
  • is compares identity; == compares value.
  • and/or return an operand: 0 or "hi" gives "hi".
  • ** is right-associative: 2 ** 3 ** 2 is 512.

Example

Code
every operator group:
a, b = 17, 5
print(a + b, a - b, a * b)     # 22 12 85
print(a / b, a // b, a % b)    # 3.4 3 2
print(a ** 2)                  # 289
print(-7 // 2, -7 % 3)         # -4 2

print(1 < b < 10)              # True (chained)
x = 10
x += 5; x *= 2
print(x)                       # 30

print(0 or "hi", "a" and "b")  # hi b
print(not 0)                   # True

print(5 & 3, 5 | 3, 5 ^ 3)     # 1 7 6
print(~5, 1 << 3, 16 >> 2)     # -6 8 4

l1, l2 = [1, 2], [1, 2]
print(l1 == l2, l1 is l2)      # True False
print(3 in [1, 2, 3], "z" not in "abc")  # True True

print(2 + 3 * 4, (2 + 3) * 4, 2 ** 3 ** 2)   # 14 20 512

if (n := len("python")) > 5:
    print(n)                   # 6
5

Python Comments

Comments are notes in the source code that Python ignores while running. A single-line comment starts with #. Triple-quoted strings placed first in a module, function or class are docstrings that document that object.

In short: A comment explains your code to humans. The computer skips it.

Think about it

Readable, documented code is easier to debug, review and maintain. Teams read docstrings through help() or documentation generators such as Sphinx.

Single-line comment: everything after # on that line is ignored.

Inline comment: placed on the same line as code, separated by two spaces by PEP 8.

Python has no special multi-line comment syntax; use several # lines.

A triple-quoted string that is not assigned to anything is often used as a block comment, but technically it is a string expression.

A docstring is a triple-quoted string right after def, class or at the top of a file; it is stored in __doc__ and read by help().

Good comments explain WHY, not what the obvious code does.

Use # TODO and # FIXME to mark pending work.

Special comments: the first line #!

/usr/bin/env python3 (shebang) and # -*- coding: utf-8 -*- (encoding).

Key points

  • Comment: Text ignored by the interpreter, starts with #.
  • Docstring: Triple-quoted documentation string of a module, class or function.
  • __doc__: Attribute that stores an object's docstring.
  • Shebang: First line that tells Unix which interpreter to use.
  • # starts a comment; Python has no /* */ style.
  • A docstring is available at run time through __doc__; a comment is not.
  • Comment the reason, not the obvious.

Example

Code
comments and docstring:
# This is a single-line comment
price = 100   # inline comment: base price

# Multi-line explanation
# uses several hash lines
# like this.

def area(r):
    """Return the area of a circle with radius r."""
    return 3.14159 * r * r

print(area.__doc__)    # Return the area of a circle with radius r.
help(area)             # shows the docstring

# print("this line is disabled by a comment")
print("done")

Solved examples

Example 01 · Basic

Find the output: print(17 // 5, 17 % 5, 17 / 5)

Given Data:
    Required To Find:

    Three values

    Formula Applied:—
    Step-by-Step Solution:
    Step 1: 17 // 5 = 3 (floor)
    Step 2: 17 % 5 = 2 (remainder)
    Step 3: 17 / 5 = 3.4 (true division)
    Final Answer: 3 2 3.4

    Approach note: Check: 5 * 3 + 2 = 17.

    Example 02 · Intermediate

    Evaluate 2 + 3 * 4 ** 2 // 8 and explain the order.

    Given Data:
      Required To Find:

      Final value

      Formula Applied:—
      Step-by-Step Solution:
      Step 1: ** first: 4 ** 2 = 16
      Step 2: * and // left to right: 3 * 16 = 48, then 48 // 8 = 6
      Step 3: + last: 2 + 6 = 8
      Final Answer: 8

      Approach note: Order: ** then * / // % then + -. Use brackets when unsure.

      Example 03 · Intermediate

      Why does a = [1, 2]; b = [1, 2]; print(a == b, a is b) print True False?

      Given Data:
        Required To Find:

        Explanation of == and is

        Formula Applied:—
        Step-by-Step Solution:
        Step 1: a == b compares contents: equal, so True
        Step 2: a and b are two separate list objects
        Step 3: a is b compares identity (same object), so False
        Final Answer: True False

        Approach note: Use == for values; use is mainly for None checks: x is None.

        Example 04 · Basic

        What does print(5 & 3, 5 | 3, 5 ^ 3, ~5) output?

        Given Data:
          Required To Find:

          Four bitwise results

          Formula Applied:—
          Step-by-Step Solution:
          Step 1: 5 is 101, 3 is 011
          Step 2: AND: 001 = 1
          Step 3: OR: 111 = 7
          Step 4: XOR: 110 = 6
          Step 5: NOT ~5 = -6 (two's complement)
          Final Answer: 1 7 6 -6

          Approach note: ~n equals -(n+1) for integers in Python.

          Real-world applications

          Python

          Using Python Syntax, Keywords & Operators in real projects

          Every Python program uses syntax, operators and comments from the first line.

          Mechanism: Write small programs, read errors carefully, then grow complexity only after the basics are solid.

          Common mistakes

          ❌ Myth: print and input are keywords.

          Why this is wrong: They are built-in functions in Python 3.

          ✅ Verified Truth: Keywords are listed by keyword.kwlist; print is not there.

          ⚠️ Exam Tip: Use keyword.iskeyword() to check.

          ❌ Myth: is and == mean the same.

          Why this is wrong: == compares values, is compares object identity.

          ✅ Verified Truth: Two equal lists are not the same object.

          ⚠️ Exam Tip: Use is only for None, True, False.

          ❌ Myth: Python has a multi-line comment like /* */.

          Why this is wrong: Python only has # comments.

          ✅ Verified Truth: Triple-quoted strings are strings, not real comments; docstrings are for documentation.

          ⚠️ Exam Tip: Use # on each line for block comments.

          ❌ Myth: 7 / 2 gives 3 in Python 3.

          Why this is wrong: The / operator always returns a float in Python 3.

          ✅ Verified Truth: 7 / 2 = 3.5 and 7 // 2 = 3.

          ⚠️ Exam Tip: Remember / is true division.

          Revision notes

          Syntax is the set of rules for writing valid Python code. This chapter covers indentation and statements, reserved keywords, literals, all operator groups with precedence, and comments.

          High-Yield Quick Revision Points

          1. Python uses indentation (4 spaces) to form blocks; headers end with a colon.
          2. Python is case-sensitive; identifiers cannot start with a digit or be keywords.
          3. There are about 35 keywords; True, False, None are capitalised; list them with keyword.kwlist.
          4. Literals: numeric (int, float, complex), string, boolean, None, collections.
          5. Operators: arithmetic, comparison, assignment, logical, bitwise, identity (is), membership (in).
          6. / is true division, // is floor division, % remainder, ** power (right-associative).
          7. Precedence: ** > * / // % > + - > comparisons > not > and > or.
          8. Comments start with #; docstrings use triple quotes and are stored in __doc__.

          Practice questions

          Question 1 · MCQ (Interview / semester)

          Which symbol starts a single-line comment in Python?

          Question 2 · MCQ (Interview / semester)

          Which of these is a valid identifier?

          Question 3 · MCQ (Interview / semester)

          What is the output of print(2 ** 3 ** 2)?

          Question 4 · MCQ (Interview / semester)

          What does print(-7 // 2) display?

          Question 5 · MCQ (Interview / semester)

          Which one is a keyword?

          Question 6 · MCQ (Interview / semester)

          What does print(0 or "hi") output?