Python Syntax
What is Python Syntax?
Python syntax refers to the set of rules that define how a Python program is written and interpreted. Python has clean and readable syntax, which emphasizes indentation over braces or semicolons.
1. Execute Python Syntax
Python syntax can be executed in several ways:
Example 1: Executing Directly in Interactive Mode (REPL)
print("Hello, World!")
Output:
Hello, World!This line uses the built-in print() function to output text.
Example 2: Saving in a .py file
Code (hello.py):
print("Welcome to Python!")
To execute:
python hello.py
Output:
Welcome to Python!
2. Python Indentation
Indentation is mandatory in Python and is used to define blocks of code (like loops, functions, and conditionals). It usually consists of 4 spaces or 1 tab.
Incorrect Indentation (This will raise an error):
if 5 > 2:
print("Five is greater than two!")
Output:
IndentationError: expected an indented block
Correct Indentation:
if 5 > 2:
print("Five is greater than two!")
Output:
Five is greater than two!
Example: Indentation in a Function
def greet(name):
print("Hello", name)
print("Welcome to Python!")
greet("Alice")
Output:
Hello Alice Welcome to Python!
Example: Indentation in Loops
for i in range(3):
print("Iteration:", i)
print("Inside loop")
print("Outside loop")
Output:
Iteration: 0 Inside loop Iteration: 1 Inside loop Iteration: 2 Inside loop Outside loop
Summary of Python Syntax Rules:
Syntax Element | Rule |
---|---|
Indentation | Required to define code blocks. |
Colons (:) | Used to start an indented block (e.g., in if, for, def). |
Case-Sensitive | Print is different from print. |
Comments | Use # for single-line comments. |
Statements | End without a semicolon (;), but you can use one optionally. |