Python Syntax
Python Syntax
### 1. **Indentation**
Python uses indentation (whitespace) to define blocks of code instead of braces
`{}` (like in C or Java).
**Example:**
```python
if 5 > 2:
print("Five is greater than two!") # Indented block
```
❌ **Wrong Indentation:**
```python
if 5 > 2:
print("Five is greater than two!") # Error: expected an indented block
```
---
### 2. **Comments**
- Single-line comments start with `#`.
- Multi-line comments can be written using triple quotes (`'''` or `"""`), but
these are actually string literals (not true comments).
**Example:**
```python
# This is a single-line comment
"""
This is a multi-line
comment (technically a string).
"""
```
---
**Example:**
```python
x = 5 # Integer
name = "Alice" # String
is_valid = True # Boolean
```
---
---
### 5. **Operators**
- Arithmetic: `+`, `-`, `*`, `/`, `//` (floor division), `%` (modulus), `**`
(exponent)
- Comparison: `==`, `!=`, `>`, `<`, `>=`, `<=`
- Logical: `and`, `or`, `not`
**Example:**
```python
sum = 5 + 3 # 8
is_true = (5 > 3) # True
```
---
---
### 7. **Loops**
- `for` loop (iterates over sequences)
- `while` loop (executes while condition is `True`)
**Example:**
```python
# For loop
for i in range(3): # 0, 1, 2
print(i)
# While loop
count = 0
while count < 3:
print(count)
count += 1
```
---
### 8. **Functions**
Defined using `def` keyword.
**Example:**
```python
def greet(name):
return f"Hello, {name}!"
---
**Example:**
```python
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
```
---
**Example:**
```python
import math
print(math.sqrt(16)) # 4.0
```
---