Syntax is the set of grammar rules a language follows. Python’s rules are short: one statement per line, indentation to group lines, and no semicolons or curly braces. Learn these few rules now and most error messages will make sense later.
In this lesson you will learn
- What a statement is and how Python reads a file
- How indentation creates blocks of code
- Why
scoreandScoreare different names - How to split a long line over several lines
- When to use single, double and triple quotes
- Which words Python reserves as keywords
One Statement per Line
A statement is one complete instruction, such as creating a variable or calling print(). Python runs statements from the top of the file to the bottom. A line break ends a statement, so you do not need a semicolon.
greeting = "Shubho shokal"
print(greeting)
print(len(greeting))
Output
Shubho shokal
13
Line 1 creates a variable. Line 2 prints it. Line 3 prints how many characters it holds, spaces included. Python allows several statements on one line if you separate them with ;, but almost no one does this because it is harder to read.
Indentation Groups Lines Into Blocks
Some statements control other lines: if, for, while, def and class. These lines end with a colon :. The lines they control are pushed to the right. That pushed-in group is called a block.
temperature = 36
if temperature > 32:
print("It's hot outside.")
print("Carry water.")
print("This line always runs.")
Output
It's hot outside.
Carry water.
This line always runs.
The two indented print() lines belong to the if, so they run only when the temperature is above 32. The last line is back at the left edge. It is outside the block, so it runs every time. Change 36 to 25 and only the last line prints.
Indentation Rules to Remember
- Use 4 spaces per level. This is the Python standard (PEP 8), and every good editor inserts them when you press Tab.
- Every line in the same block must be indented by exactly the same amount.
- A colon
:must be followed by at least one indented line. - Never mix tabs and spaces in one file.
Coming from C or Java?
In C, curly braces { } mark a block and indentation is only for looks. In Python, indentation is the block marker. Code that is indented wrongly in C still runs; in Python it either fails with an IndentationError or, worse, runs with a line in the wrong block.
Python Is Case-Sensitive
Capital and small letters count as different characters. Score and score are two separate variables.
Score = 10
score = 99
print(Score)
print(score)
Output
10
99
The same applies to built-in names. print works; Print and PRINT give a NameError. The values True, False and None must start with a capital letter.
Splitting a Long Line
PEP 8 suggests keeping lines under 79 characters so code fits side by side on a screen. When a line grows too long, you have two choices.
- Wrap it in brackets. Inside
( ),[ ]or{ }, Python ignores line breaks until the bracket closes. This is the preferred way. - End the line with a backslash
\. This works but breaks easily if a space sneaks in after the backslash.
monthly_costs = (
12000 # rent
+ 4500 # food
+ 800 # internet
+ 1200 # transport
)
print("Monthly total:", monthly_costs)
message = "Python lets a long line " \
"continue with a backslash."
print(message)
Output
Monthly total: 18500
Python lets a long line continue with a backslash.
The brackets let each cost sit on its own line with a comment beside it. In the second statement, two pieces of text written side by side are joined into one string automatically.
Single, Double and Triple Quotes
Text values (strings) can use single quotes '...' or double quotes "...". They mean exactly the same thing. Pick the one that avoids clashing with quotes inside the text. Triple quotes """...""" let text run over several lines.
single = 'Rahim said "hello"'
double = "It's a sunny day"
triple = """Line one
Line two"""
print(single)
print(double)
print(triple)
Output
Rahim said "hello"
It's a sunny day
Line one
Line two
A good habit is to use double quotes by default and switch to single quotes when the text itself contains a double quote.
Python Keywords
Keywords are words with a fixed meaning in Python, such as if, for and return. You cannot use them as variable names. The keyword module lists them.
import keyword
print(len(keyword.kwlist), "keywords")
print(keyword.kwlist[:8])
print(keyword.iskeyword("for"))
print(keyword.iskeyword("total"))
Output
35 keywords
['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await']
True
False
Recent Python 3 versions have 35 keywords. You will learn most of them naturally as the course goes on.
| Group | Keywords |
|---|---|
| Values | True, False, None |
| Decisions | if, elif, else |
| Loops | for, while, break, continue, in |
| Logic | and, or, not, is |
| Functions and classes | def, return, lambda, class, yield, global, nonlocal |
| Errors | try, except, finally, raise, assert |
| Modules | import, from, as |
| Other | pass, del, with, async, await |
Common Syntax Errors and What They Mean
| Error message | Usual cause | Fix |
|---|---|---|
IndentationError: expected an indented block | Nothing indented after a line ending in : | Indent the next line by 4 spaces |
IndentationError: unexpected indent | A line is pushed in for no reason | Move it back to match the lines around it |
SyntaxError: expected ':' | Missing colon after if, for, def | Add : at the end of the line |
SyntaxError: unterminated string literal | A quote was opened but never closed | Add the matching closing quote |
NameError: name 'Print' is not defined | Wrong capital letter, or a typo | Check spelling and case |
SyntaxError: invalid syntax on a keyword | Using a keyword such as class as a variable name | Rename it, for example class_name |
Python points to the line where it got confused. The real mistake is often on the line just above, such as a bracket or quote left open.
Habits That Keep Code Readable
- Let your editor handle indentation; set it to insert 4 spaces.
- Leave one blank line between small sections of a program, and two before a function definition.
- Put spaces around operators:
total = price * qty, nottotal=price*qty. - Break long lines with brackets, not backslashes.
Practice Exercises
Exercise 1. This code fails. Find both mistakes.
marks = 85
if marks >= 80
print("A+ grade")
Show answer
The if line needs a colon, and the print() line must be indented:
marks = 85
if marks >= 80:
print("A+ grade")
Exercise 2. Print the sentence She said “Python is easy” with the double quotes showing.
Show answer
print('She said "Python is easy"')
Exercise 3. Is Total = 5 followed by print(total) correct? Why or why not?
Show answer
No. Python is case-sensitive, so total was never created. It raises NameError: name 'total' is not defined.
Frequently Asked Questions
Does Python need semicolons?
No. A new line ends a statement. Semicolons are allowed to put two statements on one line, but this is rarely used.
Can I use 2 spaces instead of 4?
Python accepts any consistent amount, but 4 spaces is the official style and what other programmers expect to see.
Is there any difference between single and double quotes?
No. 'hi' and "hi" create the same string. Choose whichever avoids escaping quotes inside the text.
What is PEP 8?
PEP 8 is Python’s official style guide. It covers indentation, line length, naming and spacing so that Python code looks similar everywhere.
Summary
- Each line is one statement; no semicolons needed.
- A line ending in
:starts a block; indent the block by 4 spaces. - Python is case-sensitive:
scoreandScorediffer. - Split long lines inside brackets.
- Single and double quotes are equal; triple quotes span lines.
- Keywords like
ifandclasscannot be variable names.
