Python is a high-level programming language with clean and straightforward syntax. Its readability and simplicity are some of the key features that make Python popular among developers.
Python syntax refers to the set of rules that define how Python programs are written and interpreted.
Case Sensitivity:
Python is case-sensitive. For example, Variable
and variable
are two different identifiers.
name = "Alice"
Name = "Bob"
print(name) # Outputs: Alice
print(Name) # Outputs: Bob
No Semicolons:
Unlike many programming languages, Python does not require semicolons (;
) to terminate a statement.
print("Hello, World!") # This is valid
Colons for Blocks:
Blocks of code start with a colon (:
) and are followed by an indented block.
if 10 > 5:
print("10 is greater than 5")
Dynamic Typing:
Python does not require explicit declaration of variable types. Variables can change their type dynamically.
x = 10 # Integer
x = "Python" # String
Indentation in Python is used to define the structure and hierarchy of the code. Unlike other programming languages, Python does not use braces ({}
) to define blocks of code. Instead, indentation is mandatory.
Consistent Indentation:
All statements within a block must have the same level of indentation.
if True:
print("This is valid")
print("This is part of the block")
IndentationError:
Inconsistent indentation will result in an error.
if True:
print("This is valid")
print("This will cause an error") # Inconsistent indentation
Default Indentation:
Python recommends using 4 spaces per indentation level.
for i in range(5):
print("Iteration:", i)
if i % 2 == 0:
print("Even number")
Output:
Iteration: 0
Even number
Iteration: 1
Iteration: 2
Even number
Iteration: 3
Iteration: 4
Even number
Objective: Write a Python program that demonstrates correct syntax and indentation.
Create a Program:
Write a script named syntax_and_indentation.py
.
Use Conditional Statements:
Write an if-else
block that checks if a number is positive, negative, or zero.
Example:
num = int(input("Enter a number: "))
if num > 0:
print("The number is positive.")
elif num < 0:
print("The number is negative.")
else:
print("The number is zero.")
Use Loops:
Add a for
loop to print numbers from 1 to 5 with proper indentation.
Example:
for i in range(1, 6):
print("Number:", i)
Check Syntax: Ensure all statements follow Python's syntax rules, and the indentation is consistent.
Follow PEP 8:
Use 4 spaces per indentation level as recommended by PEP 8.
Use Consistent Tools:
Use tools like linters or code formatters (e.g., black
or flake8
) to maintain consistent syntax and indentation.
Avoid Tabs:
Prefer spaces over tabs to avoid conflicts between different editors.
Understanding Python syntax and indentation is crucial for writing error-free and maintainable code. With this foundation, you're ready to explore more complex programming concepts!