Indentation Errors
Part of the Logic & Flow section of Coddy's Python journey — lesson 27 of 78.
In Python, proper indentation is crucial for defining the scope of blocks of code, such as loops, functions, and conditional statements. Incorrect indentation can lead to errors or unexpected behavior. These errors are known as IndentationError.
Correct Indentation:
if x > 5:
print("x is greater than 5")
else:
print("x is not greater than 5")Incorrect Indentation:
if x > 5:
print("x is greater than 5") # This will cause an IndentationError
else:
print("x is not greater than 5")In the incorrect example, the print statement inside the if block is not properly indented, which will result in an IndentationError. Consistent and correct indentation is essential for writing valid Python code.
Cheat sheet
Python uses indentation to define code blocks. Incorrect indentation causes IndentationError.
Correct indentation:
if x > 5:
print("x is greater than 5")
else:
print("x is not greater than 5")Incorrect indentation:
if x > 5:
print("x is greater than 5") # IndentationError
else:
print("x is not greater than 5")Try it yourself
This lesson doesn't include a code challenge.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Variables Exploration
ConstantsMultiple Variable AssignmentsSwapping VariablesPlaceholder VariablesRound NumbersList Casting4Contact Book Application
Display MenuAdd Contact7Sets Part 2
Mathematical Operations Part 1Mathematical Operations Part 2Recap - Treasure HuntSubsets and SupersetsIterating Over SetsRecap - Tournament Tracker2Dictionaries Part 1
What is a Dictionary?Creating a DictionaryAccessing ValuesModifying DictionariesRecap - Recipe Manager5Advanced Decision Making
Ternary OperatorMembership ChecksIdentity ChecksIndentation ErrorsRecap - Vacation Filter8Student Records Manager
Project OverviewAdd Student11Advanced Functions
Returning Multiple ValuesLambda Functions Part 1Lambda Functions Part 2Recap Challenge - Lambda SortRecursive Functions Part 1Recursive Functions Part 2Recap - Sum Nested List14Higher-Order Functions
The Map FunctionThe Filter FunctionRecap - Email ValidatorRecap - Number Processor3Dictionaries Part 2
Dictionary MethodsNested DictionariesChecking for KeysLooping Through DictionariesRecap - Frequency Counter9Advanced Data Aggregation
Using SumFinding Minimum and MaximumSorting Data EfficientlyRecap - Dictionary Sorter