⚡0 XP🔥0

Python Syntax, Indentation & Comments

Lesson 3 of 33 ⏱ 5 min read ✎ 2 exercises ❓ 5-question quiz ▶ Runs Python

The basic grammar of Python - statements, indentation, case sensitivity, keywords and how to write comments.

What is syntax?#

Syntax is the set of grammar rules of a programming language. Just like an English sentence needs proper grammar, a Python program needs proper syntax - otherwise Python shows a SyntaxError and refuses to run.

Statements#

Each instruction in Python is called a statement. Normally one statement is written per line - no semicolon is needed at the end.

print("Line one")
x = 10
print(x)

You can put two statements on one line using ;, but it is not recommended because it makes code hard to read:

a = 5; b = 6; print(a + b)   # works, but avoid this style

Indentation - the most important rule#

Indentation means the spaces at the beginning of a line. Many languages use { } to group code. Python uses indentation instead.

age = 20
if age >= 18:
    print("You are an adult")      # inside the if-block (4 spaces)
    print("You can vote")          # inside the if-block
print("This line always runs")     # outside the block (no spaces)
Output
You are an adult
You can vote
This line always runs
  • A line ending with a colon : (like if, for, def) starts a new block.
  • All lines in the block must be indented by the same amount.
  • The standard is 4 spaces per level.
  • The block ends when the indentation goes back.
हिंदी में समझें

Python में indentation (लाइन की शुरुआत में spaces) सिर्फ सुंदरता के लिए नहीं है - यह बताता है कि कौन-सी लाइन किस block का हिस्सा है। जैसे ऊपर के example में दोनों print लाइनें 4 spaces आगे हैं, इसलिए वे if के अंदर हैं और तभी चलेंगी जब condition सही हो। आखिरी print बिना spaces के है, इसलिए वह हमेशा चलेगी।

याद रखें: : के बाद वाली लाइन हमेशा आगे खिसकाएं (indent करें), और एक block की सभी लाइनों में spaces बराबर रखें।

Try changing the value of age to 15 and run again:

▶ Try it YourselfPython
Ctrl + Enter to run

Indentation errors#

if True:
print("Hello")        # missing indentation
Output
IndentationError: expected an indented block after 'if' statement on line 1
if True:
    print("A")
      print("B")      # extra spaces - inconsistent
Output
IndentationError: unexpected indent
Common Mistake

Never mix Tabs and spaces in the same file. Configure your editor to insert 4 spaces when you press Tab (VS Code does this by default for .py files).

Case sensitivity#

Python treats uppercase and lowercase letters as different:

▶ Try it YourselfPython
Ctrl + Enter to run

Comments#

A comment is a note for humans. Python ignores it completely. Use comments to explain why your code does something.

Single-line comments#

# This program calculates the total bill
price = 250      # price of one item
qty = 3          # quantity
print(price * qty)

Multi-line comments#

Python has no special multi-line comment symbol. You can use # on every line:

# Line 1 of the comment
# Line 2 of the comment

Or a triple-quoted string that is not assigned to anything (Python ignores it):

"""
This is a multi-line note.
It is often used to describe a whole file or function.
"""
print("Program starts")
Tip

"Commenting out" code means putting # before a line so it doesn't run - useful while testing. In VS Code, press Ctrl + / to comment or uncomment the selected lines.

Keywords#

Keywords are reserved words with a special meaning. You cannot use them as variable names. 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

You can print the list yourself:

▶ Try it YourselfPython
Ctrl + Enter to run

Long lines#

If a line is too long, you can continue it inside brackets ( ), [ ], { } - Python allows line breaks there:

total = (100 + 200 + 300 +
         400 + 500)
print(total)

Summary#

  • One statement per line; no semicolons needed.
  • Indentation (4 spaces) defines blocks; a : starts a new block.
  • Python is case-sensitive.
  • # starts a comment; triple-quoted strings are used for longer notes.
  • Keywords like if, for, while, def are reserved and cannot be used as names.

Practice Exercises

Write your code, then press Check. Your program is tested automatically.

1

Fix the indentation

This program has an indentation error. Fix it so that it prints:

Good morning
Have a nice day
Expected output:
Good morning
Have a nice day
2

Comment out a line

The program below prints three lines. Use a comment (don't delete the line!) so that only Line 1 and Line 3 are printed.

Expected output:
Line 1
Line 3

Quick Quiz

Q1.

How does Python mark a block of code (for example, the body of an if statement)?

Q2.

Which symbol starts a single-line comment?

Q3.

What error do you get if indentation is wrong?

Q4.

Which of these is a Python keyword?

Q5.

Are Name and name the same in Python?