Tutorials Python Syntax Basics
Ch 3 / 58
Python Beginner 6 min read Chapter 3 of 58

Python Syntax Basics

Python has the cleanest, most readable syntax of any popular programming language. Unlike Java or C++, there are no semicolons, no curly braces, and code reads almost like plain English. This chapter covers every core syntax rule you need to write correct Python from day one.

What you'll learn in this chapter
How Python uses indentation instead of braces
Writing and ending Python statements correctly
Variable naming rules and conventions
Why Python is case-sensitive and what that means
All 35 Python reserved keywords
Multiline statements, blank lines & best practices
Advertisement

What Makes Python Syntax Special?

Every programming language has a set of rules — called syntax — that defines how you write valid code. Python was designed with one core goal: readability first. Its creator Guido van Rossum built it so that Python code looks similar to pseudocode or plain English.

🚫
No Semicolons
Lines end naturally — no ; needed at end of each statement like in Java or C.
📐
Indentation = Structure
Code blocks use spaces — not curly braces { }. Indentation is mandatory and meaningful.
🔤
Case Sensitive
age, Age and AGE are three completely different variables.
💬
Comments with #
Everything after # on a line is a comment — Python ignores it completely.
🎯
No Type Declarations
You never write int x = 5. Just write x = 5 — Python figures the type automatically.
📦
One Statement Per Line
Typically one statement per line. No need for delimiters — newline = end of statement.
✓ Python — clean & readable
if age >= 18: print("Adult") else: print("Minor")
Java / C++ — verbose syntax
if (age >= 18) { System.out.println("Adult"); } else { System.out.println("Minor"); }
The Zen of Python Run import this in any Python shell to see Python's 19 guiding principles. The most important one: "Readability counts."

Indentation — Python's Most Important Rule

In most languages, indentation is optional — just a style choice. In Python, indentation is mandatory. It tells Python which lines belong to which block of code. Get it wrong and your program crashes.

IndentationError If your indentation is inconsistent or missing where required, Python throws an IndentationError and refuses to run your code. This is the #1 mistake new Python developers make.

How indentation defines code blocks — visual diagram

if score >= 90: ← no indentation = top level
print("Grade A") ← 4 spaces = inside the if block
if score == 100: ← still 4 spaces = nested if
print("Perfect score!") ← 8 spaces = inside nested if
else: ← back to 0 spaces = same level as if
print("Keep trying") ← 4 spaces = inside else block
print("Done") ← 0 spaces = back to top level
✓ Correct indentation
for i in range(3): print(i) # 4 spaces ✓ def greet(name): print(f"Hi {name}") # 4 spaces ✓ return True
✗ Wrong indentation — crashes!
for i in range(3): print(i) # IndentationError! def greet(name): print(f"Hi {name}") # 2 spaces — be consistent return True # Error!
Python — indentation examples
# ✅ Standard: 4 spaces per level (PEP 8 standard)
if True:
    print("Level 1")       # 4 spaces
    if True:
        print("Level 2")   # 8 spaces
        if True:
            print("Level 3")  # 12 spaces

# ✅ You CAN use 2 spaces — just be consistent throughout the file
if True:
  print("2-space indent")    # 2 spaces — OK if used everywhere

# ❌ Mixing spaces and tabs → TabError in Python 3
if True:
	print("tab")    # tab ← DO NOT mix with spaces
    print("space")  # spaces ← will cause TabError!
PEP 8 Standard: Always use 4 spaces
PEP 8 is Python's official style guide. It recommends 4 spaces per indentation level. VS Code and PyCharm both default to this automatically. Never use tabs — Python 3 forbids mixing tabs and spaces in the same file.

Python Statements

A statement is a single instruction Python executes. In Python, each line is typically one statement, and it ends at the newline — no semicolons required.

Python — statements
# Each line is one statement — no semicolons needed
x = 10                       # assignment statement
print(x)                     # function call statement
name = "Alice"               # string assignment
result = x + 5               # expression statement

# You CAN put multiple statements on one line using semicolons
# (but it's bad style — avoid this)
a = 1; b = 2; c = 3         # ← works but NOT recommended

# Simple statements (one line)
pass                         # does nothing (placeholder)
break                        # used inside loops
continue                     # skip rest of loop iteration
return x                     # return from function

# Compound statements (span multiple lines, need colon + indented block)
if x > 5:
    print("big")              # body of the if block

for i in range(3):
    print(i)                 # body of the for loop
How Python reads each statement
You Write
name = "Alice"
→
Python Reads
Newline found
→
Executes
Statement done
→
Next line
Repeat
Simple statement
Fits on one line. Examples: assignment (x = 5), print(), return, import. No colon at the end.
Compound statement
Has a header line ending with : and an indented body. Examples: if, for, while, def, class.
Expression statement
A standalone expression like a function call: print("hi"). Python evaluates it and discards the result unless it's assigned.
Advertisement

Variables in Python

A variable is a name that stores a value in memory. In Python, you create a variable simply by assigning a value to a name — no type declaration, no var, no let. Python automatically figures out the type.

Python — creating variables
# Create variables by assignment — no type keyword needed
name    = "Alice"      # str  (string)
age     = 25           # int  (integer)
height  = 5.7          # float
is_adult = True        # bool (Boolean)

# Python infers the type — check with type()
print(type(name))      # <class 'str'>
print(type(age))       # <class 'int'>
print(type(height))    # <class 'float'>
print(type(is_adult))  # <class 'bool'>

# Reassign to a completely different type — Python allows it
x = 10
print(type(x))         # <class 'int'>
x = "hello"
print(type(x))         # <class 'str'> — changed!

# Assign multiple variables in one line
a, b, c = 1, 2, 3
print(a, b, c)          # 1 2 3

# Assign same value to multiple variables
x = y = z = 0
print(x, y, z)          # 0 0 0

# Swap two variables (Python makes this elegant)
a, b = 10, 20
a, b = b, a             # swap!
print(a, b)             # 20 10
Variables are labels, not boxes
Think of a variable as a label that points to a value in memory. When you write x = 10, Python creates the integer 10 in memory and attaches the label x to it. If you then write x = "hello", the label moves — it now points to the string. The integer 10 is still in memory until garbage collected.

Variable Naming Rules & Conventions

Python has strict rules (break them → error) and recommended conventions (ignore them → ugly code). Learn both.

Hard Rules — violating these causes a SyntaxError

Rule Valid Example Invalid Example Reason
Start with letter or underscore ✓ name ✓ _age ✗ 2name Cannot start with a digit
Letters, digits, underscores only ✓ user_1 ✗ user-1 ✗ user@ No hyphens or special chars
No spaces allowed ✓ first_name ✗ first name Use underscore instead
Cannot be a keyword ✓ for_loop ✗ for ✗ if Reserved words are off-limits
Case sensitive ✓ age ✓ Age (different) — Different variables entirely

Conventions — PEP 8 recommendations every Python dev follows

Python — naming conventions (PEP 8)
# ── Variables and functions → snake_case (lowercase + underscores)
user_name = "Alice"
total_price = 99.99
def calculate_tax(price): ...

# ── Constants → UPPER_SNAKE_CASE (all caps)
MAX_SIZE = 100
PI = 3.14159
DATABASE_URL = "localhost:5432"

# ── Classes → PascalCase (each word capitalised)
class BankAccount: ...
class UserProfile: ...

# ── "Private" variables → single leading underscore (by convention)
_internal_counter = 0

# ── Throwaway / unused variable → single underscore
for _ in range(3):
    print("Hello")    # don't need the loop counter

# ── Good names are descriptive
x = 25            # ← bad: what is x?
user_age = 25    # ← good: meaning is clear

Python is Case-Sensitive

Python treats uppercase and lowercase letters as completely different. This applies to variable names, function names, class names, and keywords. This is one of the most common sources of bugs for beginners.

name
Different variable
Name
Different variable
NAME
Different variable
True
Python keyword ✓
true
NameError ✗
TRUE
NameError ✗
Python — case sensitivity in action
# These are THREE separate variables
name = "alice"
Name = "Bob"
NAME = "CAROL"
print(name, Name, NAME)   # alice Bob CAROL

# Python keywords are all lowercase — capitalisation breaks them
print(True)    # True   ← works
print(False)   # False  ← works
print(None)    # None   ← works
# print(TRUE)   ← NameError: name 'TRUE' is not defined
# print(true)   ← NameError: name 'true' is not defined

# Functions are also case-sensitive
print("hello")   # works
# Print("hello")  ← NameError
# PRINT("hello")  ← NameError

# Practical tip: be consistent — use one style and stick to it
city = "Mumbai"
print(city)    # Mumbai
# print(City)   ← NameError — it's city, not City
Real bug alert A common mistake: defining userName = "Alice" then trying to use username later. Python sees them as different variables and throws a NameError. This is why the PEP 8 convention of always using snake_case helps — it eliminates ambiguity.

Python Reserved Keywords

Python has 35 reserved keywords — words with special meanings built into the language. You cannot use them as variable names. Python 3.10+ added a few new ones (match, case). Here are all of them:

FalseNoneTrue andasassertasyncawait breakclasscontinue defdelelifelse exceptfinallyfor fromglobalif importinis lambdanonlocalnot orpassraise returntrywhile withyieldmatchcase
Python — check all keywords at runtime
# See all keywords programmatically
import keyword
print(keyword.kwlist)
# ['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']

# Check if something is a keyword
print(keyword.iskeyword("for"))     # True
print(keyword.iskeyword("name"))    # False — safe to use as variable

# ❌ Using keywords as variable names → SyntaxError
# for = 10     ← SyntaxError: invalid syntax
# class = "A"  ← SyntaxError: invalid syntax
# if = True    ← SyntaxError: invalid syntax

# ✅ Workaround: add underscore if name clashes
type_ = "admin"     # 'type' is a built-in, so use type_
list_ = [1, 2, 3]    # 'list' is a built-in, so use list_
Advertisement

Multiline Statements & Blank Lines

Sometimes a single statement is too long for one line. Python gives you two ways to break it across multiple lines, plus conventions for blank lines to make code readable.

Python — multiline statements
# METHOD 1: Backslash continuation ( \ )
total = 100 + \
        200 + \
        300
print(total)    # 600

long_string = "Hello, this is a very " \
              "long sentence split across lines."

# METHOD 2: Implicit continuation inside brackets ( ), [ ], { }
# Preferred — cleaner and safer than backslash
result = (100 +
          200 +
          300)
print(result)   # 600

# Long list — split across lines inside [ ]
fruits = [
    "apple",
    "banana",
    "cherry",
    "mango",
]

# Long function call — split across lines inside ( )
print(
    "Name:", "Alice",
    "Age:",  25,
    "City:", "Vadodara",
)

# Long dictionary — split across lines inside { }
user = {
    "name":  "Alice",
    "age":   25,
    "city":  "Vadodara",
}

# Long if condition — use brackets
if (age >= 18 and
        is_registered and
        has_id_proof):
    print("Eligible")

Blank Lines — how to use them (PEP 8)

Python — blank line conventions
# 2 blank lines before and after top-level functions / classes


def first_function():
    print("first")


def second_function():
    print("second")


class MyClass:
    # 1 blank line between methods inside a class
    def method_one(self):
        pass

    def method_two(self):
        pass

# Inside a function: use blank lines sparingly to group logic
def process_order(order):
    # validate
    if not order:
        return

    # calculate total
    total = order["price"] * order["qty"]

    # send confirmation
    print(f"Order total: {total}")
2 blank lines
Before and after top-level function/class definitions. This separates major code sections and is the PEP 8 standard.
1 blank line
Between methods inside a class. Also used sparingly inside functions to separate logical sections.
\ backslash
Continues the statement on the next line. Must be the very last character on the line — even a space after it breaks the continuation.
( ) [ ] { }
Any open bracket automatically allows continuation across lines — no backslash needed. This is the preferred approach.
Backslash pitfall — trailing space
When using \ for line continuation, there must be absolutely nothing after it — not even a space. A trailing space breaks it silently. This is why most professionals prefer brackets ( ) for multiline statements instead.
K2infocom Python Masterclass & Backend Development
Master Python, Django & Backend APIs with AI
Go from absolute beginner to building production-ready REST APIs, web applications, and ML pipelines. Real projects, live mentoring in Vadodara, and placement support included.
2,400+
Students Enrolled
4.9
Google Rating
6 Months
Full Program
100%
Placement Support
Python 3Django & DRF FastAPIPostgreSQL Machine LearningDocker & AWS Real ProjectsAI Tools
Chapter Summary
  • Indentation is mandatory in Python — 4 spaces per level is the PEP 8 standard. Never mix tabs and spaces.
  • Each line is one statement. No semicolons needed. Compound statements end their header line with a colon :.
  • Variables are created with name = value — no type keyword. Python infers type automatically.
  • Naming rules: start with a letter or _, only letters/digits/underscores, no spaces, not a keyword.
  • Naming convention: snake_case for variables/functions, UPPER_CASE for constants, PascalCase for classes.
  • Python is case-sensitive: age, Age, AGE are three different variables.
  • Python has 35 reserved keywords — you cannot use them as variable names.
  • Use brackets ( ) [ ] { } for clean multiline statements. Backslash \ also works but is fragile.
⚡
Free Resource
Download our Python Cheat Sheet
Syntax rules, naming conventions, keywords — all on one printable page.
Get Sheet
Advertisement
Quick Check — Test Your Understanding
Question & Answer
✓ Answer

Python throws an IndentationError and refuses to run the code at all. For example, if you write if True: followed by print("hi") at the same indentation level (not indented), Python will say IndentationError: expected an indented block after 'if' statement. Python uses indentation to understand code structure, so it is a hard syntax requirement — not optional like in most other languages.

✓ Answer

These are reserved keywords — words that Python has already claimed with specific meanings in the language grammar. for means "start a loop", class means "define a class", import means "load a module". If Python allowed you to redefine them as variables, it would become impossible to tell whether for means "loop" or "a variable named for". Python protects them to keep the language unambiguous. You'll get a SyntaxError immediately.

✓ Answer

snake_case (all lowercase, words separated by underscores) is used for variables and functions: user_name, calculate_tax(). PascalCase (each word starts with capital, no underscores) is used for class names: BankAccount, UserProfile. UPPER_CASE (all caps with underscores) is used for constants — values that should never change: MAX_SIZE = 100, API_KEY = "xyz". These are conventions from PEP 8, not enforced by Python itself — but every professional Python developer follows them.

✓ Answer

The preferred way is implicit continuation inside brackets — wrapping the expression in parentheses ( ), square brackets [ ], or curly braces { }. Python automatically allows the statement to continue to the next line inside any open bracket. The alternative is the backslash \ at the end of the line, but it's fragile — a trailing space after the backslash silently breaks it. Most Python developers prefer brackets for safety and readability.

✓ Answer

Yes, Python is fully case-sensitive. Two practical examples:

1. Keywords: True and False are Python's boolean keywords (capital T and F). Writing true or false gives a NameError — Python doesn't recognise them as the boolean values.

2. Variables: If you define userName = "Alice" and later write print(username), Python throws a NameError because username (all lowercase) is a completely different, undefined variable. This is a very common beginner bug.

MCQ 1 of 3
Which of the following is a valid Python variable name?
MCQ 2 of 3
What error does Python throw when indentation is wrong or missing?
MCQ 3 of 3
According to PEP 8, what naming style should be used for Python functions?

Rate Us on Google

4.8 / 5
Enjoying this tutorial?
Your 5-star review helps other learners discover our free tutorials and encourages us to keep creating quality content.
80+ reviews
Write a Google Review
Join WhatsApp Channel