Python indentation
Created By: chatGPT
Indentation in Python is crucial because it defines the structure of the code. Unlike many other programming languages that use curly braces or keywords to define blocks of code, Python uses indentation to determine the grouping of statements. This means that you must be consistent with your indentation levels to avoid syntax errors or unexpected behavior.
def greet(name):
print(f'Hello, {name}!')
if __name__ == '__main__':
greet('World')
In the example above, the function greet has its print statement indented with 4 spaces. This indicates that the print statement belongs to the
greet
function. Similarly, we have another block under the if __name__ == '__main__'
condition, also indented to show that it is part of that conditional statement.for i in range(5):
print(i)
if i == 2:
print('Reached 2!')
Note that mixing tabs and spaces for indentation can lead to errors, as Python does not allow this. It's recommended to consistently use either spaces (most common) or tabs throughout your code. The PEP 8 style guide suggests using 4 spaces per indentation level.
def add(a, b):
return a + b
result = add(5, 3)
print(result)
Understanding indentation is essential for writing clean and functional Python code. Always ensure you maintain the same type of indentation throughout your code to avoid confusion and errors. You can configure your text editor to visualize and replace tabs with spaces or adjust the settings to suit your preferred indentation method.
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
pass
class Dog(Animal):
def speak(self):
print(f'{self.name} says Woof!')