Understanding Python Syntax
Python is a high-level, interpreted programming language known for its simplicity and readability. Its syntax emphasizes clarity, using indentation instead of braces or keywords to define blocks of code.
This guide will cover the core elements of Python syntax with examples to help you write clean and functional Python code.
1. Basic Structure and Indentation
Indentation
Python uses indentation (spaces or tabs) to define blocks of code. Unlike many other languages that use curly braces {}
, Python relies on consistent indentation levels.
Example:
if 5 > 2:
print("Five is greater than two!")
Here, the indented print
statement belongs to the if
block.
Key Point: Indentation must be consistent (commonly 4 spaces per level). Mixing tabs and spaces will raise errors.
2. Variables and Data Types
Python variables do not need explicit declaration to reserve memory space. The declaration happens automatically when you assign a value.
x = 5 # Integer
name = "Alice" # String
pi = 3.1415 # Float
is_active = True # Boolean
Python is dynamically typed — the type of the variable is inferred at runtime and can change.
x = 5
x = "Now I'm a string"
Common Data Types:
- int – Integer numbers (e.g., 3, -100)
- float – Floating-point numbers (e.g., 3.14)
- str – Strings (e.g., "hello")
- bool – Boolean values (
True
orFalse
) - list – Ordered, mutable collections (e.g.,
[1, 2, 3]
) - tuple – Ordered, immutable collections (e.g.,
(1, 2, 3)
) - dict – Key-value pairs (e.g.,
{"name": "Alice", "age": 25}
)
3. Comments
Comments are lines ignored by the Python interpreter and are used to explain code.
- Single-line comments start with
#
# This is a comment
print("Hello") # This prints Hello
- Multi-line comments are typically written using triple quotes
'''
or"""
, often used as docstrings.
"""
This is a
multi-line comment
"""
4. Python Statements and Expressions
- Statements are instructions executed by the interpreter (e.g., assignment, loops).
- Expressions compute values and return results.
Example:
a = 5 # Statement (assignment)
b = a + 3 # Expression inside assignment (a + 3)
print(b) # Statement
5. Operators
Arithmetic Operators
Operator | Description | Example |
---|---|---|
+ |
Addition | 3 + 2 → 5 |
- |
Subtraction | 5 - 1 → 4 |
* |
Multiplication | 4 * 2 → 8 |
/ |
Division (float) | 7 / 2 → 3.5 |
// |
Floor division | 7 // 2 → 3 |
% |
Modulus (remainder) | 7 % 2 → 1 |
** |
Exponentiation | 2 ** 3 → 8 |
Comparison Operators
Operator | Description | Example |
---|---|---|
== |
Equal to | 5 == 5 → True |
!= |
Not equal to | 5 != 3 → True |
> |
Greater than | 5 > 3 → True |
< |
Less than | 5 < 3 → False |
>= |
Greater or equal | 5 >= 5 → True |
<= |
Less or equal | 5 <= 3 → False |
Logical Operators
Operator | Description | Example |
---|---|---|
and |
Logical AND | True and False → False |
or |
Logical OR | True or False → True |
not |
Logical NOT | not True → False |
6. Control Flow: Conditional Statements
Python uses if
, elif
, and else
for branching.
age = 18
if age >= 18:
print("Adult")
elif age > 12:
print("Teenager")
else:
print("Child")
Indentation defines the blocks under each condition.
7. Loops
While Loop
Executes a block as long as a condition is true.
count = 0
while count < 5:
print(count)
count += 1
For Loop
Iterates over a sequence (like list, string, or range).
for i in range(5): # range(5) = 0 to 4
print(i)
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
8. Functions
Functions group code into reusable blocks.
Defining a Function
def greet(name):
print(f"Hello, {name}!")
Calling a Function
greet("Alice")
Return Values
Functions can return values:
def add(a, b):
return a + b
result = add(3, 4)
print(result) # Output: 7
9. Data Structures
Lists
Ordered, mutable collections.
numbers = [1, 2, 3, 4]
numbers.append(5)
print(numbers) # [1, 2, 3, 4, 5]
Access by index:
print(numbers[0]) # 1
Tuples
Ordered, immutable collections.
coords = (10, 20)
# coords[0] = 5 # This will raise an error
Dictionaries
Key-value pairs, unordered (Python 3.7+ maintains insertion order).
person = {"name": "Alice", "age": 25}
print(person["name"]) # Alice
person["age"] = 26 # Update
Sets
Unordered collections of unique elements.
myset = {1, 2, 3}
myset.add(2) # No duplicate added
print(myset) # {1, 2, 3}
10. Classes and Objects (Basic OOP)
Python supports Object-Oriented Programming.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def greet(self):
print(f"Hello, my name is {self.name} and I'm {self.age} years old.")
# Creating an object
p1 = Person("Alice", 30)
p1.greet()
11. Modules and Imports
You can organize code into modules (Python files) and import them.
# math_module.py
def add(a, b):
return a + b
Import and use:
import math_module
print(math_module.add(3, 4))
12. Exception Handling
Handle errors gracefully with try-except
blocks.
try:
num = int(input("Enter a number: "))
print(10 / num)
except ValueError:
print("That's not a valid number!")
except ZeroDivisionError:
print("Cannot divide by zero!")
13. File Handling
Reading and writing files is straightforward.
# Writing to a file
with open("file.txt", "w") as f:
f.write("Hello, world!")
# Reading from a file
with open("file.txt", "r") as f:
content = f.read()
print(content)
14. List Comprehensions
Concise way to create lists.
squares = [x**2 for x in range(5)]
print(squares) # [0, 1, 4, 9, 16]
evens = [x for x in range(10) if x % 2 == 0]
print(evens) # [0, 2, 4, 6, 8]
15. Lambda Functions (Anonymous Functions)
Small, unnamed functions useful for short operations.
add = lambda a, b: a + b
print(add(2, 3)) # 5
nums = [1, 2, 3, 4]
doubled = list(map(lambda x: x*2, nums))
print(doubled) # [2, 4, 6, 8]
16. Python Keywords and Identifiers
- Keywords are reserved words (like
if
,else
,for
,while
) and cannot be used as variable names. - Identifiers are names for variables, functions, classes, etc., and must start with a letter or underscore.
17. Indentation Errors and Syntax Errors
Python syntax errors occur if you violate rules such as missing colons, wrong indentation, or using reserved keywords improperly.
Example:
if True
print("Missing colon") # SyntaxError
Always end statements that introduce blocks with a colon (:
).
18. Useful Built-in Functions
print()
input()
len()
type()
range()
int()
,str()
,float()
help()
Example:
print(len("hello")) # 5
print(type(3.14)) # <class 'float'>
Summary
Python syntax is designed to be easy to read and write. Its main characteristics include:
- Use of indentation to define code blocks
- Dynamic typing without explicit declarations
- Clean and simple control flow statements
- Rich data structures like lists, dictionaries, and tuples
- Support for functional and object-oriented programming
- Straightforward exception handling and file operations
At Online Learner, we're on a mission to ignite a passion for learning and empower individuals to reach their full potential. Founded by a team of dedicated educators and industry experts, our platform is designed to provide accessible and engaging educational resources for learners of all ages and backgrounds.
Terms Disclaimer About Us Contact Us
Copyright 2023-2025 © All rights reserved.