- Understand Python's indentation rules and their importance
- Learn about Python's case sensitivity
- Master basic naming conventions following PEP 8
- Distinguish between statements and expressions
Python Syntax Basics
Every language has rules. Python's syntax is famous for being clean and readable - almost like writing in plain English. But there are still important rules you need to follow.
Once you understand these rules, they become second nature. Like learning to drive, the mechanics fade into the background and you focus on where you're going.
Let's explore the fundamental rules that govern how Python code is written.
Indentation: Python's Unique Feature
What is Indentation?
Indentation is the whitespace (spaces or tabs) at the beginning of a line. In most programming languages, indentation is optional and just for readability. In Python, indentation is mandatory and defines the structure of your code.
Why Indentation Matters in Python
Other Languages (Java, C++):
if (condition) {
// code block defined by braces
}
Python:
if condition:
# code block defined by INDENTATION
How Indentation Works
# Correct indentation
if True:
print("This is inside the if block")
print("This is also inside")
print("This is outside the if block")
# The indented lines belong to the if statement
# The unindented line is separate
Output:
This is inside the if block
This is also inside
This is outside the if block
Standard: 4 Spaces
Python's style guide (PEP 8) recommends 4 spaces for each indentation level:
# Good: 4 spaces per level
if condition:
if another_condition:
print("Nested code")
print("Same level")
print("Back one level")
print("Outside everything")
Common Indentation Errors
# WRONG: Inconsistent indentation
if True:
print("4 spaces")
print("2 spaces") # IndentationError!
# WRONG: Missing indentation
if True:
print("No indentation") # IndentationError!
# WRONG: Unexpected indentation
print("Hello")
print("Indented for no reason") # IndentationError!
# CORRECT: Consistent indentation
if True:
print("Properly indented")
print("Same level")
Tabs vs Spaces
| Aspect | Recommendation |
|---|---|
| What to use | Spaces (4 per level) |
| Why not tabs? | Tabs can display differently in different editors |
| Mixing? | Never mix tabs and spaces |
| Editor tip | Configure your editor to convert tabs to 4 spaces |
Most code editors can be configured to automatically insert 4 spaces when you press Tab.
Case Sensitivity
Python treats uppercase and lowercase letters as completely different. This applies to everything: variable names, function names, and keywords.
Examples of Case Sensitivity
# These are THREE different variables!
name = "Alice"
Name = "Bob"
NAME = "Charlie"
print(name) # Alice
print(Name) # Bob
print(NAME) # Charlie
# Same applies to functions
def greet():
print("Hello!")
def Greet():
print("Hi there!")
greet() # Hello!
Greet() # Hi there!
Keywords Must Be Lowercase
Python's reserved keywords are all lowercase:
# Correct
if True:
print("Works!")
for i in range(5):
print(i)
# Wrong - these will cause errors
If True: # NameError: name 'If' is not defined
print("Broken")
FOR i in range(5): # NameError
print(i)
Python Keywords (Reserved Words)
These words have special meaning and cannot be used as variable names:
False |
await |
else |
import |
pass |
None |
break |
except |
in |
raise |
True |
class |
finally |
is |
return |
and |
continue |
for |
lambda |
try |
as |
def |
from |
nonlocal |
while |
assert |
del |
global |
not |
with |
async |
elif |
if |
or |
yield |
# Cannot use keywords as variables
class = "Math" # SyntaxError
import = 5 # SyntaxError
if = "condition" # SyntaxError
# Use variations instead
class_name = "Math"
import_count = 5
if_condition = "condition"
Naming Conventions
Variable Naming Rules
| Rule | Example | Valid? |
|---|---|---|
| Start with letter or underscore | name, _count |
|
| Can contain letters, numbers, underscores | user_1, total_2024 |
|
| Cannot start with a number | 1st_place |
|
| Cannot contain special characters | my-var, user@name |
|
| Cannot be a keyword | class, for |
Python Naming Conventions (PEP 8)
# Variables and functions: snake_case
user_name = "Alice"
total_count = 100
def calculate_total():
pass
# Constants: UPPER_SNAKE_CASE
MAX_SIZE = 100
PI = 3.14159
DATABASE_URL = "localhost"
# Classes: PascalCase (CamelCase)
class UserProfile:
pass
class ShoppingCart:
pass
# Private variables: start with underscore
_internal_counter = 0
_helper_function = lambda x: x
# "Dunder" methods: double underscores
__init__
__str__
Good vs Bad Names
# BAD: Unclear, too short
x = 100
n = "John"
def f():
pass
# GOOD: Descriptive and clear
user_age = 100
customer_name = "John"
def calculate_discount():
pass
# BAD: Too long or complicated
the_total_number_of_items_in_the_shopping_cart = 5
# GOOD: Concise but clear
cart_item_count = 5
Statements and Expressions
What's a Statement?
A statement is an instruction that Python executes. It performs an action.
# Assignment statement
x = 10
# Print statement
print("Hello")
# If statement
if x > 5:
print("Big number")
# Import statement
import math
# Function definition statement
def greet():
print("Hi!")
What's an Expression?
An expression is code that produces (evaluates to) a value.
# These are expressions - they produce values
5 + 3 # produces 8
"Hello" + "!" # produces "Hello!"
len("Python") # produces 6
x > 5 # produces True or False
2 ** 10 # produces 1024
# Expressions can be assigned to variables
result = 5 + 3 # 8 is assigned to result
message = "Hi" + "!" # "Hi!" is assigned to message
Statements vs Expressions
Statements vs Expressions
STATEMENT: Does something
x = 10 # assigns a value
print("Hi") # prints output
if x > 5: # makes a decision
EXPRESSION: Produces a value
5 + 3 # produces 8
x > 5 # produces True/False
"Hello"[0] # produces "H"
KEY INSIGHT: Expressions can be part of statements!
x = 5 + 3 # Statement containing an expression
Expression
Line Length and Line Continuation
Recommended Line Length
PEP 8 recommends limiting lines to 79 characters (or 99 for less strict standards). This makes code easier to read, especially when comparing files side by side.
Breaking Long Lines
Method 1: Backslash ()
# Use backslash to continue a long line
total = first_number + second_number + third_number + \
fourth_number + fifth_number
# Long string
message = "This is a very long message that " + \
"spans multiple lines for readability"
Method 2: Parentheses (Preferred)
# Implicit continuation inside parentheses
total = (first_number + second_number + third_number +
fourth_number + fifth_number)
# Also works with brackets and braces
my_list = [
"item_one",
"item_two",
"item_three",
"item_four"
]
my_dict = {
"name": "Alice",
"age": 25,
"city": "Paris"
}
Method 3: Triple Quotes for Long Strings
long_text = """
This is a very long string
that spans multiple lines.
Each line is preserved exactly
as written, including newlines.
"""
Multiple Statements
One Statement Per Line (Recommended)
# Good: One statement per line
x = 5
y = 10
z = x + y
print(z)
Multiple Statements Per Line (Avoid if possible)
# Avoid: Multiple statements separated by semicolon
x = 5; y = 10; z = x + y; print(z)
# Only acceptable for very simple, related statements
a, b = 1, 2 # This is actually one statement (tuple unpacking)
Key Takeaways
Remember These Points
INDENTATION
• Use 4 spaces per level
• Indentation defines code blocks
• Never mix tabs and spaces
CASE SENSITIVITY
• 'Name' and 'name' are different
• Keywords are lowercase
NAMING
• Variables: snake_case
• Constants: UPPER_CASE
• Classes: PascalCase
CODE STRUCTURE
• One statement per line
• Keep lines under 79-99 characters
• Use parentheses for line continuation
What's Next
You've completed the "Getting Started with Python" module. You now understand:
- What Python is and why it's used
- How to install Python and set up your environment
- How to write and run your first programs
- The fundamental syntax rules that govern Python code
In the next module, we'll dive into Python Basics - learning about variables, data types, and operators. This is where you'll really start building programs.
Keep practicing. Every expert was once a beginner.
