Python Syntax: A Beginner's Guide With Examples
Python syntax refers to the rules that determine how Python programs must be written so that the interpreter can understand and execute them.
Just as natural languages have grammatical rules, programming languages have rules for arranging instructions, defining expressions, using variables, and controlling program execution.
Python is known for its readable syntax. However, even small mistakes involving quotation marks, indentation, or spelling can cause errors.
In this tutorial, you will learn the fundamental rules of Python syntax with practical examples.
1. Writing Your First Python Statement
Let's begin with a simple program.
print("Hello, World!")
Output:
Hello, World!
This is a valid Python function call.
Python executes the statement and displays the specified message.
Unlike languages that require every instruction to end with a semicolon, Python generally uses a newline to separate statements.
2. Python Statements Usually End With a Newline
Consider the following example:
print("Welcome to Python")
print("Learn programming step by step")
print("Practice every day")
Output:
Welcome to Python
Learn programming step by step
Practice every day
Each statement appears on a separate line.
Python generally recognizes the end of a simple statement when the line ends, provided the statement has not been continued onto another line.
A semicolon is not required at the end of each statement.
Can Multiple Statements Appear on One Line?
Yes. Python allows multiple simple statements on one physical line when they are separated by semicolons.
For example:
x = 10; y = 20; print(x + y)
Output:
30
Although valid, placing unrelated statements on separate lines is usually more readable and is generally preferred.
3. Python Is Case-Sensitive
Python distinguishes between uppercase and lowercase letters in identifiers.
For example:
name = "Amit"
Name = "Priya"
print(name)
print(Name)
Output:
Amit
Priya
The identifiers name and Name refer to different variables.
However, Python's keywords must be written using their correct spelling and capitalization.
For example:
if 10 > 5:
print("Ten is greater than five")
The keyword if is lowercase.
Writing If instead of if will not produce the intended valid conditional statement.
4. Understanding Python Indentation
Indentation means adding spaces at the beginning of a line.
In Python, indentation is essential because it defines blocks of code.
Other languages may use curly brackets to mark a block, but Python normally uses indentation.
Example: Correct Indentation
if 10 > 5:
print("Ten is greater than five")
print("This statement belongs to the if block")
print("This statement is outside the if block")
Output:
Ten is greater than five
This statement belongs to the if block
This statement is outside the if block
The first two print() statements are indented under the if statement.
The final statement is not indented, so it executes after the conditional block.
Example: Incorrect Indentation
if 10 > 5:
print("Ten is greater than five")
This code produces an IndentationError because the body of the if statement is not indented.
How Many Spaces Should You Use?
Four spaces per indentation level is the standard recommendation for Python code.
Example:
if 20 > 10:
print("Level 1")
if 15 > 5:
print("Level 2")
The inner if statement is nested inside the outer block.
Consistent indentation improves readability and helps prevent errors.
5. Python Comments
Comments are notes written in source code to explain its purpose.
Python ignores comments when executing a program.
A single-line comment begins with the # character.
Example: Single-Line Comment
# Display a welcome message
print("Welcome to Python")
Output:
Welcome to Python
The comment explains the purpose of the following statement.
Example: Comments for Calculations
# Store the product price
price = 500
# Store the discount amount
discount = 50
# Calculate the final price
final_price = price - discount
print(final_price)
Output:
450
Comments can make a program easier to understand, especially when calculations or business rules become more complex.
Multiple-Line Explanations
You can write a comment across multiple lines by beginning each line with #.
# This program calculates the total price
# of two products and displays the result.
price1 = 100
price2 = 200
print(price1 + price2)
Output:
300
Python also supports multiline string literals using triple quotation marks. However, these are string literals, not a dedicated multiline comment syntax. Triple-quoted strings are commonly used for docstrings when placed appropriately in modules, classes, and functions.
6. Python Variables
Variables are names used to refer to values.
You can assign a value to a variable using the assignment operator =.
Example
name = "Ravi"
age = 22
percentage = 85.5
print(name)
print(age)
print(percentage)
Output:
Ravi
22
85.5
Python does not require you to declare the variable's type explicitly in these assignments.
The values determine the types of the objects referenced by the variables.
Rules for Naming Variables
Python identifiers follow specific rules:
-
A name can contain letters, digits, and underscores.
-
A name cannot begin with a digit.
-
Spaces are not allowed in an identifier.
-
Python keywords cannot be used as ordinary identifiers.
-
Identifiers are case-sensitive.
Examples of valid names:
student_name = "Amit"
age = 21
total_marks = 450
Examples of invalid names:
# Invalid: starts with a digit
# 1student = "Amit"
# Invalid: contains a space
# student name = "Amit"
The invalid lines are commented out so that the example itself remains executable.
For readability, Python programmers commonly use snake_case for variable and function names.
7. Python Strings and Quotation Marks
Strings represent text.
Python supports single quotes and double quotes for ordinary string literals.
Example
first_name = 'Amit'
last_name = "Sharma"
print(first_name)
print(last_name)
Output:
Amit
Sharma
Both quotation styles are valid.
However, the opening and closing quotation marks must match.
Example: Incorrect String
# Incorrect
# print("Hello, World!)
The closing quotation mark is missing.
Correct version:
print("Hello, World!")
Output:
Hello, World!
8. Python Uses Indentation for Conditional Blocks
Let's look at a practical example using an if...else statement.
marks = 75
if marks >= 40:
print("Result: Pass")
else:
print("Result: Fail")
Output:
Result: Pass
The program checks whether the marks are greater than or equal to 40.
-
If the condition is true, the first block executes.
-
Otherwise, the
elseblock executes.
The indentation determines which statements belong to each block.
9. Continuing a Python Statement Across Multiple Lines
Python supports implicit and explicit line continuation.
Implicit Line Continuation
When an expression is enclosed in parentheses, brackets, or braces, it can usually continue across multiple lines.
Example:
total = (
100
+ 200
+ 300
)
print(total)
Output:
600
This style is useful for long expressions and collections.
Explicit Line Continuation
A backslash can be used to continue a statement across physical lines.
total = 100 + 200 + \
300 + 400
print(total)
Output:
1000
Use explicit backslash continuation carefully. Implicit continuation inside parentheses is generally easier to maintain.
10. Python Syntax Errors
A syntax error occurs when Python cannot parse code according to its language rules.
Example 1: Missing Parenthesis
Incorrect:
# print("Hello, World!"
Correct:
print("Hello, World!")
Example 2: Incorrect Indentation
Incorrect:
# if True:
# print("Hello")
Correct:
if True:
print("Hello")
Example 3: Incorrect Keyword Capitalization
Incorrect:
# IF True:
# print("Hello")
Correct:
if True:
print("Hello")
When debugging syntax errors, check quotation marks, parentheses, colons, indentation, and keyword spelling.
Python Syntax: Quick Reference
Next: Python Statements | EDUNAVO
Conclusion
Python syntax provides the basic rules needed to write valid programs.
Understanding statements, indentation, comments, variables, quotation marks, and case sensitivity will help you avoid common beginner errors.
Practice writing small programs and intentionally correcting syntax mistakes to become more comfortable with Python.