Python Syntax
Python’s syntax is designed to be clean and easy to read. Let’s explore some fundamental aspects.
Indentation Matters
In Python, indentation isn’t just for readability—it’s part of the syntax. Blocks of code are defined by their
indentation level, typically using 4 spaces.
Example:
if 5 > 2:
print("Five is greater than two.")
print("This line is part of the if block.")
print("This line is outside the if block.")
Notes:
- Consistent indentation is crucial.
- Mixing tabs and spaces can lead to errors.
- The standard is 4 spaces per indentation level.
No Braces or Semicolons
Python does not use curly braces {}
to define code blocks or semicolons ;
to end statements.
Example:
# Correct in Python
def greet(name):
print(f"Hello, {name}!")
# Incorrect (this would cause an error)
def greet(name){
print(f"Hello, {name}!");
}
Case Sensitivity
Python is case-sensitive. This means Variable
and variable
are two different identifiers.
Example:
age = 25
Age = 30
print(age) # Outputs: 25
print(Age) # Outputs: 30
Dynamic Typing
You don’t need to declare variable types. Assigning a value to a variable declares and initializes it.
my_var = 10 # Integer
my_var = 'Ten' # Now it's a String