|
| Home |
|---|
Python syntax refers to the set of rules that determine how Python programs must be written and structured. Just as natural languages have grammar rules, Python has syntax rules that tell the Python interpreter how to understand and execute code.
Python syntax is designed to be relatively simple, readable and consistent. This is one of the reasons Python is widely used by beginners, students, developers, data scientists and software engineers.
Understanding Python syntax is essential before learning more advanced topics such as variables, operators, conditional statements, loops, functions, lists, dictionaries and object-oriented programming.
In this tutorial, you will learn the most important Python syntax rules, including Python statements, indentation, code blocks, comments, variables, expressions, operators, colons, parentheses, strings, case sensitivity, line continuation, functions, conditions, loops and common syntax errors.
Syntax is the set of rules that determines how code must be written so that a programming language can understand it.
For example, Python expects a function call to use parentheses:
print("Hello Python")
If Python syntax is written incorrectly, the interpreter may report a SyntaxError or another type of error.
Some important characteristics of Python syntax include:
: to introduce many code blocks.# symbol.if, for,
while and def to define program structures.A Python statement is an instruction that Python can execute. Python programs are made up of statements that perform actions such as assigning values, calling functions, importing modules and controlling program flow.
print("Hello Python")
Hello Python
The print() function displays the text on the screen.
The complete line is a Python statement.
name = "Alice"
age = 25
print(name)
print(age)
Alice
25
Each executable line performs a specific operation. The first two statements create variables and the final two statements display their values.
Indentation is one of the most important Python syntax rules. Python uses indentation to indicate which statements belong to a block of code.
Many programming languages use curly braces such as { } to
define blocks. Python instead uses whitespace at the beginning of a
line.
The standard convention is to use four spaces for each indentation level.
age = 20
if age > 18:
print("You are an adult")
You are an adult
The print() statement is indented, so Python knows that it
belongs to the if block.
age = 20
if age > 18:
print("You are an adult")
This code produces an IndentationError because the
statement belonging to the if block is not indented.
A code block is a group of statements that belong together. Python uses indentation to identify the statements inside a block.
Code blocks are commonly used with:
if, elif and elsefor loopswhile loopsdefclasstry, except and finallyscore = 85
if score >= 50:
print("Pass")
print("Well done")
Pass
Well done
Both print() statements have the same indentation, so both
belong to the if block.
A colon : is an important part of Python syntax. It is
normally used after a statement that introduces an indented block.
For example, an if statement uses a colon:
age = 20
if age >= 18:
print("Adult")
The colon tells Python that an indented block of code follows.
Colons are also commonly used with for,
while, def, class,
try, except, finally and
other compound statements.
Comments are notes written inside Python source code for human readers. Python ignores comments during normal program execution.
A Python single-line comment begins with the # symbol.
# This is a Python comment
print("Hello Python")
Hello Python
The comment does not affect the output of the program.
A comment can also appear after a statement.
age = 25 # Store the student age
print(age)
25
Python variables are created by assigning a value to a name using the
assignment operator =.
name = "Alice"
age = 25
print(name)
print(age)
Python does not normally require you to declare the data type of a variable before assigning a value.
The assignment operator = should not be confused with the
comparison operator ==.
An expression is code that Python evaluates to produce a value. Expressions can contain values, variables, operators and function calls.
x = 10
y = 5
result = x + y
print(result)
15
The expression x + y is evaluated and its result is
assigned to the variable result.
Python uses operators to perform calculations, comparisons, logical operations and assignments.
a = 10
b = 3
print(a + b)
print(a - b)
print(a * b)
print(a / b)
13
7
30
3.3333333333333335
Operators are an important part of Python expressions and are used throughout Python programs.
Functions are called by writing the function name followed by parentheses.
print("Hello Python")
The text inside the parentheses is passed as an argument to the
print() function.
A function can also receive multiple arguments.
name = "Alice"
age = 25
print(name, age)
Alice 25
Strings are sequences of text characters. Python allows strings to be written using single quotation marks or double quotation marks.
name = "Alice"
city = 'London'
print(name)
print(city)
Alice
London
Using matching quotation marks is an important Python syntax rule.
message = "Hello Python"
print(message)
An unmatched quotation mark can cause a SyntaxError.
Python is a case-sensitive programming language. This means uppercase and lowercase letters are treated as different.
name = "Alice"
Name = "Bob"
print(name)
print(Name)
Alice
Bob
The variables name and Name are different
because their capitalization is different.
Python contains reserved words called keywords. Keywords have special meanings in Python syntax and cannot normally be used as variable names.
Examples include:
ifelseforwhiledefclassreturnimportFor example, this is invalid:
if = 10
The word if is reserved for conditional statements.
Conditional statements allow a program to execute code only when a condition is true.
The basic Python if syntax is:
if condition:
statement
age = 20
if age >= 18:
print("You are an adult")
You are an adult
The colon and indentation are both important parts of the syntax.
Python can use if, elif and
else to test multiple conditions.
score = 75
if score >= 80:
print("Grade A")
elif score >= 60:
print("Grade B")
else:
print("Grade C")
Grade B
Each condition is followed by a colon, and the statements inside each block are indented.
A for loop is used to repeat a block of code for each item
in a sequence or iterable.
Basic syntax:
for variable in sequence:
statement
for number in range(3):
print(number)
0
1
2
The colon introduces the loop block and the indented statement belongs to that block.
A while loop repeatedly executes a block of code while a
condition remains true.
number = 1
while number <= 3:
print(number)
number += 1
1
2
3
Python functions are defined using the def keyword.
Basic syntax:
def function_name():
statement
def greet():
print("Hello Python")
greet()
Hello Python
The def keyword begins the function definition, the
parentheses contain parameters if required, and the colon introduces
the indented function body.
A function can accept values called parameters.
def greet(name):
print("Hello", name)
greet("Alice")
Hello Alice
The parameter name receives the value passed when the
function is called.
The return statement sends a value back from a function.
def add(a, b):
return a + b
result = add(5, 3)
print(result)
8
The import statement is used to make modules and their
functionality available to a Python program.
import math
print(math.sqrt(25))
5.0
Python includes many useful standard-library modules, and external packages can also be installed and imported when needed.
Python normally treats the end of a physical line as the end of a statement.
name = "Alice"
age = 25
print(name)
print(age)
Each statement is written on its own line, which contributes to the readability of Python code.
Python allows multiple simple statements to be separated by a semicolon, although this style is generally discouraged because separate lines are easier to read.
x = 10; y = 20
print(x)
print(y)
For normal Python programs, it is usually better to place separate statements on separate lines.
Long expressions can sometimes be split across multiple lines. Python naturally supports line continuation inside parentheses, brackets and braces.
total = (
10
+ 20
+ 30
)
print(total)
60
Using parentheses for long expressions generally produces cleaner code than relying on explicit line-continuation characters.
Lists are written using square brackets [ ]. Multiple
items are separated by commas.
fruits = ["apple", "banana", "cherry"]
print(fruits)
['apple', 'banana', 'cherry']
Dictionaries use curly braces { } and store information
as key-value pairs.
student = {
"name": "Alice",
"age": 20
}
print(student)
{'name': 'Alice', 'age': 20}
Dictionary keys and values are separated using a colon, while individual key-value pairs are separated by commas.
Python allows structures to be placed inside other structures. This is called nesting.
students = [
["Alice", 20],
["Bob", 22]
]
print(students[0][0])
Alice
Nested data structures are common in real Python programs, particularly when working with collections and data processing.
Whitespace is especially important in Python because indentation can change the meaning of a program.
Python generally recommends using four spaces for each indentation level. Consistent indentation makes code easier to read and helps prevent indentation errors.
Whitespace can also make expressions easier to understand.
total = price * quantity
average = total / students
Writing readable Python code is an important part of following good Python syntax and style practices.
A SyntaxError occurs when Python cannot understand the structure of the code according to its syntax rules.
Common causes include:
age = 20
if age >= 18
print("Adult")
The if statement is missing the required colon.
print("Hello Python"
The closing parenthesis is missing, so Python cannot correctly parse the function call.
Beginners sometimes confuse syntax errors with indentation errors. Both indicate problems in the structure of the program, but they are reported differently depending on the problem.
| Error | Common Cause |
|---|---|
SyntaxError |
Invalid Python syntax such as a missing colon or quotation mark |
IndentationError |
Incorrect or missing indentation |
TabError |
Inconsistent use of tabs and spaces |
Following good syntax and formatting practices makes Python programs easier to read, debug and maintain.
The following example combines variables, input, a calculation, conditional logic and formatted output.
name = input("Enter your name: ")
score = float(input("Enter your score: "))
if score >= 50:
result = "Pass"
else:
result = "Fail"
print(f"{name}: {result}")
Enter your name: Alice
Enter your score: 75
Alice: Pass
This example demonstrates several important Python syntax rules: variable assignment, function calls, type conversion, indentation, conditional statements, the colon and f-string formatting.
| Python Feature | Basic Syntax |
|---|---|
| Variable assignment | name = "Alice" |
| Output | print("Hello") |
| User input | name = input("Name: ") |
| Condition | if condition: |
| For loop | for item in items: |
| While loop | while condition: |
| Function | def function_name(): |
| Return value | return value |
| Comment | # comment |
| Import module | import module |
| List | [1, 2, 3] |
| Tuple | (1, 2, 3) |
| Dictionary | {"name": "Alice"} |
Python syntax is the collection of rules that determines how Python code must be written so that the Python interpreter can understand and execute it.
Python syntax is designed to be relatively readable and consistent, which makes it accessible to beginners. However, concepts such as indentation, code blocks, functions and exceptions still need to be learned carefully.
Indentation determines which statements belong to a particular code block. Python uses indentation instead of curly braces to structure many parts of a program.
The standard convention is four spaces for each indentation level. Consistency is important, and mixing tabs and spaces can cause problems.
Yes. Python is case-sensitive, so names such as name and
Name are treated as different.
A colon introduces an indented block in statements such as
if, for, while,
def and class.
A SyntaxError can occur when Python code violates the
language's syntax rules, such as when a quotation mark or closing
parenthesis is missing, a colon is omitted or a statement is written
incorrectly.
Syntax describes how Python code must be written, while semantics describe what that correctly written code means and does when it is executed.
Python syntax defines how Python programs are written and structured. Important Python syntax rules include indentation, statements, expressions, variables, operators, function calls, comments, keywords, colons and parentheses.
Python uses indentation to define code blocks, making correct whitespace an essential part of writing Python programs. The language is also case-sensitive, so uppercase and lowercase letters can change the meaning of names.
Understanding Python syntax provides the foundation for learning variables, data types, operators, conditions, loops, functions and other Python programming concepts.
Once you understand these basic syntax rules, you can begin writing Python programs that are easier to read, debug and maintain.
Continue learning Python with these related beginner tutorials:
Struggling with Python syntax, assignments or debugging errors? Learning alone can be frustrating.
Get 1-on-1 Python tutoring and learn faster with clear explanations, real examples and live help.
Home Tutorial Online Live Trainings Contact Us © 2026 All rights reserved by www.PythonTutor.net