What is Indentation and Why is it Important?
Indentation refers to spacing the beginning of a line of code to the right by a certain amount.
In most programming languages, indentation is encouraged to make the code look neat and organized. However, in Python, incorrect indentation can cause your program to throw errors, making it crucially important.
Code Blocks and Indentation
In programming, a Code Block refers to a group of lines that are executed together.
Code blocks are mainly used in functions, conditionals, loops, etc., grouping logically related code for execution.
While many languages use curly braces { } to define code blocks, Python uses indentation.
// Function to add a and b function add(a, b) { return a + b; }
# Function to add a and b def add(a, b): return a + b
How to Use Indentation
Indentation in Conditionals
if condition: print("Executed if the condition is true") # Indented else: print("Executed if the condition is false") # Indented
In the example above, if the if condition is true, the indented print statement will execute.
If there's a mistake in indentation, the program will not function as intended.
if condition: # No indentation, error occurs print("Executed if the condition is true.")
Indentation in Loops
for i in range(3): print(i) # Indented
In the example above, the for loop executes print statements for each value returned by range(3) from 0 to 2.
Without indentation on the print statement, the loop will not function correctly.
for i in range(3): print(i) # No indentation, error occurs
Indentation in Functions
def add(a, b): result = a + b # Indentation defines the function body return result # Indentation specifies the return value result = add(3, 5)
In the example above, the add function accepts two parameters (a, b) and returns their sum.
An argument is a value provided to a function to perform its task.
In the code, the function add receives 3 for a and 5 for b, and the variable result will store the returned value, which is 8.
Lessons in this chapter ยท Mastering the Basics
- 1. What is Programming?
- 2. What is Python and Why is it Popular?
- 3. Containers for Data, Variables
- 4. Data Types in Python
- 5. Operators for Performing Operations on Variables and Values
- 6. Fill-in-the-blank quiz
- 7. How to Talk to a Computer (Input and Output)
- 8. Various Ways to Output Values with the print Function
- 9. Escaping Special Characters
- 10. Converting Between Strings and Numbers
- 11. Reserved Words with Special Meaning, Keywords
- 12. What is Indentation and Why is it Important?
- 13. Multiple-choice quiz
- 14. Coding Quiz - Return Five Times the Given Number
In Python, a program can still run even if there are indentation errors.
Lecture
AI Tutor
Design
Upload
Notes
Favorites
Help